This is part 5 of the data engineering design patterns series. Part 4 replaced rows one key at a time. Many targets are not written that way. They are partitioned by a date, and each run rewrites whole partitions: delete everything for a day, write the day again. It is cheap, it is idempotent, and the unit of work matches the unit of storage.
The question this part answers is which partitions a run is allowed to replace, and what it has to put in them.
My position is that a run names the partitions it replaces, and fills each one completely. The list of partitions is computed in my own code from the batch and written into the write itself, not left to a mode setting on the session. And a partition is rebuilt from everything the source holds for it, not from the slice of it that happened to arrive in today's batch. This post shows an overwrite that wipes the table, two ways of choosing partitions that lose or duplicate rows, the pattern, and two versions of it that are each missing one piece.
#The Failure
The target is fact_trades, partitioned by trade_date, the business
day a trade belongs to. The pipeline runs once a day, reads the trades
booked that day with part 2's interval read, and writes them with an
overwrite.
On Spark, the write most people reach for first is this:
batch.write.format("delta").mode("overwrite").partitionBy("trade_date").save(path)It reads as "overwrite the partitions I am writing". In Spark's default
mode it means overwrite the table. On Postgres the same mistake is
spelled out: truncate fact_trades, then insert the batch, in one
transaction.
After five daily runs:
| Step | Expected rows | Target rows | Target partitions | Missing from target | Target total | Expected total |
|---|---|---|---|---|---|---|
| 5 October | 3 | 3 | 1 | none | 1,750,000 | 1,750,000 |
| 6 October | 6 | 3 | 2 | TR-01, TR-02, TR-03 | 1,450,000 | 3,200,000 |
| 9 October | 15 | 3 | 2 | Twelve of the fifteen trades | 1,800,000 | 9,200,000 |
Every run succeeded, and every run left the table holding only its own batch. Monday's partition existed until Tuesday's run, and then it was gone. An overwrite that is not told which partitions to replace replaces all of them.
#The Companion Code
Everything below comes from data-engineering-design-patterns, part 5. 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_partition_overwriteEach scenario starts with an empty source and target and runs the five
business days from Monday 5 to Friday 9 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: every trade the
source has booked so far, once, in its own trade_date partition. The
report lists trades that are missing or duplicated, and the
partitions whose rows differ from the expected ones. The reports
used in this post are in example-results.
#The Data
The source is one Postgres table, src_trades. Every trade is written
once and never changes. trade_date is the business day it belongs to;
booked_at is when the source committed it, and the daily read is on
booked_at.
Twelve of the fifteen trades are booked on their trade date. Three are not:
trade_id | trade_date | booked_at | What it shows |
|---|---|---|---|
TR-06 | Mon 5 Oct | Tue 6 Oct 08:10 | Tuesday's batch holds a row for Monday's partition |
TR-12 | Tue 6 Oct | Thu 8 Oct 17:05 | Booked two days late, after a break report |
TR-15 | Thu 8 Oct | Fri 9 Oct 07:45 | Friday's batch holds a row for Thursday's partition |
This is the ordinary shape of trade data. A trade made in the evening is booked the next morning, and a trade found missing in a reconciliation is booked days later with its original trade date. So a day's batch and a day's partition are not the same set of rows, and every scenario below turns on that difference.
On Postgres the target is a list-partitioned table with one partition
per trade_date, created the first time a row needs it. Rows are
inserted through the parent table, so each one is routed to its own
partition.
#The Variant That Breaks: Overwrite the Partitions in the Batch
The obvious repair is to replace only the partitions the batch has rows
for. On Spark that is partitionOverwriteMode=dynamic. On Postgres it is
a truncate of each of those partitions, then the insert, in one
transaction:
batch = extract_interval(conn, run)
partitions = partitions_in_batch(batch)
with conn.transaction():
empty_partitions(conn, partitions)
insert_rows(conn, batch)| Step | Partitions emptied | Target rows | Partitions that differ | Missing from target | Target total | Expected total |
|---|---|---|---|---|---|---|
| 5 October | 1 | 3 | none | none | 1,750,000 | 1,750,000 |
| 6 October | 2 | 3 | 5 Oct | TR-01, TR-02, TR-03 | 1,450,000 | 3,200,000 |
| 7 October | 1 | 6 | 5 Oct | TR-01, TR-02, TR-03 | 4,200,000 | 5,950,000 |
| 8 October | 2 | 7 | 5 Oct, 6 Oct | TR-01 to TR-05 | 4,600,000 | 7,400,000 |
| 9 October | 2 | 8 | 5 Oct, 6 Oct, 8 Oct | Seven trades | 5,300,000 | 9,200,000 |
Tuesday's batch holds TR-06, which belongs to Monday. So Monday's
partition is one of the partitions in the batch, and it is replaced with
what the batch holds for Monday: one trade. The three trades booked on
Monday are gone. The same thing happens to Tuesday's partition when
TR-12 arrives on Thursday, and to Thursday's when TR-15 arrives on
Friday.
This is the worse failure of the two. The static overwrite empties the table, and someone notices the next morning. This one keeps every partition, with plausible row counts, and quietly replaces three of the five with a single late trade each. A partition overwrite is only correct if the rows written are the whole partition, and a batch read by booking time is not.
#The Variant That Breaks: Replace the Run's Own Day
The other obvious choice is part 3's: the run owns its own day. It replaces the partition for its run date, and writes the batch:
run_day = run.interval_start.date()
with conn.transaction():
empty_partitions(conn, [run_day])
insert_rows(conn, batch)| Step | Run outcome | Target rows | Partitions that differ | Missing from target | Duplicated trade_id | Target total | Expected total |
|---|---|---|---|---|---|---|---|
| 5 October | ok | 3 | none | none | none | 1,750,000 | 1,750,000 |
| 6 October | ok | 6 | none | none | none | 3,200,000 | 3,200,000 |
| 9 October | ok | 15 | none | none | none | 9,200,000 | 9,200,000 |
| Rerun 6 October | ok | 15 | 5 Oct, 6 Oct | TR-12 | TR-06 | 9,250,000 | 9,200,000 |
For five days it is perfect. Late trades are inserted through the parent table, routed to their own earlier partitions, and appended there, because only the run's own day was emptied.
Then 6 October is rerun. It empties Tuesday's partition, which by now
holds TR-12, booked on Thursday. It writes its batch, which includes
TR-06 for Monday, and Monday's partition already has TR-06 from the
first run. One rerun leaves one trade missing and another counted
twice, and the row count is unchanged: 15 before, 15 after. Only
the total moves, by the difference between the two notionals.
This load is half partition overwrite and half append, and it is idempotent only for the half that is an overwrite.
#The Pattern: Name the Partitions, Rebuild Them Whole
The pattern is four steps, each a function with its own output that can be inspected:
batch = extract_interval(conn, run) # 1. what arrived today
partitions = partitions_in_batch(batch) # 2. which partitions it touches
rebuild = extract_partitions(conn, partitions) # 3. everything the source holds for them
check_rebuild(batch, partitions, rebuild) # 4. it fits, before anything is replaced
with conn.transaction():
empty_partitions(conn, partitions)
insert_rows(conn, rebuild)The batch decides which partitions, not what goes in them. The interval read is still the trigger: a partition is rebuilt because something new arrived for it. But its content comes from a second read, by partition key:
select * from src_trades where trade_date = any(%s)The partitions are named. partitions_in_batch returns a sorted
list of dates. On Postgres it becomes the list of partitions to
truncate; on Delta it becomes the replaceWhere predicate, written out
in full where the commit log keeps it.
The rebuild is checked before anything is replaced. Every row of the rebuild belongs to a named partition, every named partition has rows, and every trade in the batch is in the rebuild. If any of those fails, the run stops with the target untouched.
After the five days, 6 October is rerun, and then all five days again:
| Step | Pipeline runs so far | Partitions emptied | Rows written | Target rows | Target total | Matches expected |
|---|---|---|---|---|---|---|
| 5 October | 1 | 1 | 3 | 3 | 1,750,000 | yes |
| 6 October | 2 | 2 | 6 | 6 | 3,200,000 | yes |
| 7 October | 3 | 1 | 3 | 9 | 5,950,000 | yes |
| 8 October | 4 | 2 | 5 | 12 | 7,400,000 | yes |
| 9 October | 5 | 2 | 5 | 15 | 9,200,000 | yes |
| Rerun 6 October | 6 | 2 | 7 | 15 | 9,200,000 | yes |
| Rerun 5 to 9 October | 11 | 8 | 25 | 15 | 9,200,000 | yes |
Every step matches. The cost is in the "Rows written" column: Tuesday's run writes six rows for a three-row batch, because it rewrites all of Monday as well as Tuesday. A rerun of all five days writes 25 rows to end up with 15. That is the price of a partition overwrite, and it is worth knowing before the partitions hold millions of rows each: one late row costs a rewrite of its whole partition.
#The Variant That Breaks: Rebuild as of the Run's End
Part 2 and part 3 taught that a run reads its own interval and nothing newer, so that rerunning it reads the same rows. Applied to the rebuild, that becomes: rebuild each partition only from the trades booked before the run's interval ended.
select * from src_trades where trade_date = any(%s) and booked_at < %s| Step | Partitions emptied | Rows written | Partitions that differ | Missing from target | Target total | Expected total |
|---|---|---|---|---|---|---|
| 9 October | 2 | 5 | none | none | 9,200,000 | 9,200,000 |
| Rerun 6 October | 2 | 6 | 6 Oct | TR-12 | 8,850,000 | 9,200,000 |
Daily it is indistinguishable from the pattern. The rerun of 6 October
rebuilds Tuesday's partition as it stood on Tuesday night, before
TR-12 was booked, and writes that over the partition that had it. The
run succeeded, every check passed, and the table has gone back in time
by two days for one partition.
This is part 4's unguarded MERGE again, in a different shape. A partition is a function of its key, not of the run that last touched it. Rebuild it from everything the source holds for it now, and every rerun, in any order, gives the same partition.
#Delta Lake
On Delta Lake the source stays in Postgres and the target is a Delta
table partitioned by trade_date. Each Postgres scenario has a Delta
counterpart, and the write is the only line that changes:
| Scenario | The Delta write |
|---|---|
| Overwrite the table | mode("overwrite").partitionBy("trade_date"), in Spark's default static mode |
| Overwrite the partitions in the batch | mode("overwrite").option("partitionOverwriteMode", "dynamic") |
| Replace the run's own day | mode("overwrite").option("replaceWhere", "trade_date = DATE'...'") |
| The pattern, and the as-of variant | mode("overwrite").option("replaceWhere", "trade_date IN (...)") with the rebuild |
The pattern's write names its partitions in the predicate:
def named_partitions_predicate(partitions):
return f"trade_date IN ({', '.join(date_literal(d) for d in partitions)})"
(
batch_frame(spark, rebuild)
.write.format("delta")
.mode("overwrite")
.option("replaceWhere", named_partitions_predicate(partitions))
.save(path)
)replaceWhere has a property the Postgres version does not: by default
Delta checks that every row written matches the predicate, and refuses
the commit if one does not. So the run's-own-day variant, which on
Postgres quietly appends a late trade to an older partition, should
fail on Delta instead of writing anything.
Delta adds one scenario of its own. Dynamic mode can be set on the
write, as above, or once for the whole session with
spark.sql.sources.partitionOverwriteMode. The sixth scenario writes
the pattern's complete partitions with a plain mode("overwrite") and
leaves the mode to the session: dynamic for four days, and on Friday a
session with Spark's default, static, as a job gets when it moves to a
cluster that was set up without the setting. The code is identical on
all five days; only the session differs.
The Delta run is slow on my machine, and its measured results, with the
commit history of every scenario, are in the companion repository's
example-results folder.
#Side by Side
From the Postgres runs:
| Load | Daily runs | Late trade arrives | Rerun of 6 October | Cost of one late trade |
|---|---|---|---|---|
| Overwrite the table | Keeps only the last batch | Lost with everything else | Not reached | The whole table |
| Overwrite the partitions in the batch | Loses rows from day 2 | Replaces its partition with itself | Not reached | Its partition, wrongly |
| Replace the run's own day | Matches | Appended to its partition | One trade duplicated, one lost | One row |
| Rebuild named partitions from everything | Matches | Its partition rebuilt whole | Matches | A rewrite of its partition |
| Rebuild named partitions as of the run's end | Matches | Its partition rebuilt whole | Partition goes back in time | A rewrite of its partition |
Only one row is clean in every column. It is also the most expensive per late trade, and that is the trade-off of the pattern: correctness is bought by rewriting whole partitions, so partitions should be sized for the rewrites they will get.
#Checks Worth Keeping
The companion code's tests state the claims above as assertions:
- Overwriting the table leaves only Friday's three trades after five days, with the twelve earlier trades missing.
- Overwriting the partitions in the batch loses
TR-01,TR-02andTR-03on Tuesday, and ends with Monday's, Tuesday's and Thursday's partitions wrong. - Replacing the run's own day matches the expected table every day, and
a rerun of 6 October duplicates
TR-06and losesTR-12. - Rebuilding the named partitions matches after every run and rerun; the rerun of 6 October empties two partitions and writes seven rows, and the rerun of all five days empties eight and writes 25.
- Rebuilding as of the run's end matches every day, and a rerun of
6 October loses
TR-12. - The Delta tests pin the same failures, the
replaceWhererefusal, and the session without the dynamic setting.
The check I would add to a real pipeline compares each partition, not
just the table: rows and total notional per trade_date in the target
against the same per trade_date in the source. A table-level count
passes the rerun in the third scenario, because one duplicate and one
loss cancel out in the row count. A per-partition check fails on both
partitions. Part 14 covers reconciliation.
#What Is Next
Every load so far has read the source with a query, by interval or by key, and the source has never deleted anything. Real sources delete rows, and a query cannot see a row that is no longer there. Part 6 is change data capture: log-based capture from Postgres through Kafka into Delta against snapshot comparison, and what happens to deletes and out-of-order events.
#Summary to Save
- An overwrite that is not told which partitions to replace replaces all
of them. In Spark that is the default, even with
partitionBy. - A day's batch and a day's partition are different sets of rows as soon as anything is booked late.
- Overwriting the partitions the batch has rows for, with only the batch, replaces a whole partition with its late rows.
- Replacing only the run's own day appends late rows to older partitions, and a rerun then duplicates some rows and drops others.
- The batch decides which partitions to rebuild; the source decides what goes in them. Read each named partition whole, by its key.
- Name the partitions in the write itself, as a list on Postgres or a
replaceWherepredicate on Delta, instead of leaving it to a session setting. - Check the rebuild before replacing anything: every row inside a named partition, no named partition empty, every batch row present.
- Rebuild from everything the source holds now, not as of the run's interval, or a rerun takes a partition back in time.
- Compare rows and totals per partition after every run; table-level counts let errors cancel out.