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()
trips
trip_iddriver_idcityfare
1017New York18
1023Austin12.5
1037New York31
1045Denver9
1053Austin22
1069New York15.5
1075Denver27
1089New York11
1097New York19.5
1103Austin14
drivers
driver_iddriver_namerating
3Ana4.9
5Ben4.7
7Chen4.8
9Dara4.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

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()
trips
trip_iddriver_idcityfare
1017New York18
1023Austin12.5
1037New York31
1045Denver9
1053Austin22
1069New York15.5
1075Denver27
1089New York11
1097New York19.5
1103Austin14

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.

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()

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.