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.

Each snapshot is built from the one before it and is never written again after its own day.
  • 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()
snapshot
listing_refpricechange_seq
L11003
L22505
L3802
changes
listing_refpricechange_seq
L22456
L22407
L1954
L22407
L4608

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?

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.