Changing a Layout Safely

Concepts covered: Configuration Tuning

trips_by_city, the older layout, is partitioned by city. The target is curated.trips_v2, partitioned by ds and bucketed into 2048 on driver_id, holding each trip of the last 90 days exactly once. Rewriting in place is ruled out: Spark refuses to overwrite a table the same query reads from, and working around that refusal deletes the input before the lazy plan has read it. The move builds the new table beside the old one and switches readers at the end.

The move in 5 steps

History flows through the backfill, new days come from the live writer into both tables, and the view moves to trips_v2 only after every day passes the check.
  • trips_by_city (storage, old layout, by city)
  • Live daily writer (source, Spark batch)
  • Backfill by ds range (transform, Spark batch); backfill: 10-day chunks, 2023-12-16 to 2024-03-14; idempotency: dynamic overwrite per ds
  • trips_v2 (storage, by ds, 2048 buckets)
  • Fingerprint check (quality gate, count, distinct ids, fare sum per ds); on error: rerun the chunk
  • curated.trips view (consumer, what readers query)
  • trips_by_city -> Backfill by ds range
  • Backfill by ds range -> trips_v2
  • Live daily writer -> trips_by_city
  • Live daily writer -> trips_v2
  • trips_by_city -> Fingerprint check
  • trips_v2 -> Fingerprint check
  • Fingerprint check -> curated.trips view

Overwrite a day, never the table

The default overwrite mode, static, deletes every existing partition of the target before writing, including days the DataFrame holds no rows for. Setting spark.sql.sources.partitionOverwriteMode to dynamic narrows the delete to the partitions the DataFrame writes. Under it, a chunk that dies halfway can rerun: the retry replaces its own days and leaves the rest alone.

from pyspark.sql import functions as F

spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")

old = spark.table("curated.trips_by_city")
target_columns = spark.table("curated.trips_v2").columns
chunks = [("2023-12-16", "2023-12-25"), ("2023-12-26", "2024-01-04")]

for first_ds, last_ds in chunks:
    days = old.filter(F.col("ds").between(first_ds, last_ds))
    (
        days.select(*target_columns)
        .repartition(2048, "driver_id")
        .write.mode("overwrite")
        .insertInto("curated.trips_v2")
    )

insertInto matches columns by position, so the select lists them in the target's order; swap 2 columns of the same type, such as trip_id and driver_id, and rows load into the wrong places without an error. Each chunk scans all of trips_by_city, because ds is not that table's partition column and nothing prunes, so the chunk size trades the number of full scans against the size of each job.

Chunk by ds, never by city. Dynamic overwrite replaces whole ds partitions, so a loop that writes New York's trips and then Austin's leaves every day holding Austin's trips alone.

Proving nothing moved twice

A fingerprint per ds catches both failures. A lost row lowers the count. A doubled row lifts the count above the number of distinct trip ids. Compute the same fingerprint on both tables and compare them day by day; a day that differs gets its chunk rerun, which dynamic overwrite makes safe. Try the fingerprint on store_sales_raw, grouped by sale_date.

Any day where row_count exceeds distinct_ids holds a repeated sale id. On a real move, the query must return identical rows from the old table and the new one.

The switch and the way back

Every reader queries curated.trips, a view over whichever table is current. A view resolves to its table at planning time, so queries through it still get the bucketed scan. Moving every reader takes a single statement:

CREATE OR REPLACE VIEW curated.trips AS
SELECT
  trip_id,
  driver_id,
  city,
  fare,
  ds
FROM curated.trips_v2

With dynamic overwrite on, a teammate's first pass writes New York's trips for all 90 days into trips_v2 with mode("overwrite") and insertInto. A second pass writes Austin's trips for 2024-02-14 to 2024-03-14 only, the last 30 days. What does trips_v2 hold?

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.