Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 2

Joins and Aggregations at Scale, Shuffle by Shuffle

A worked example on two million trips and their payments: count the rows that cross each shuffle, compare a sort-merge join with a broadcast hash join, fix a fan-out by aggregating before the join, watch adaptive query execution change a plan at run time, and measure a Python UDF against a built-in function.

Contentsand lesson path

What you will learn

  • Write PySpark DataFrame and Spark SQL code that reads Parquet or table-format data, joins and aggregates it, and writes partitioned output.
  • Diagnose data skew, excess shuffles and spills in the Spark UI and fix them with broadcast joins, repartitioning, adaptive query execution or caching where justified.

Prerequisites: Python Foundations

01. The problem

Finance wants a report per pickup zone: trips, fare total and the amount actually paid. The fares are in a trips table of two million rows. The payments table has one row per payment, and 2% of trips were paid in two parts. Zone names come from the lookup table of the lab in lesson 2.

The task is not only to write the query but to know what each version costs: for every step, count the rows that cross a shuffle, name the join strategy, and check the numbers. Run everything from spark-lab/, with session.py, pipeline.py and data/zones from lesson 2 in place. The new tables take about 40 MB.

Python · spark-lab/make_big.py
from pathlib import Path

from pyspark.sql import functions as F

from session import local_session

spark = local_session("make-big")
n = 2_000_000
trips = spark.range(1, n + 1, numPartitions=8).select(
    F.col("id").alias("trip_id"),
    (1 + F.floor(F.rand(11) * 12)).cast("int").alias("pickup_zone_id"),
    F.round(0.5 + F.rand(12) * 20, 1).alias("distance_km"),
    F.round(3 + F.rand(13) * 40, 2).cast("decimal(8,2)").alias("fare"),
)
trips.write.mode("overwrite").parquet("data/big_trips")

# One payment per trip, but 2% of trips are split across two payments.
methods = F.array(F.lit("card"), F.lit("card"), F.lit("cash"), F.lit("app"))
voucher = F.rand(16) < 0.01  # 1% of payments use a voucher
paid_at = F.timestamp_seconds(1772323200 + F.floor(F.rand(18) * 86400 * 31))
payments = (
    spark.range(1, n + 1, numPartitions=8)
    .withColumnRenamed("id", "trip_id")
    .withColumn("parts", F.when(F.rand(14) < 0.02, 2).otherwise(1))
    .withColumn("part", F.explode(F.sequence(F.lit(1), F.col("parts"))))
    .withColumn("method", methods[F.floor(F.rand(15) * 4).cast("int")])
    .withColumn("method", F.when(voucher, "voucher").otherwise(F.col("method")))
    .withColumn("amount", F.round(1 + F.rand(17) * 40, 2).cast("decimal(8,2)"))
    .withColumn("paid_at", paid_at)
    .select("trip_id", "part", "method", "amount", "paid_at")
)
payments.write.mode("overwrite").parquet("data/payments")

for name in ("big_trips", "payments"):
    size = sum(p.stat().st_size for p in Path("data", name).glob("*.parquet"))
    rows = spark.read.parquet(f"data/{name}").count()
    print(f"{name}: {rows} rows, {size / 2**20:.1f} MiB")
spark.stop()
Terminal
python make_big.py
Expected output
big_trips: 2000000 rows, 13.5 MiB
payments: 2039776 rows, 28.1 MiB

02. Step 1: An aggregation, shuffle by shuffle

Start with fare per zone, without payments. The script prints the plan, runs the query in a named job group and prints one row per stage from the REST API with stage_table. Stages skipped because their shuffle files already existed are left out.

Python · spark-lab/shuffle_agg.py
from pyspark.sql import functions as F

from session import local_session, plan, stage_table

spark = local_session("shuffle-agg")
trips = spark.read.parquet("data/big_trips")

per_zone = trips.groupBy("pickup_zone_id").agg(F.sum("fare").alias("revenue"))
print("\n".join(plan(per_zone)))

spark.sparkContext.setJobGroup("agg", "revenue per zone")
print("zones:", len(per_zone.collect()))
stage_table(spark, "agg")
spark.stop()
Terminal
python shuffle_agg.py
Expected output
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[pickup_zone_id], functions=[sum(UnscaledValue(fare))])
   +- Exchange hashpartitioning(pickup_zone_id, 200), ENSURE_REQUIREMENTS, [plan_id=
      +- HashAggregate(keys=[pickup_zone_id], functions=[partial_sum(UnscaledValue(f
         +- FileScan parquet [pickup_zone_id,fare] Batched: true, DataFilters: [], F
zones: 12
stage  tasks  input rows  shuffle write  shuffle read
    1      4     2000000             48             0
    3      1           0              0            48

Read the plan from the bottom. The scan reads only the two columns it needs. The lower HashAggregate computes partial_sum inside each read task, the Exchange shuffles the partial results by zone, and the upper HashAggregate adds them up. Spark splits sum, count, min and avg into this partial and final aggregation.

Stage 1 read 2,000,000 rows in 4 tasks but wrote only 48 rows to the shuffle: one partial row per zone per task, 4 × 12. Without the partial step, two million rows would cross the network. The final stage ran 1 task, not 200, because AQE merged the tiny partitions.

03. Step 2: Two large tables: a sort-merge join, and a fan-out

Both tables are larger than 10 MB, so Spark plans a sort-merge join: it shuffles both sides by trip_id so that equal keys meet in one partition, sorts each partition by the key, and walks the two sorted sides together. The script runs two versions: join first and aggregate after, or sum the payments per trip first and then join.

Python · spark-lab/shuffle_join.py
from pyspark.sql import functions as F

from session import local_session, operators, stage_table

spark = local_session("shuffle-join")
trips = spark.read.parquet("data/big_trips")
payments = spark.read.parquet("data/payments")


def zone_report(trips, payments):
    return (
        trips.join(payments, "trip_id")
        .groupBy("pickup_zone_id")
        .agg(
            F.count("*").alias("trips"),
            F.sum("fare").alias("fare"),
            F.sum("amount").alias("paid"),
        )
    )


def run(name, report):
    ops = operators(report)
    joins = [op for op in ops if op.endswith("Join")]
    print(f"--- {name}: {joins[0]}, {ops.count('Exchange')} Exchange operators")
    spark.sparkContext.setJobGroup(name, name)
    rows = report.collect()
    print("trips counted:", sum(r.trips for r in rows))
    zone = [r for r in rows if r.pickup_zone_id == 1][0]
    print(f"zone 1: {zone.trips} trips, fare {zone.fare}, paid {zone.paid}")
    stage_table(spark, name)


run("join-first", zone_report(trips, payments))

per_trip = payments.groupBy("trip_id").agg(F.sum("amount").alias("amount"))
run("aggregate-first", zone_report(trips, per_trip))

truth = trips.filter("pickup_zone_id = 1").agg(F.count("*"), F.sum("fare")).first()
print("zone 1 in the trips table:", truth[0], "trips,", truth[1], "fare")
spark.stop()
Terminal
python shuffle_join.py
Expected output
--- join-first: SortMergeJoin, 3 Exchange operators
trips counted: 2039776
zone 1: 170130 trips, fare 3905609.43, paid 3578320.68
stage  tasks  input rows  shuffle write  shuffle read
    2      4     2039776        2039776             0
    3      4     2000000        2000000             0
    6      4           0             48       4039776
   10      1           0              0            48
--- aggregate-first: SortMergeJoin, 3 Exchange operators
trips counted: 2000000
zone 1: 166848 trips, fare 3829562.53, paid 3578320.68
stage  tasks  input rows  shuffle write  shuffle read
   11      4     2000000        2000000             0
   12      4     2039776        2000000             0
   15      4           0             48       4000000
   19      1           0              0            48
zone 1 in the trips table: 166848 trips, 3829562.53 fare

The first version is wrong. It counted 2,039,776 trips for 2,000,000, and the zone 1 fare is 3,905,609.43 instead of 3,829,562.53: a trip paid in two parts matched two payment rows, so its fare was counted twice. The paid amount is right in both versions, because each payment appears once either way. When a join multiplies rows, measures of the multiplied side go wrong.

Its stages show the cost of a sort-merge join. Stages 2 and 3 shuffle a whole table each. Stage 6 reads both shuffles, 4,039,776 rows, sorts and merges them and pre-aggregates per zone; stage 10 finishes the sums. The join stage ran 4 tasks, not the 200 of spark.sql.shuffle.partitions, because AQE merged small partitions.

The second version also has three Exchange operators, but the payments side has only one: the groupBy shuffles payments by trip_id, and the join needs exactly that layout, so Spark reuses it. Aggregating to the join key first costs no extra shuffle and makes the payment side one row per trip. The fix comes from knowing each table's grain, as in Grain First, not from a setting.

04. Step 3: A small table: the broadcast hash join

The zone lookup is tiny, so Spark plans a broadcast hash join: the driver collects the small side, builds a hash table and sends a copy to every executor, and each task joins its partition of the large side against that copy. The large side never shuffles. Spark does this when its size estimate for one side is below spark.sql.autoBroadcastJoinThreshold, 10 MB by default, and the join type allows that side to be copied.

Python · spark-lab/broadcast_join.py
from pyspark.sql import functions as F

from pipeline import latest_zones
from session import local_session, operators

spark = local_session("broadcast-join")
trips = spark.read.parquet("data/big_trips")
zones = latest_zones(spark.read.parquet("data/zones"))
payments = spark.read.parquet("data/payments")


def join_names(df):
    return [op for op in operators(df) if op.endswith("Join")]


by_borough = trips.join(zones, trips.pickup_zone_id == zones.zone_id).groupBy("borough")
print("1. zones, default threshold:", join_names(by_borough.count()))

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "-1")
by_borough = trips.join(zones, trips.pickup_zone_id == zones.zone_id).groupBy("borough")
print("2. zones, threshold -1:     ", join_names(by_borough.count()))
hinted = trips.join(F.broadcast(zones), trips.pickup_zone_id == zones.zone_id)
print("3. zones, broadcast hint:   ", join_names(hinted.groupBy("borough").count()))
spark.conf.unset("spark.sql.autoBroadcastJoinThreshold")

vouchers = payments.filter(F.col("method") == "voucher")
voucher_paid = (
    trips.join(vouchers, "trip_id")
    .groupBy("pickup_zone_id")
    .agg(F.sum("fare").alias("fare"), F.sum("amount").alias("paid"))
)
print("4. vouchers, before running:", join_names(voucher_paid))
rows = voucher_paid.collect()
print("   after running:           ", join_names(voucher_paid), "(final, initial)")
print("   voucher payments:", vouchers.count(), "| zones:", len(rows))
spark.stop()
Terminal
python broadcast_join.py
Expected output
1. zones, default threshold: ['BroadcastHashJoin']
2. zones, threshold -1:      ['SortMergeJoin']
3. zones, broadcast hint:    ['BroadcastHashJoin']
4. vouchers, before running: ['SortMergeJoin']
   after running:            ['BroadcastHashJoin', 'SortMergeJoin'] (final, initial)
   voucher payments: 20302 | zones: 12

Lines 1 to 3 show the controls. With the threshold at -1, automatic broadcasting is off and Spark shuffles two million trips to join 12 rows. The hint F.broadcast(zones), or /*+ BROADCAST(z) */ in SQL, asks for a broadcast whatever the threshold. Use it when you know a side is small and the estimate is too high, for example after a selective filter, but not on a side that grows: the driver and every executor must hold the whole copy, and a broadcast of gigabytes fails with an out-of-memory error or a timeout.

Line 4 shows Spark correcting itself. Before the run it planned a sort-merge join, because it estimates a filtered table from the size of its files. At run time AQE measured the shuffle output of the 20,302 voucher payments, found it below the threshold and switched to a broadcast hash join. After a run, explain() prints the final plan, then the initial one.

05. Step 4: Shuffle partitions and adaptive query execution

Every shuffle splits its output into spark.sql.shuffle.partitions partitions, 200 by default. No fixed number suits every query: 200 is far too many for 48 rows and far too few for a terabyte. Adaptive query execution (AQE), on by default since Spark 3.2, re-plans the rest of a query after each shuffle from the real sizes. Its main rules:

  • Coalescing partitions: small neighbouring partitions are merged, which turned 200 planned tasks into 1 in step 1 and into 4 in step 2.
  • Switching the join strategy: a sort-merge join becomes a broadcast hash join when one side turns out small, as in step 3.
  • Splitting skewed partitions: a partition of a sort-merge join that is larger than 5 times the median and than 256 MB, by default, is split into several tasks. Lab 4 needs it.

Coalescing can only merge. When the tasks of a large shuffle each process gigabytes and spill to disk, raise the starting number with spark.sql.shuffle.partitions or spark.sql.adaptive.coalescePartitions.initialPartitionNum. With AQE off, the setting is used as given.

06. Step 5: A Python UDF against a built-in function

A user-defined function (UDF) runs your own Python code on each row, but Spark cannot see inside it. The script labels trips as high or normal fare with a Python UDF and with the built-in when, then counts the high ones.

Python · spark-lab/udf_vs_builtin.py
import time

from pyspark.sql import functions as F

from session import local_session, operators, plan

spark = local_session("udf-vs-builtin")
trips = spark.read.parquet("data/big_trips")


@F.udf("string")
def fare_band_udf(fare):
    return "high" if fare is not None and fare >= 30 else "normal"


fare_band = F.when(F.col("fare") >= 30, "high").otherwise("normal")

for name, band in [("udf", fare_band_udf("fare")), ("built-in", fare_band)]:
    high = trips.withColumn("band", band).filter(F.col("band") == "high")
    print(f"--- {name}:", " > ".join(operators(high)))
    filter_line = next(line for line in plan(high) if "Filter" in line)
    print("Filter" + filter_line.split("Filter")[1])
    start = time.perf_counter()
    print(f"high-fare trips: {high.count()}, {time.perf_counter() - start:.1f} s")
spark.stop()
Terminal
python udf_vs_builtin.py

Plans and counts will match on your machine; the times will not.

Illustrative output
--- udf: Project > ArrowEvalPython > Project > Filter > ArrowEvalPython > FileScan
Filter (pythonUDF0 = high)
high-fare trips: 649933, 10.7 s
--- built-in: Project > Filter > ColumnarToRow > FileScan
Filter ((fare >= 30.00) <=> true)
high-fare trips: 649933, 0.5 s

Both find 649,933 trips. The UDF plan has two ArrowEvalPython operators: Spark sends the fare column in Arrow batches to Python worker processes, runs your function and copies the results back into the JVM. It even ran the UDF twice: it pushed the filter below the new column and copied the UDF call into it, because it treats a UDF as deterministic and cannot see that it is expensive. The built-in version stays in the JVM, and Catalyst rewrote the filter on the label into fare >= 30.00. On the run shown, the UDF version took about 20 times as long.

PySpark uses Arrow for Python UDFs by default since 4.2, which is faster than the old row-by-row path, but the data still crosses a process boundary. Look for a built-in first: pyspark.sql.functions has hundreds, for text, dates, JSON and arrays. Keep UDFs for logic no built-in can express, and prefer a pandas UDF, which handles whole batches.

07. Check your understanding

Practice check · 3 questions

Shuffles, joins and functions

Each question changes one detail of the worked example. Pick the best answer.

Q1. A `groupBy("country").agg(sum("amount"))` reads 1 billion rows in 500 tasks. There are 40 countries, and every task sees all of them. About how many rows does the first stage write to the shuffle?
Q2. Before a run, `explain()` shows a sort-merge join. After the run, the SQL tab of the Spark UI shows a broadcast hash join for the same query. What happened?
Q3. A pipeline cleans phone numbers with a Python UDF that applies one regular expression. What is the main gain from rewriting it with `regexp_replace`?
Practice only: not graded, not saved, not evidence.

08. Apply it

For the practice project you will add one tuning change and measure its effect. Rehearse it here:

  1. Run shuffle_join.py with spark.sql.adaptive.enabled set to false in local_session, and compare the task count of the join stage with the run above.
  2. Join big_trips with the zones from lesson 2 with the threshold at -1, then with the hint, and compare the shuffle write column of stage_table for both runs.
  3. Rewrite the fare band with F.expr("CASE WHEN fare >= 30 THEN 'high' ELSE 'normal' END") and check that the plan matches the built-in version from step 5.

09. Review prompt

Without looking back, explain in your own words:

  • why the first stage of the aggregation wrote only 48 rows to the shuffle;
  • what a sort-merge join does to both inputs, and what a broadcast hash join does instead;
  • why joining payments first counted 2,039,776 trips, and why aggregating first costs no extra shuffle;
  • three things adaptive query execution can change while a query runs;
  • why a Python UDF is slower than when, even with Arrow.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check