data-engineering

Data Engineering Design Patterns: Partition Overwrite

published
reading
15 min
tags
data-engineering, etl, partitioning, partition-overwrite, postgres, delta-lake, spark, series
On this page
  1. The Failure
  2. The Companion Code
  3. The Data
  4. The Variant That Breaks: Overwrite the Partitions in the Batch
  5. The Variant That Breaks: Replace the Run's Own Day
  6. The Pattern: Name the Partitions, Rebuild Them Whole
  7. The Variant That Breaks: Rebuild as of the Run's End
  8. Delta Lake
  9. Side by Side
  10. Checks Worth Keeping
  11. What Is Next
  12. Summary to Save

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:

python
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:

StepExpected rowsTarget rowsTarget partitionsMissing from targetTarget totalExpected total
5 October331none1,750,0001,750,000
6 October632TR-01, TR-02, TR-031,450,0003,200,000
9 October1532Twelve of the fifteen trades1,800,0009,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:

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_partition_overwrite

Each 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_idtrade_datebooked_atWhat it shows
TR-06Mon 5 OctTue 6 Oct 08:10Tuesday's batch holds a row for Monday's partition
TR-12Tue 6 OctThu 8 Oct 17:05Booked two days late, after a break report
TR-15Thu 8 OctFri 9 Oct 07:45Friday'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:

python
batch = extract_interval(conn, run)
partitions = partitions_in_batch(batch)
with conn.transaction():
    empty_partitions(conn, partitions)
    insert_rows(conn, batch)
StepPartitions emptiedTarget rowsPartitions that differMissing from targetTarget totalExpected total
5 October13nonenone1,750,0001,750,000
6 October235 OctTR-01, TR-02, TR-031,450,0003,200,000
7 October165 OctTR-01, TR-02, TR-034,200,0005,950,000
8 October275 Oct, 6 OctTR-01 to TR-054,600,0007,400,000
9 October285 Oct, 6 Oct, 8 OctSeven trades5,300,0009,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:

python
run_day = run.interval_start.date()
with conn.transaction():
    empty_partitions(conn, [run_day])
    insert_rows(conn, batch)
StepRun outcomeTarget rowsPartitions that differMissing from targetDuplicated trade_idTarget totalExpected total
5 Octoberok3nonenonenone1,750,0001,750,000
6 Octoberok6nonenonenone3,200,0003,200,000
9 Octoberok15nonenonenone9,200,0009,200,000
Rerun 6 Octoberok155 Oct, 6 OctTR-12TR-069,250,0009,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:

python
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:

sql
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:

StepPipeline runs so farPartitions emptiedRows writtenTarget rowsTarget totalMatches expected
5 October11331,750,000yes
6 October22663,200,000yes
7 October31395,950,000yes
8 October425127,400,000yes
9 October525159,200,000yes
Rerun 6 October627159,200,000yes
Rerun 5 to 9 October11825159,200,000yes

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.

sql
select * from src_trades where trade_date = any(%s) and booked_at < %s
StepPartitions emptiedRows writtenPartitions that differMissing from targetTarget totalExpected total
9 October25nonenone9,200,0009,200,000
Rerun 6 October266 OctTR-128,850,0009,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:

ScenarioThe Delta write
Overwrite the tablemode("overwrite").partitionBy("trade_date"), in Spark's default static mode
Overwrite the partitions in the batchmode("overwrite").option("partitionOverwriteMode", "dynamic")
Replace the run's own daymode("overwrite").option("replaceWhere", "trade_date = DATE'...'")
The pattern, and the as-of variantmode("overwrite").option("replaceWhere", "trade_date IN (...)") with the rebuild

The pattern's write names its partitions in the predicate:

python
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:

LoadDaily runsLate trade arrivesRerun of 6 OctoberCost of one late trade
Overwrite the tableKeeps only the last batchLost with everything elseNot reachedThe whole table
Overwrite the partitions in the batchLoses rows from day 2Replaces its partition with itselfNot reachedIts partition, wrongly
Replace the run's own dayMatchesAppended to its partitionOne trade duplicated, one lostOne row
Rebuild named partitions from everythingMatchesIts partition rebuilt wholeMatchesA rewrite of its partition
Rebuild named partitions as of the run's endMatchesIts partition rebuilt wholePartition goes back in timeA 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-02 and TR-03 on 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-06 and loses TR-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 replaceWhere refusal, 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 replaceWhere predicate 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.
Share

Related