Compaction in Production
Concepts covered: Shuffle Optimization
pings takes a write every 5 minutes, partitioned by ds and hour. Each write runs 200 tasks and each task writes 1 file, so a closed hour holds 2,400 files averaging about 2.6MB across its 6GB. Compaction rewrites that hour as 24 files of 256MB. The rewrite is a short Spark job; the production work is swapping files that other queries may be reading at that moment.
How compaction breaks readers
| What the compactor does | What a live reader sees |
|---|---|
| Deletes the 2,400 old files while a query is scanning them | The query fails on the first old file it tries to open after the delete |
| Writes the 24 new files into `hour=11` before deleting the old ones | A query that lists the directory in between reads every row twice |
| Compacts the hour the writer is still appending to | Files written mid-run get deleted with the old ones, and their rows are gone |
| Repoints `hour=11` while a late writer still appends to the old path | Late rows land in a directory the table no longer reads |
A protocol readers never notice
At 14:30 on 2024-03-15, with a 2-hour lateness window, hour=11 is the newest hour the compactor may touch. Its run takes 5 steps:
- Compact closed hours only: Once late rows stop arriving the writer never touches the hour again, so nothing lands while the compactor reads it.
- Write to a fresh directory: A new path per run, such as /lake/pings_compacted/ds=2024-03-15/hour=11/run=1/, keeps half-written output out of every listing a reader makes.
- Verify the copy: The compacted directory must hold exactly as many rows as the source hour, or the run stops before any reader is affected.
- Repoint the partition: Queries planned after the update list the 24 new files; queries planned before it keep the 2,400 old ones they already listed.
- Delete after a grace period: The old files go only once every query that could have listed them has finished: measure the longest query and add margin.
Together the steps keep the metastore pointing the partition at exactly 1 complete directory at every moment, and no file a planned query listed disappears before that query can finish.
- Pings writer (source, Spark batch, every 5 min)
- pings hour=11 (storage, 2,400 files, 6GB)
- Compact closed hour (transform, Spark batch); freshness: hour end + 2h; idempotency: fresh run directory
- Staging dir (storage, 24 files of 256MB)
- Row count check (quality gate, source rows = written rows); on error: stop before repoint
- Repoint partition (transform, metastore update)
- Delete old files (transform, after grace period)
- Pings writer -> pings hour=11
- pings hour=11 -> Compact closed hour
- Compact closed hour -> Staging dir
- Staging dir -> Row count check
- Row count check -> Repoint partition
- Repoint partition -> Delete old files
import math
from pyspark.sql import functions as F
TARGET_FILE_BYTES = 256 * 1024 * 1024
def compact_hour(ds, hour, hour_bytes, staging_dir):
rows = spark.table("lake.pings").filter(
(F.col("ds") == ds) & (F.col("hour") == hour)
)
file_count = max(1, math.ceil(hour_bytes / TARGET_FILE_BYTES))
(
rows.drop("ds", "hour")
.repartition(file_count)
.write.mode("errorifexists")
.parquet(staging_dir)
)
written = spark.read.parquet(staging_dir).count()
expected = rows.count()
if written != expected:
raise ValueError(f"{staging_dir}: wrote {written} rows, expected {expected}")
return file_counterrorifexists makes a reused staging path fail instead of mixing with a half-written earlier attempt. repartition(file_count) shuffles the hour's 6GB so each output file gets an equal share of rows. coalesce(file_count) skips the shuffle by merging the scan's input partitions in place, and the merged groups, and so the files, can differ in size. At 6GB the shuffle costs seconds and buys even files. On a 2TB day it becomes the largest cost of the run, and coalesce with its uneven files is often the better trade.
Writers should append through the table name, never a hard-coded path. An append by name goes to the partition's current location, so a late row that slips past the window still lands where readers look. An append by path to the old directory survives only until the delayed delete, and no reader sees it before then.
A compactor writes 24 new files into hour=11, then deletes the 2,400 old ones. A dashboard query sums pings for that hour, lists the directory between those 2 steps, and finishes before the delete. What does it return?
- The correct sum, because Spark reads only the newest files in a directory
- Twice the true sum, because it read the old files and the new ones
- A file-not-found error, because the old files vanished before it read them
- Half the true sum, because the new files replaced half of the old listing
About this lesson
This section is part of the Partitioning: Advanced 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.