Idempotent Upserts
Concepts covered: Keyed Deduplication
Day partitions work when every row belongs to the day it arrived. A listings table breaks that: it holds 1 row per listing, and a listing created on March 2 can change price on March 14 and again on March 15. No day owns that row, so appending each day's changes leaves 3 versions of it, and overwriting a day keeps only the listings that changed that day. The table needs an upsert: insert new keys and update existing ones.
Rebuild from inputs that never change
A Parquet file is written once and never edited, so in plain files an upsert is a rewrite. Read yesterday's snapshot, union today's changes, keep the newest version of each key, and write the result as today's snapshot in a directory of its own. Since yesterday's snapshot is never touched, rerunning the 2024-03-14 merge sees exactly the inputs the first attempt saw, and its output at ds=2024-03-14 comes out the same however many times it runs.
- Snapshot ds=2024-03-13 (storage, Parquet, read only)
- Changes 2024-03-14 (source, listing_attribute_changes)
- Keep latest per key (transform, Spark window); parallelism: 200 partitions
- Snapshot ds=2024-03-14 (storage, Parquet); idempotency: overwrite its own ds
- Next day's merge (consumer, reads ds=2024-03-14)
- Snapshot ds=2024-03-13 -> Keep latest per key
- Changes 2024-03-14 -> Keep latest per key
- Keep latest per key -> Snapshot ds=2024-03-14
- Snapshot ds=2024-03-14 -> Next day's merge
The animation runs that merge on a snapshot of 3 listings and 5 change rows. One change arrived twice because the upstream feed redelivered it.
from pyspark.sql import functions as F
from pyspark.sql.window import Window
merged = snapshot.unionByName(changes)
w = Window.partitionBy("listing_ref").orderBy(F.col("change_seq").desc())
latest = (merged
.withColumn("rn", F.row_number().over(w))
.filter(F.col("rn") == 1)
.drop("rn"))
latest.collect()| listing_ref | price | change_seq |
|---|---|---|
| L1 | 100 | 3 |
| L2 | 250 | 5 |
| L3 | 80 | 2 |
| listing_ref | price | change_seq |
|---|---|---|
| L2 | 245 | 6 |
| L2 | 240 | 7 |
| L1 | 95 | 4 |
| L2 | 240 | 7 |
| L4 | 60 | 8 |
Window.partitionBy("listing_ref") hash-shuffles the union by key, so every version of L2 lands on 1 task whichever input it came from. That task sorts its rows by change_seq descending, and row_number keeps the first. The redelivered change gives 2 identical L2 rows at change_seq 7; either can take number 1 and the surviving row is the same. Feeding the output back in with the same changes returns the output unchanged.
Merges that converge
A merge converges when applying a change twice equals applying it once. Keep-latest by sequence number has that property, and so does set union; max and min do too. Adding to a stored total lacks it: a balance updated with + 30 on every run drifts 30 higher per retry. For sums and counts, store the deduplicated events as the state and recompute the total from them, so a rerun recomputes a number instead of adding to one.
A daily job maintains each user's total spend from transactions, and the job for 2024-03-14 may run twice. Which design leaves the same result after 1 run or 2?
- Append each user's spend for the day as a new row, and have readers sum a user's rows at query time
- Store transactions deduplicated by transaction_id, recompute each total from them, and overwrite ds=2024-03-14
- Add the day's sums to the stored totals in place, since a rerun of the day reads the same transactions
- Recompute each total from all stored transactions, then append the new totals beside the old ones
The ordering comes from the source
Keep-latest needs an ordering column that sorts the same way on every run. change_seq is assigned by the system that produced the change, so a replay sorts identically. A load timestamp stamped by your job is a poor substitute: a rerun stamps fresh times, and a redelivered old change can outrank a newer one that loaded first. When 2 versions can share an ordering value with different contents, add a second column to the ordering so exactly 1 row ranks first.
Run the cell. It applies keep-latest to the change log in listing_attribute_changes, ranking each listing attribute by change_seq and keeping rank 1. The op column records the kind of each change, and when the winning row is a delete, the attribute no longer exists, so the snapshot drops it instead of keeping its last value. Then change .desc() to .asc() and run again: the cell returns the earliest value still in the change log for each attribute, because the sort direction decides which version wins.
About this lesson
This section is part of the Fault Tolerance: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.