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:
| Step | Source events | Expected rows | Target rows | Duplicated txn_id | Target total | Expected total |
|---|---|---|---|---|---|---|
| 1 October | 5 | 4 | 5 | T-03 | 385.00 | 305.00 |
| 2 October | 8 | 5 | 8 | T-01, T-02, T-03 | 756.00 | 511.00 |
| 5 October | 18 | 9 | 18 | Eight of the nine transactions | 1619.90 | 744.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:
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_mergeEach 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_seq | txn_id | Status | Amount | event_at | What it shows |
|---|---|---|---|---|---|
| 1 | T-01 | Authorised | 120.00 | 1 Oct 09:15 | |
| 3, 4 | T-03 | Authorised, settled | 80.00 | 1 Oct 12:00, 18:00 | Two events for one key in one day |
| 6 | T-01 | Settled | 126.00 | 2 Oct 08:00 | A tip, a day after the first load |
| 9 | T-04 | Settled | 62.40 | 3 Oct 07:30 | A currency conversion |
| 10, 12 | T-05 | Authorised, settled | 230.00, 236.50 | 3 Oct 09:00, 16:45 | A hotel: two events in one day for a key the target already holds |
| 14, 15 | T-07 | Authorised, settled | 15.00 | 4 Oct 12:30, 12:30 | Captured 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:
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:
| Step | Run outcome | Target rows | Missing from target | Target total | Expected total |
|---|---|---|---|---|---|
| 3 October | ok | 6 | none | 584.90 | 584.90 |
| 4 October, crash between commits | Crashed after the update committed 1 row | 6 | T-07, T-08 | 584.90 | 689.90 |
| Retry 4 October | ok | 8 | none | 689.90 | 689.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:
| Step | Target rows | Duplicated txn_id | Not the latest event | Target total | Expected total |
|---|---|---|---|---|---|
1 October, event_seq order | 5 | T-03 | none | 385.00 | 305.00 |
5 October, event_seq order | 11 | T-03, T-07 | T-05 | 833.40 | 744.90 |
| 5 October, reverse order | 11 | T-03, T-07 | none | 839.90 | 744.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:
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:
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:
| Step | Pipeline runs so far | Rows written | Target rows | Target total | Matches expected |
|---|---|---|---|---|---|
| 1 October | 1 | 4 | 4 | 305.00 | yes |
| 2 October | 2 | 3 | 5 | 511.00 | yes |
| 3 October | 3 | 3 | 6 | 584.90 | yes |
| 4 October | 4 | 3 | 8 | 689.90 | yes |
| 5 October | 5 | 2 | 9 | 744.90 | yes |
| Rerun 1 October | 6 | 0 | 9 | 744.90 | yes |
| Rerun 1 to 5 October | 11 | 0 | 9 | 744.90 | yes |
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:
| Step | Run outcome | Target rows | Missing from target | Duplicated txn_id | Not the latest event |
|---|---|---|---|---|---|
| 1 October | ok | 5 | none | T-03 | none |
| 2 October | ok | 6 | none | T-03 | none |
| 3 October | Failed: CardinalityViolation | 6 | T-06 | T-03 | T-04, T-05 |
| Retry 3 October | Failed: CardinalityViolation | 6 | T-06 | T-03 | T-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:
| Step | Rows written | Not the latest event | Target total | Expected total |
|---|---|---|---|---|
| 5 October | 2 | none | 744.90 | 744.90 |
| Rerun 1 October | 4 | T-01, T-02, T-04 | 736.50 | 744.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.
| Step | Not the latest event | Target total | Expected total | Matches expected |
|---|---|---|---|---|
| 3 October | none | 584.90 | 584.90 | yes |
| 4 October | T-07 | 689.90 | 689.90 | no |
| 5 October | T-07 | 744.90 | 744.90 | no |
| Rerun 1 to 5 October | T-07 | 744.90 | 744.90 | no |
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:
(
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:
| Step | Run outcome | Target rows | Missing from target | Target total | Expected total |
|---|---|---|---|---|---|
| 3 October | ok | 6 | none | 584.90 | 584.90 |
| 4 October, crash between commits | Crashed after the delete committed | 5 | T-06, T-07, T-08 | 549.90 | 689.90 |
| Retry 4 October | ok | 8 | none | 689.90 | 689.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:
| Step | Duplicated txn_id | Not the latest event | Target total | Expected total |
|---|---|---|---|---|
5 October, event_seq order | none | T-03, T-05, T-07 | 738.40 | 744.90 |
| 5 October, reverse order | none | none | 744.90 | 744.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:
| Version | Run | Files added | Files removed | Rows inserted | Rows updated |
|---|---|---|---|---|---|
| 1 | 1 October | 1 | 0 | 4 | 0 |
| 2 | 2 October | 1 | 1 | 1 | 2 |
| 5 | 5 October | 1 | 1 | 1 | 1 |
| 6 | Rerun 1 October | 1 | 1 | 0 | 0 |
| 7 to 11 | Rerun 1 to 5 October | 1 each | 1 each | 0 | 0 |
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
| Load | Two events for a new key | Two events for a known key | Crash mid-run | Rerun an old day | Same-second events |
|---|---|---|---|---|---|
| Part 3's day replacement | Both kept | Every version kept | Safe | Safe, still wrong | Both kept |
| Update then insert, two commits | One kept | Latest kept | Half a run visible; on Delta a loaded key is deleted | Safe | Latest kept |
| Update then insert, raw batch (Postgres) | Inserted twice | Arbitrary event kept | Safe | Safe | Inserted twice |
dropDuplicates, then guarded MERGE (Delta) | Whichever row came first | Whichever row came first | Safe | Not run | Whichever row came first |
| Guarded MERGE, one event per key | One kept | Latest kept | Safe | No rows change; on Delta, one commit and a file rewrite | Latest kept |
| Guarded MERGE, raw batch | Inserted twice | Run fails, and keeps failing | Safe | Not reached | Not reached |
| MERGE with no guard | One kept | Latest kept | Safe | Rows go back in time | Latest kept |
Guarded MERGE on event_at (Postgres) | One kept | Latest kept | Safe | No rows change | Earlier 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-07andT-08when the run dies between them, and a retry repairs it. - An update and an insert with the raw batch insert
T-03andT-07twice, 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-03twice, 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-02andT-04back to their authorisations when 1 October is rerun. - Ordering by
event_atleavesT-07authorised 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,
dropDuplicatesleavesT-03,T-05andT-07at their authorisations when the batch is inevent_seqorder, 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 existscheck 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.
dropDuplicatesgives 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.