Bucketing at Write Time
Concepts covered: Shuffle Optimization
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()| 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 |
| driver_id | driver_name | rating |
|---|---|---|
| 3 | Ana | 4.9 |
| 5 | Ben | 4.7 |
| 7 | Chen | 4.8 |
| 9 | Dara | 4.6 |
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()| 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 |
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.
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
- 51TB
The bucketed table pays for 1 shuffle when the day is written, and all 24 hourly runs after it join without any.
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()- 0, because every step runs inside the driver_id buckets
- 1, a range exchange for the orderBy, while the join and groupBy reuse the buckets
- 2: an exchange for the join and another for the orderBy, since joins always exchange
- 3: an exchange for each wide step, the join, the groupBy and the orderBy
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.