Two-Phase Aggregation

Concepts covered: Data Skew

A two-phase aggregation computes each key's result in 2 rounds: a partial pass produces a small result per piece of the key, and a final pass per key combines the pieces. Before writing one by hand, check whether Spark already runs it. The animation below groups 7 orders by customer_id and sums amount. Five of the orders belong to c7, and the table is read as 2 partitions. Watch what each map task writes before the shuffle.

orders.groupBy("customer_id").agg(F.sum("amount").alias("total")).collect()
orders
order_idcustomer_idamount
1c740
2c725
3c260
4c735
5c750
6c320
7c745

Each map task sums its own c7 rows before writing, so the reducer that owns c7 receives at most 2 rows for it, 1 per input partition, and adds them to 195. The physical plan shows the same split: a HashAggregate with partial_sum(amount) below the Exchange, and a final HashAggregate with sum(amount) above it. Scale it up: 40M rows of a hot key read by 2,000 map tasks reach their reducer as 2,000 partial sums. That task was never slow, so a hand-salted version of this query adds a second shuffle and a second aggregation and buys nothing. The same holds for count, min, max and avg, which carries a sum and a count through the shuffle.

When the partial pass cannot shrink

The partial pass shrinks a key only when the partial result is smaller than the rows behind it. collect_list and collect_set break that: their partial result holds the values themselves, so all 40M values of a hot key still cross the shuffle to 1 task. Here are the top 5 payment amounts per merchant, written the direct way:

top5 = payments.groupBy("merchant_id").agg(
    F.slice(F.sort_array(F.collect_list("amount"), asc=False), 1, 5).alias("top5")
)

A split works only when the final answer can be computed from the partial answers. For top 5 it can. A value in the overall top 5 is beaten by fewer than 5 values in the whole set, so by fewer than 5 inside its own piece, which keeps it in that piece's top 5. Phase 1 keeps 5 values per (merchant_id, salt) group; phase 2 picks 5 from at most 5 times N survivors per merchant.

N = 32

phase1 = (
    payments
    .withColumn("salt", F.col("txn_id") % N)
    .groupBy("merchant_id", "salt")
    .agg(F.slice(F.sort_array(F.collect_list("amount"), asc=False), 1, 5).alias("top5"))
)

top5 = phase1.groupBy("merchant_id").agg(
    F.slice(F.sort_array(F.flatten(F.collect_list("top5")), asc=False), 1, 5).alias("top5")
)

The hot merchant's 40M amounts now arrive as 32 groups of about 1.25M. Those groups hash across the reducers, so each reducer holds 1 or a few of them instead of all 40M rows, and the merchant's phase-2 task receives at most 160 values. The salt comes from txn_id, a column every row already carries, so each row lands in the same group on every run.

Phase 1 below keeps the top 3 revenues per (store_id, salt) group. Which phase 2 returns each store's exact top 3 revenues?

phase1 = (
    sales
    .withColumn("salt", F.col("sale_id") % 16)
    .groupBy("store_id", "salt")
    .agg(F.slice(F.sort_array(F.collect_list("revenue"), asc=False), 1, 3).alias("top3"))
)

A key holds 40M of a table's rows. For which aggregation does a hand-written salted two-phase version cut the work on that key's reducer?

About this lesson

This section is part of the Data Skew: 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.