AdvancedSpark · 15 min · 17 challenges

Partitioning: Advanced

A data engineer at Uber has a pricing job that reruns every hour, joining yesterday's 2TB of trips to drivers. Each run reshuffles all 2TB by driver_id, an older table partitioned by city leaves a single task grinding through New York, and a GPS pings table piles up 2,400 small files an hour. All 3 problems come from how the files are laid out.

Bucketing at Write Time

Daily Life
Interviews

Bucketing fixes a table's hash layout at write time. Spark hashes each row's bucket column, takes the result modulo the bucket count n, and writes the row into a file tagged with that bucket's number. The metastore stores the column and n beside the table's schema, so a query that later reads the table by name knows which bucket holds every key before it opens a file.

That knowledge is what a join normally buys with a shuffle. The pricing job joins trips, 2TB per day, to drivers, 120GB, on driver_id. Neither table is stored by driver_id, so Spark hash-partitions both inputs across the network before a trip can meet its driver. The animation runs that join on 10 trips and 4 drivers.

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
joined = trips.join(drivers, "driver_id")
joined.collect()
trips10 rows
trip_id
driver_id
city
fare
101
7
New York
18
102
3
Austin
12.5
103
7
New York
31
104
5
Denver
9
105
3
Austin
22
106
9
New York
15.5
107
5
Denver
27
108
9
New York
11
109
7
New York
19.5
110
3
Austin
14
drivers4 rows
driver_id
driver_name
rating
3
Ana
4.9
5
Ben
4.7
7
Chen
4.8
9
Dara
4.6
Preparing the animation

The first line turns off broadcasting, which would otherwise copy a table this small whole to every task; the production tables are far too large for that shortcut. What runs instead is an exchange on each side: every input task writes its rows to shuffle files keyed by driver_id, and each reducer task fetches its share from all of them. Every row for driver 7 reaches the same reducer, whichever partition it started in, and meets its match there.

Paying the shuffle once, at write

Bucketing moves that exchange from the read to the write. The table is shuffled by its bucket column once, as it is written, and the hashed layout is kept as files. Every read afterwards starts from rows already grouped by driver_id.

trips = spark.read.parquet("/lake/raw/trips/")
(
trips.repartition(2048, "driver_id")
.write.partitionBy("ds")
.bucketBy(2048, "driver_id")
.sortBy("driver_id")
.mode("overwrite")
.saveAsTable("curated.trips_bucketed")
)
The write, line by line
  • bucketBy works only with saveAsTable. Writing with .save(path) raises an error, because the bucket column and count have to be recorded in the metastore.
  • repartition(2048, "driver_id") applies the same hash and modulo as bucketBy(2048, "driver_id"), so each write task holds exactly 1 bucket and writes 1 file into each ds directory: 2048 files per day.
  • sortBy orders the rows inside each bucket file. The plan further down shows what it leaves in place.

The animation shows that reuse at small scale. Once rows are hash-partitioned by driver_id, a groupBy on driver_id needs no second exchange, because each driver's rows already sit in 1 partition. A bucketed table is that first exchange, saved to disk.

from pyspark.sql import functions as F
by_driver = trips.repartition(3, "driver_id")
revenue = by_driver.groupBy("driver_id").agg(F.sum("fare").alias("revenue"))
revenue.collect()
trips10 rows
trip_id
driver_id
city
fare
101
7
New York
18
102
3
Austin
12.5
103
7
New York
31
104
5
Denver
9
105
3
Austin
22
106
9
New York
15.5
107
5
Denver
27
108
9
New York
11
109
7
New York
19.5
110
3
Austin
14
Preparing the animation
Loading the challenge

Reading 2 bucketed tables by name

drivers is written the same way, into 2048 buckets on driver_id. Read both tables by name and join them, and the planner finds each scan already delivering hash partitioning on driver_id into 2048 parts, the exact distribution the join requires. It adds no exchange. Task 0 reads bucket 0 of both tables, task 1 reads bucket 1 of both, and so on through 2048 tasks of about 1GB of trips each.

Plan without buckets
OperatorReads
SortMergeJoinboth
Sorttrips
Exchange hashpartitioning(driver_id, 200)trips
FileScan parquettrips
Sortdrivers
Exchange hashpartitioning(driver_id, 200)drivers
FileScan parquetdrivers
Plan with 2048 buckets on each side
OperatorReads
SortMergeJoinboth
Sorttrips
FileScan parquet, Bucketed: truetrips
Sortdrivers
FileScan parquet, Bucketed: truedrivers

The Sort steps stay. In Spark 3 a bucketed scan does not report its sort order to the planner by default, so sortBy does not remove them; the missing exchange is the saving to count on.

2.12TB
shuffle written per unbucketed run
51TB
shuffle written per day, unbucketed
The bucketed table pays for 1 shuffle when the day is written, and all 24 hourly runs after it join without any.
TIP
Bucketing pays off when reads on the key outnumber writes. A table rewritten every hour and read once an hour gains nothing: the shuffle at write replaces the shuffle at read 1 for 1.
Multiple Choice

trips_bucketed and drivers_bucketed are both bucketed by driver_id into 2048 buckets and read by name. How many exchanges does the plan for this program contain?

from pyspark.sql import functions as F
trips = spark.table("curated.trips_bucketed")
drivers = spark.table("curated.drivers_bucketed")
ranked = (
trips.join(drivers, "driver_id")
.groupBy("driver_id")
.agg(F.sum("fare").alias("revenue"))
.orderBy(F.desc("revenue"))
)
ranked.collect()

Bucketing Pitfalls

Daily Life
Interviews

A bucketed table keeps its exchange-free plan only while each query meets the conditions the planner checks. Miss any of them and the plan regains an exchange with no error and no warning: the same result, at the old shuffle cost. Traps 1 to 3 show up in explain() as an Exchange sitting above a scan you expected to read buckets. Traps 4 and 5 add no exchange; they show up as file counts on disk and as per-task input sizes in the Spark UI.

Trap 1: reading the files instead of the table

The bucket column and count live in the metastore; the files hold rows and nothing more. spark.read.parquet("/lake/curated/trips_bucketed/") reads the same bytes as spark.table("curated.trips_bucketed"), yet sees a plain directory, so its scan reports no partitioning at all. Read a bucketed table by its name, or through a view over that name.

Trap 2: bucket counts that differ

Buckets line up only when both sides split the key space the same number of ways. With trips in 2048 buckets and drivers in 512, a driver in bucket 1,031 of trips sits in bucket 7 of drivers, since 1,031 modulo 512 is 7. Spark keeps the side with more buckets as it is and shuffles the other into 2048 partitions, so drivers pays a 120GB exchange on every run.

Spark 3.1 added spark.sql.bucketing.coalesceBucketsInJoin.enabled, off by default. When one count divides the other, it reads the larger side at the smaller count, giving up parallelism to drop the exchange.

Trap 3: join columns that differ from the bucket columns

Join keys must equal the bucket columns, in name and in type. A groupBy is looser: its keys must include the bucket columns and may add others. This is what each query on trips, bucketed by driver_id, gets:

Query on tripsExchange addedWhy
Join on `driver_id`, `drivers` in 2048 buckets on itNoneBoth scans already cluster rows on the join key
`groupBy("driver_id", "city")`NoneRows sharing both keys already share a `driver_id` bucket
`groupBy("city")`1Each city's trips sit in all 2048 buckets
Join on `driver_id` and `city`, both sides bucketed on `driver_id`Both sidesThe join needs rows clustered on both keys together
Join to `drivers` whose `driver_id` is a stringThe string sideSpark casts the string side, and the cast column has no bucket layout

The animation plays the groupBy("city") row at small scale: rows are laid out by driver_id first, then aggregated by city.

from pyspark.sql import functions as F
by_driver = trips.repartition(3, "driver_id")
per_city = by_driver.groupBy("city").agg(F.sum("fare").alias("revenue"))
per_city.collect()
trips10 rows
trip_id
driver_id
city
fare
101
7
New York
18
102
3
Austin
12.5
103
7
New York
31
104
5
Denver
9
105
3
Austin
22
106
9
New York
15.5
107
5
Denver
27
108
9
New York
11
109
7
New York
19.5
110
3
Austin
14
Preparing the animation

The second exchange moves every row again, because each city's trips are scattered across all 3 driver partitions. A layout on driver_id is worth nothing to a query that groups or joins on anything else.

Trap 4: the file explosion on write

Leave out the repartition before bucketBy and every write task opens a file for each bucket it holds rows for. A day of trips is read as 16,384 input tasks of 128MB, and hashing scatters rows from nearly every bucket into each of them.

33.5M
files per day without the repartition
1GB
size of each file with the repartition

Trap 5: the parallelism ceiling

A bucketed scan runs 1 task per bucket and never splits a bucket across tasks, so the count fixed at write time is the parallelism of every bucketed join and aggregation that follows. Bucket 2TB into 64 and each of 64 tasks reads 32GB, however many cores the cluster has. Bucket a column with 30 distinct values into 2048 and 2,018 buckets sit empty while 30 tasks do the work.
Checking a bucketed plan
  • ▸Call explain() on the final DataFrame before trusting a layout.
  • ▸Each scan of a bucketed table should read Bucketed: true.
  • ▸No Exchange should sit between a bucketed scan and the join or groupBy above it.
  • ▸In the Spark UI, the stage holding that scan should run as many tasks as the table has buckets.
Multiple Choice

A teammate reads the bucketed trips table by path and joins it to drivers_bucketed, read by name. Both were written with 2048 buckets on driver_id. What does the join's plan contain?

trips = spark.read.parquet("/lake/curated/trips_bucketed/")
drivers = spark.table("curated.drivers_bucketed")
joined = trips.join(drivers, "driver_id")
joined.write.mode("overwrite").saveAsTable("curated.trips_priced")

Cardinality decides whether a column can fill its buckets: a column with fewer distinct values than buckets caps the useful task count at that number. Compare 2 candidate bucket columns on user_events.

from pyspark.sql import functions as F

events = spark.table("user_events")
cardinality = events.agg(
    F.count("*").alias("total_rows"),
    F.countDistinct("user_id").alias("distinct_users"),
    F.countDistinct("country").alias("distinct_countries"),
)
cardinality.show()

Changing a Layout Safely

Daily Life
Interviews

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

Spark batch
Live daily writer
old layout
trips by city
by city
Spark batch
Backfill by ds range
BACKFILL10-day chunks, 2023-12-16 to 2024-03-14IDEMPOTENCYdynamic overwrite per ds
by ds
trips v2
2048 buckets
count
Fingerprint check
distinct idsfare sum per dsERRORrerun the chunk
what readers query
curated.trips view

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.

  • Pick a cutover dayds = 2024-03-15In trips_v2, days before it come from the backfill and days from it on come from the live writer, which keeps writing trips_by_city too until the rollback window closes. No day has 2 writers.
  • Backfill by day rangedynamic partition overwriteEach write covers a range of ds values and replaces exactly those partitions, so a failed or repeated chunk rewrites its own days and nothing else.
  • Fingerprint every dayold and new, compared day by dayRow count, distinct trip ids and fare total per ds must match across the 2 tables before anything switches.
  • Switch the viewa single metadata statementReaders query curated.trips; repointing it at trips_v2 moves every new query at once.
  • Keep the old tableuntil the rollback window closesPointing the view back at trips_by_city undoes the switch with nothing lost only while the live writer still sends it every new day.

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.

from pyspark.sql import functions as F

sales = spark.table("store_sales_raw")
fingerprint = (
    sales.filter(F.col("sale_date").isNotNull())
    .groupBy("sale_date")
    .agg(
        F.count("*").alias("row_count"),
        F.countDistinct("sale_id").alias("distinct_ids"),
        F.round(F.sum("revenue"), 2).alias("revenue_total"),
    )
    .orderBy("sale_date")
)
fingerprint.show()

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
TIP
Run downstream jobs against trips_v2 for a full week of real traffic before dropping trips_by_city. Until then, pointing the view back at the old table is the entire rollback.
Multiple Choice

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?

Layout-Induced Skew

Daily Life
Interviews
Skew is a single task holding far more data than its siblings. A stage ends when its last task does, so that task's runtime becomes the stage's runtime. Most skew arrives with the data. Layout skew is written down: a partition column or bucket key with lopsided values bakes the imbalance into the files, and every job that reads them inherits it.

Large directories still scan evenly

Take 1 day of trips partitioned by city: 300GB under city=New York and 40MB under city=Boise. A scan of both still runs evenly sized tasks, because Spark cuts large files into splits of up to spark.sql.files.maxPartitionBytes, 128MB by default, and packs small files together. New York becomes about 2,400 tasks and Boise 1. Directory size alone does not skew a scan.

Every null lands in 1 bucket

  • Writes keyed on the partition column. repartition("city") before partitionBy("city") gives each directory 1 file, and hands all 300GB of New York to a single task while Boise's task finishes in seconds.
  • Bucketed reads. A bucket is read whole by 1 task, so with 2048 buckets a key holding 5% of the rows makes its bucket about 100 times the size of the rest.
  • Null keys. Every null hashes to the same value, so all trips without a driver share 1 bucket, and any read that keeps them, such as a left join or a groupBy, hands that bucket to 1 task.
The program below left-joins 12 trips to drivers; 5 of those trips have no driver yet.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
joined = trips.join(drivers, "driver_id", "left")
joined.collect()
trips12 rows
trip_id
driver_id
city
fare
201
7
New York
18
202
NULL
New York
24
203
3
Austin
12.5
204
NULL
Austin
9.5
205
5
Denver
27
206
NULL
New York
16
207
9
New York
11
208
NULL
Denver
13.5
209
7
New York
19.5
210
3
Austin
14
211
NULL
New York
21
212
5
Denver
8
drivers4 rows
driver_id
driver_name
rating
3
Ana
4.9
5
Ben
4.7
7
Chen
4.8
9
Dara
4.6
Preparing the animation
All 5 null-key trips meet on the same reducer task. A bucketed write sends rows through the same hash, so on disk those trips would share 1 bucket, and that bucket stays whole in every read.
Multiple Choice

trips is bucketed into 2048 buckets on driver_id, and 8% of a day's 2TB has a null driver_id. In a bucketed left join to drivers, about how much does the task holding the null bucket read?

Detecting skew before it ships

A bucket can never hold less than its hottest key. With n buckets an even bucket holds 1/n of the rows, so any key above that share produces the largest task however high n goes. Before choosing a partition column or bucket key, count rows per value and compare the top share with 1/n. Run that count for country on user_events, with nulls kept as a value of their own, since they share 1 bucket like any other key.

from pyspark.sql import functions as F

events = spark.table("user_events")
by_country = (
    events.withColumn("country_key", F.coalesce(F.col("country"), F.lit("(null)")))
    .groupBy("country_key")
    .agg(F.count("*").alias("row_count"))
    .orderBy(F.desc("row_count"), "country_key")
)
by_country.show()
On a table already written, the Spark UI shows the same thing per task. A stage's summary metrics list the minimum, median and maximum of task duration and input size; a maximum many times the median, on a stage reading bucketed or freshly partitioned data, points at the layout.

Designing around skew

For writes, range partitioning on the partition column plus a high-cardinality column splits the hot value. Spark samples the keys and cuts them into ranges of similar row counts, so New York's trips spread over many ranges and many tasks each write a slice of its directory, while several small cities share 1 range.
(
trips.repartitionByRange(400, "city", "trip_id")
.write.partitionBy("city")
.mode("overwrite")
.saveAsTable("curated.trips_by_city")
)
✓Do
  • Partition by a column with bounded, even values, such as ds
  • Compare the top key's row share with 1/n before choosing a bucket key
  • Write null or placeholder keys to their own table before bucketing
  • Spread a hot partition value on write with repartitionByRange on a second column
✗Don't
  • Repartition by the partition column alone when 1 value dominates
  • Bucket on a key whose nulls or test accounts hold a large share of rows
  • Raise the bucket count to tame 1 hot key; its bucket stays whole

Compaction in Production

Daily Life
Interviews

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:

  • Compact closed hours onlyhour end plus a 2-hour lateness windowOnce late rows stop arriving the writer never touches the hour again, so nothing lands while the compactor reads it.
  • Write to a fresh directoryoutside the live partitionA 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 copyrow counts must matchThe compacted directory must hold exactly as many rows as the source hour, or the run stops before any reader is affected.
  • Repoint the partitiona single metastore updateQueries 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 periodlonger than the longest queryThe 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.
Spark batch
Pings writer
every 5 min
2
pings hour=11
400 files6GB
Spark batch
Compact closed hour
SLAhour end + 2hIDEMPOTENCYfresh run directory
24 files of 256MB
Staging dir
source rows = written rows
Row count check
ERRORstop before repoint
metastore update
Repoint partition
after grace period
Delete old files

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.

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.

Loading the challenge
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.
Multiple Choice

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?

PUTTING IT ALL TOGETHER

> Back in the Uber pricing scenario: the team rewrites trips as trips_v2, partitioned by ds and bucketed into 2048 on driver_id, and writes trips with no driver to a table of their own. The hourly join loses both exchanges and runs 2048 tasks of about 1GB, the city-partitioned table retires a week after the view moves, and the GPS pings table gets a compactor that turns each closed hour's 2,400 files into 24 while dashboards keep querying.

The bucketed write is the pricing join's shuffle paid once and saved, which is why both sides need the same bucket count and every read must go through the table name.
The bucket count fixes 3 things at once: files per day, tasks per read, and the floor on a bucket's size, its hottest key; moving null drivers out is what keeps 2048 buckets even.
The layout move and the compactor follow a single rule: build the new files beside the old ones, check them, switch with a single metadata change, and delete only when no reader can need the old files.
Dynamic overwrite per day range makes the backfill safe to rerun for the same reason a fresh run directory makes compaction safe to rerun: a retry replaces its own output and nothing else.
KEY TAKEAWAYS
A bucketed write pays the key's shuffle once; tables bucketed on the same key into the same count then join and aggregate on it with no exchange.
The layout holds only when reads go through the table name and the counts, key columns and key types all match; explain() then shows Bucketed: true and no Exchange above the scans.
The bucket count sets the files per day and the tasks per read, and no bucket can be smaller than its hottest key, nulls included.
Move a layout beside the old one: a single writer per day, dynamic overwrite per day range, a fingerprint per day, then a view switch.
Layout skew lives where 1 task owns 1 value: writes repartitioned by the partition column, and bucketed reads of a hot or null key.
Compact only closed partitions, into a fresh directory, verify, repoint, and delete the old files after the longest query could have finished.

Lay out files so joins skip the shuffle, layout moves lose nothing, and compaction never breaks a live reader.

Category
Spark
Difficulty
advanced
Duration
15 minutes
Challenges
17 hands-on challenges

Topics covered: Bucketing at Write Time, Bucketing Pitfalls, Changing a Layout Safely, Layout-Induced Skew, Compaction in Production

Lesson Sections

  1. Bucketing at Write Time (concepts: Shuffle Optimization)

    Paying the shuffle once, at write Reading 2 bucketed tables by name The Sort steps stay. In Spark 3 a bucketed scan does not report its sort order to the planner by default, so sortBy does not remove them; the missing exchange is the saving to count on. The bucketed table pays for 1 shuffle when the day is written, and all 24 hourly runs after it join without any.

  2. Bucketing Pitfalls (concepts: Shuffle Optimization)

    Trap 1: reading the files instead of the table Trap 2: bucket counts that differ Spark 3.1 added spark.sql.bucketing.coalesceBucketsInJoin.enabled, off by default. When one count divides the other, it reads the larger side at the smaller count, giving up parallelism to drop the exchange. Trap 3: join columns that differ from the bucket columns Trap 4: the file explosion on write Trap 5: the parallelism ceiling A bucketed scan runs 1 task per bucket and never splits a bucket across tasks, so the

  3. Changing a Layout Safely (concepts: Configuration Tuning)

    The move in 5 steps Overwrite a day, never the table Proving nothing moved twice The switch and the way back

  4. Layout-Induced Skew (concepts: Data Skew)

    Skew is a single task holding far more data than its siblings. A stage ends when its last task does, so that task's runtime becomes the stage's runtime. Most skew arrives with the data. Layout skew is written down: a partition column or bucket key with lopsided values bakes the imbalance into the files, and every job that reads them inherits it. Large directories still scan evenly Every null lands in 1 bucket The program below left-joins 12 trips to drivers; 5 of those trips have no driver yet.

  5. Compaction in Production (concepts: Shuffle Optimization)

    How compaction breaks readers A protocol readers never notice 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. 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