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 doesWhat a live reader sees
Deletes the 2,400 old files while a query is scanning themThe 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 onesA query that lists the directory in between reads every row twice
Compacts the hour the writer is still appending toFiles 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 pathLate 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:

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.

The hour's rows flow from the live directory into a staging copy; the check gates the repoint, and the old files outlive the longest reader before deletion.
  • 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_count

errorifexists 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?

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.