data-engineering

Data Engineering Design Patterns: Upserts with MERGE

published
reading
21 min
tags
data-engineering, etl, merge, upsert, postgres, delta-lake, spark, series
On this page
  1. The Failure
  2. The Companion Code
  3. The Data
  4. The Variant That Breaks: Separate Update and Insert
  5. The Pattern: One Event per Key, Then a Guarded MERGE
  6. The Variant That Breaks: MERGE With the Raw Batch
  7. The Variant That Breaks: No Guard
  8. The Variant That Breaks: The Timestamp Instead of the Sequence
  9. Delta Lake
  10. Side by Side
  11. Checks Worth Keeping
  12. What Is Next
  13. Summary to Save

This is part 4 of the data engineering design patterns series. Part 3 loaded history through the daily pipeline, and every source row in it was written once and never changed. This part is about rows that change after they have been loaded.

A card transaction is authorised, and a day or two later it settles, sometimes for a different amount. The source writes the settlement as a new event with a later timestamp, so it falls into a later day's interval. The target has to replace the transaction's row by its key, wherever that row was first loaded. That is an upsert, and SQL's statement for it is MERGE.

My position is that a MERGE is only as correct as the batch it is handed. Reduce the batch to one row per key yourself, by the source's own sequence number, and write the rule "only a later event replaces a row" into the MERGE where anyone can read it. This post shows part 3's load failing on changing rows, two ways of splitting the upsert into separate steps, the pattern, and three versions of it that are each missing one piece.

#The Failure

The pipeline from part 3 runs once a day. It reads the events of its day, deletes the rows whose event_at falls in that day, and inserts what it read, in one transaction. Reruns are safe, and nothing is ever counted twice within a day's slice.

T-01 is authorised for 120.00 at 09:15 on 1 October. The 1 October run loads it. At 08:00 on 2 October it settles for 126.00, with a tip. The 2 October run reads the settlement and inserts it, because it belongs to 2 October. The authorisation is in 1 October's slice, which the 2 October run does not touch.

After five daily runs:

StepSource eventsExpected rowsTarget rowsDuplicated txn_idTarget totalExpected total
1 October545T-03385.00305.00
2 October858T-01, T-02, T-03756.00511.00
5 October18918Eight of the nine transactions1619.90744.90

The table holds every version of every transaction, and the total is more than twice what customers spent. Every run succeeded and every rerun was idempotent. Part 3's load is correct for the thing it was built for: rows that belong to exactly one day. A transaction that changes belongs to its key, not to a day.

#The Companion Code

Everything below comes from data-engineering-design-patterns, part 4. It uses the same Docker setup as the earlier parts: Postgres 16 in one container, and Python 3.11 with Spark 3.5 and Delta Lake 3.2 in another. From the part's folder:

bash
docker compose build
docker compose up -d postgres
docker compose run --rm lab python postgres_loads.py
docker compose run --rm lab python delta_loads.py
docker compose run --rm lab python -m unittest -v test_upserts_merge

Each scenario starts with an empty source and target and runs the five days from 1 to 5 October. After every step it writes the whole target to out/<engine>/<scenario>/ as a CSV, and its report compares the target with the expected table: one row per transaction, holding its latest event among those the source has committed so far. The report lists transactions that are missing, duplicated, or present once but not at their latest event. The reports used in this post are in example-results.

#The Data

The source is one Postgres table, src_transaction_events. Every event is a full copy of the transaction as it stood, not a change to apply, and event_seq is the order the source committed them in.

event_seqtxn_idStatusAmountevent_atWhat it shows
1T-01Authorised120.001 Oct 09:15
3, 4T-03Authorised, settled80.001 Oct 12:00, 18:00Two events for one key in one day
6T-01Settled126.002 Oct 08:00A tip, a day after the first load
9T-04Settled62.403 Oct 07:30A currency conversion
10, 12T-05Authorised, settled230.00, 236.503 Oct 09:00, 16:45A hotel: two events in one day for a key the target already holds
14, 15T-07Authorised, settled15.004 Oct 12:30, 12:30Captured in the same second

There are 18 events for nine transactions in all. The rest are plain authorisations and settlements on the following day. Eight of the nine transactions change on a later day than the one they first appear in.

The read is part 2's half-open interval read on event_at, unchanged. Only the write changes in this post.

#The Variant That Breaks: Separate Update and Insert

An upsert is an update for the keys the target has and an insert for the rest. Before MERGE, and in many pipelines since, it is written as two statements:

sql
update fact_transactions t
set status = b.status, amount = b.amount, event_at = b.event_at, event_seq = b.event_seq, loaded_at = now()
from batch b
where t.txn_id = b.txn_id;
 
insert into fact_transactions (txn_id, account_id, status, amount, event_at, event_seq, loaded_at)
select b.txn_id, b.account_id, b.status, b.amount, b.event_at, b.event_seq, now()
from batch b
where not exists (select 1 from fact_transactions t where t.txn_id = b.txn_id);

It breaks in two different ways, depending on what surrounds it.

#Two Commits

In the first scenario the batch is reduced to one event per transaction, and the two statements run in separate transactions. The 4 October run dies after the update commits:

StepRun outcomeTarget rowsMissing from targetTarget totalExpected total
3 Octoberok6none584.90584.90
4 October, crash between commitsCrashed after the update committed 1 row6T-07, T-08584.90689.90
Retry 4 Octoberok8none689.90689.90

The retry repairs it, because both statements are safe to run again. But between the crash and the retry the table is half of a run: T-06 shows as settled, and the two transactions that should have been inserted are not there. Anyone who reads it then gets a total 105.00 short, with no sign that anything is wrong. Part 1 made the same point about a delete and an insert in separate commits. Only the statements have changed.

#The Batch as It Arrived

The second scenario puts both statements in one transaction, which fixes the crash, but stages every event of the day as it arrived. To show what the batch's order does, the five days are loaded twice from empty, once with the rows staged in event_seq order and once with the same rows reversed:

StepTarget rowsDuplicated txn_idNot the latest eventTarget totalExpected total
1 October, event_seq order5T-03none385.00305.00
5 October, event_seq order11T-03, T-07T-05833.40744.90
5 October, reverse order11T-03, T-07none839.90744.90

Two things go wrong, and neither raises an error.

T-03 is authorised and settled on 1 October, and the target has never seen it. Both of its events pass the insert's not exists check, because the check looks at the target, not at the rest of the batch. It is inserted twice. T-07 does the same on 4 October.

T-05 is already in the target when its two 3 October events arrive. The update joins one target row to two batch rows, and Postgres applies one of them. Its documentation says which one is not predictable. Here, staged in event_seq order, the update kept the authorisation for 230.00. Staged in reverse, it kept the settlement for 236.50. The same rows, loaded by the same code, produced two different tables, and the only difference was the order of an unsorted batch.

#The Pattern: One Event per Key, Then a Guarded MERGE

The pattern has three pieces, and each one answers one of the failures above.

One statement. MERGE does the update and the insert in a single statement, so there is no moment between them for a crash or a reader.

One event per key, by the source's sequence. The batch is reduced before it reaches the database, in my own code, by keeping each transaction's event with the highest event_seq:

python
def latest_per_key_by_seq(rows):
    latest = {}
    for row in rows:
        kept = latest.get(row["txn_id"])
        if kept is None or row["event_seq"] > kept["event_seq"]:
            latest[row["txn_id"]] = row
    return sorted(latest.values(), key=lambda r: r["event_seq"])

Two events never share an event_seq, so the choice never depends on the order the rows arrived in.

A guard on the update. A matched row is replaced only by a later event of the same transaction:

sql
merge into fact_transactions t
using batch b
on t.txn_id = b.txn_id
when matched and b.event_seq > t.event_seq then
    update set account_id = b.account_id,
               status     = b.status,
               amount     = b.amount,
               event_at   = b.event_at,
               event_seq  = b.event_seq,
               loaded_at  = now()
when not matched then
    insert (txn_id, account_id, status, amount, event_at, event_seq, loaded_at)
    values (b.txn_id, b.account_id, b.status, b.amount, b.event_at, b.event_seq, now());

After the five days, 1 October is rerun, and then all five days again:

StepPipeline runs so farRows writtenTarget rowsTarget totalMatches expected
1 October144305.00yes
2 October235511.00yes
3 October336584.90yes
4 October438689.90yes
5 October529744.90yes
Rerun 1 October609744.90yes
Rerun 1 to 5 October1109744.90yes

Every step matches. The reruns write nothing at all, because every event they hand the MERGE is older than or equal to the row it would replace. That is a stronger kind of idempotence than part 1's: the rerun does not rewrite the same rows, it leaves them alone.

The next three scenarios each drop one piece.

#The Variant That Breaks: MERGE With the Raw Batch

Here the MERGE keeps its guard, but it is handed every event of the day as it arrived:

StepRun outcomeTarget rowsMissing from targetDuplicated txn_idNot the latest event
1 Octoberok5noneT-03none
2 Octoberok6noneT-03none
3 OctoberFailed: CardinalityViolation6T-06T-03T-04, T-05
Retry 3 OctoberFailed: CardinalityViolation6T-06T-03T-04, T-05

The MERGE is stricter than the separate update. On 3 October, T-05's two events both match its one target row, and Postgres refuses to update a row twice in one statement. The whole statement rolls back, which is correct, and the retry fails the same way, because the batch has not changed. The pipeline is stuck until someone changes the code.

What it does not catch is worse. On 1 October, T-03 was not in the target, so both of its events went to when not matched and were inserted. The check only applies to rows that match. MERGE refuses two updates to one row, and allows two inserts of one key.

With a primary key on txn_id, the same load fails on its very first run, with a UniqueViolation, and leaves the target empty. That is the better outcome: the bug shows on day one instead of day three, and nothing wrong is ever written. A key constraint does not replace the reduction to one event per key, but it turns a silent duplicate into a failed run.

#The Variant That Breaks: No Guard

This MERGE gets one event per key, and updates every match:

StepRows writtenNot the latest eventTarget totalExpected total
5 October2none744.90744.90
Rerun 1 October4T-01, T-02, T-04736.50744.90

Up to 5 October it is indistinguishable from the pattern. Then 1 October is rerun, as part 3 said every past day eventually is. Its batch holds the authorisations of T-01, T-02 and T-04, and the MERGE writes them over the settlements. T-01 is back to 120.00 and authorised, three days after it settled for 126.00.

The run succeeded, the row count did not change, and no key is duplicated. Only the amounts and statuses have gone back in time. Without the guard, a MERGE is only correct if the days are always run in order, and a rerun is by definition out of order.

#The Variant That Breaks: The Timestamp Instead of the Sequence

The last scenario is the pattern with event_at in place of event_seq, both to pick one event per key and in the guard. It looks like the same thing. A later event has a later timestamp.

StepNot the latest eventTarget totalExpected totalMatches expected
3 Octobernone584.90584.90yes
4 OctoberT-07689.90689.90no
5 OctoberT-07744.90744.90no
Rerun 1 to 5 OctoberT-07744.90744.90no

T-07 is authorised and captured in the same second, 12:30 on 4 October. With a tie on event_at, the reduction keeps whichever event it saw first, which is the authorisation. The guard is b.event_at > t.event_at, so the settlement can never replace it, and the rerun leaves it authorised for good.

The totals match, because the two events carry the same 15.00. A check on row counts and totals passes this table. Only a check on the status finds it, and only if someone thinks to write one.

A timestamp is a property of the event, set by whichever clock wrote it. A sequence is the order the source committed the events in. Two events can share a timestamp, at any precision. Only the sequence is guaranteed to have one answer to "which came later".

#Delta Lake

On Delta Lake the source stays in Postgres and the target is a Delta table. The pattern is the same reduction in Python, then Delta's merge builder with the guard as the matched condition:

python
(
    DeltaTable.forPath(spark, path)
    .alias("t")
    .merge(batch.alias("b"), "t.txn_id = b.txn_id")
    .whenMatchedUpdateAll(condition="b.event_seq > t.event_seq")
    .whenNotMatchedInsertAll()
    .execute()
)

The results match Postgres where the scenarios are the same. Part 3's replaceWhere load ends with the same 18 rows and the same eight duplicated transactions. The guarded MERGE with one event per key matches at every step. With the raw batch, T-03 is inserted twice on 1 October without complaint, and 3 October fails with DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE, on the first attempt and on the retry. The MERGE with no guard puts T-01, T-02 and T-04 back to their authorisations when 1 October is rerun. Three things differ.

#Separate Steps Become a Delete and an Append

Delta has no update with a join, so the separate-steps version deletes the batch's keys and appends the batch, as two commits. The crash on 4 October lands between them:

StepRun outcomeTarget rowsMissing from targetTarget totalExpected total
3 Octoberok6none584.90584.90
4 October, crash between commitsCrashed after the delete committed5T-06, T-07, T-08549.90689.90
Retry 4 Octoberok8none689.90689.90

On Postgres the crash left the new keys missing. Here it also removes T-06, which the table already held. Its row was deleted, and the append that would have put the settled version back never ran. The retry repairs it, but between the two the table has lost a transaction it had yesterday.

#dropDuplicates Is Not a Reduction by Sequence

Spark's dropDuplicates(["txn_id"]) is the obvious way to get one row per key, and it does: no key is ever duplicated. Which row it keeps is another matter. The scenario hands it the same events twice, in event_seq order and reversed, followed by the guarded MERGE:

StepDuplicated txn_idNot the latest eventTarget totalExpected total
5 October, event_seq ordernoneT-03, T-05, T-07738.40744.90
5 October, reverse ordernonenone744.90744.90

In this run it kept the first row it met for each key. With the batch in the order the source committed it, that was the authorisation every time. Spark does not promise even that much: the row it keeps depends on how the data is partitioned and ordered when the operation runs. The guard cannot catch this, because the authorisation of T-05 on 3 October is still later than the row it replaced. One row per key is not enough. It has to be the right row, chosen by a rule you wrote.

#A Rerun That Writes Nothing Still Commits

On Postgres, the guarded reruns reported 0 rows written. Delta's commit history for the same scenario:

VersionRunFiles addedFiles removedRows insertedRows updated
11 October1040
22 October1112
55 October1111
6Rerun 1 October1100
7 to 11Rerun 1 to 5 October1 each1 each00

Every rerun is a commit that removes the data file and adds a new one, with no row inserted or updated. The join found keys that matched, so Delta rewrote the file that held them, even though the guard stopped every update. Here the table is one small file. On a large table, a rerun of one day rewrites every file that holds any key from that day, and that day's transactions can be spread across the whole table. The data comes out right. The cost of the rerun does not shrink to match.

#Side by Side

LoadTwo events for a new keyTwo events for a known keyCrash mid-runRerun an old daySame-second events
Part 3's day replacementBoth keptEvery version keptSafeSafe, still wrongBoth kept
Update then insert, two commitsOne keptLatest keptHalf a run visible; on Delta a loaded key is deletedSafeLatest kept
Update then insert, raw batch (Postgres)Inserted twiceArbitrary event keptSafeSafeInserted twice
dropDuplicates, then guarded MERGE (Delta)Whichever row came firstWhichever row came firstSafeNot runWhichever row came first
Guarded MERGE, one event per keyOne keptLatest keptSafeNo rows change; on Delta, one commit and a file rewriteLatest kept
Guarded MERGE, raw batchInserted twiceRun fails, and keeps failingSafeNot reachedNot reached
MERGE with no guardOne keptLatest keptSafeRows go back in timeLatest kept
Guarded MERGE on event_at (Postgres)One keptLatest keptSafeNo rows changeEarlier event kept for good

Only one row is clean in every column, and it is the one where the batch was reduced by the sequence and the guard was written into the statement. On both engines the same scenarios fail in the same way. The engine changes what a failure costs, not whether it happens.

#Checks Worth Keeping

The companion code's tests state the claims above as assertions:

  • Part 3's day replacement leaves eight of the nine transactions duplicated after five days.
  • An update and an insert in separate commits lose T-07 and T-08 when the run dies between them, and a retry repairs it.
  • An update and an insert with the raw batch insert T-03 and T-07 twice, and the final total depends on the batch's order.
  • The guarded MERGE with one event per key matches the expected table after every run and rerun, and its reruns write no rows.
  • The guarded MERGE with the raw batch inserts T-03 twice, then fails on 3 October with a cardinality violation, and fails again on retry.
  • With a primary key, the same load fails on 1 October and writes nothing.
  • A MERGE with no guard puts T-01, T-02 and T-04 back to their authorisations when 1 October is rerun.
  • Ordering by event_at leaves T-07 authorised from 4 October onwards, through a full rerun.
  • On Delta, a crash between the delete and the append removes T-06, which the table already held, as well as the two new keys.
  • On Delta, dropDuplicates leaves T-03, T-05 and T-07 at their authorisations when the batch is in event_seq order, and gets every row right when it is reversed.
  • On Delta, the guarded MERGE reaches six commits after five days and twelve after six reruns that change no rows, and a failed MERGE adds no commit.

The check I would add to a real pipeline is a uniqueness check on the target's key after every run: select txn_id from fact_transactions group by txn_id having count(*) > 1 should return nothing. It catches part 3's load, both raw-batch inserts, and the bug that MERGE does not refuse. Where the engine allows it, make it a primary key and let the database run the check. The T-07 case needs a second one, comparing each key's event_seq in the target with the source's highest. Part 14 covers reconciliation.

#What Is Next

Every write in this post touched individual rows by key. Many targets are partitioned by day or month and rewritten one partition at a time. Part 5 is partition overwrite: replacing only the partitions a run produced, and the static overwrite setting that wipes every partition it did not touch.

#Summary to Save

  • A row that changes after it is loaded belongs to its key, not to a day. A load that replaces a day's slice keeps every version.
  • An update and an insert in separate commits let a crash or a reader see half a run. Put the write in one statement or one transaction.
  • Two events for one key in one batch break every form of upsert. The insert's not exists check inserts a new key twice, an update with a join applies an unpredictable one, and MERGE fails on a known key and inserts a new key twice.
  • Reduce the batch to one event per key in your own code, before the write, by the source's sequence number. dropDuplicates gives one row per key, but not the right one.
  • Guard the update so that only a later event replaces a row. Without the guard, rerunning an old day writes old values over new ones.
  • Use the source's commit sequence, not a timestamp, to decide which event is later. Two events can share a timestamp, and the tie is decided by whichever row arrived first.
  • A primary key on the target turns a duplicate insert into a failed run. A uniqueness check after every run does the same where the engine has no constraint.
  • On Delta Lake, a guarded rerun changes no rows but still commits and rewrites every file that holds a matched key.
Share

Related