flashpoint / case study · spark 4 physical plan autopsy

Engineering Case Study · Apache Spark 4.0.2 · 42.36M Real Rows

Beating Catalyst by 3.89× inside stock Spark.

When a 113-line Spark physical plan shuffles 107 MB to join a 4.5 MB aggregate, SQL is not the only lever. We opened the operator tree across three public Hugging Face datasets and benchmarked SQL rewrites alongside direct SparkSessionExtensions plan hooks.

3.89×Faster wall time on 19.7M NYC Taxi rows with unmodified SQL
23.7×Less shuffle I/O (107.45 MB → 4.53 MB) by stripping left Exchange
3.31×Faster on 22.28M Aviation Weather rows via single-pass fusion
100%Canonical SHA-256 & row-level output equivalence across every win

01 / Inside the 113-line physical plan

Why stock Catalyst leaves 70% of your runtime on the table.

On DinoPonjevic/NYC_TaxiData_RAW (13.4M March Uber/Lyft rides joined against 6.3M February Yellow Taxi corridors), Apache Spark 4.0.2 with Adaptive Query Execution enabled emits a 113-line EXPLAIN FORMATTED tree. Four default planner decisions dominate the bill:

L035 · 102.9 MBBlind 200-partition shuffle

Because the pre-aggregated corridor table exceeds Spark's default 10 MiB broadcast threshold, Catalyst inserts a SortMergeJoin and shuffles all 5.32M filtered March rows across 200 partitions.

L039 · L076Double external sort

SortMergeJoinExec forces a full key sort on both streams before probing. Removing the left shuffle eliminates both the network write and the CPU sort.

ParquetSingle-row-group stall

Raw public Parquet exports often ship with row_groups = 1, pinning a 13.4M-row scan onto 1 CPU core. Splitting to 16 row groups unlocks 4× scan concurrency.

Side-by-side comparison of Stock Catalyst 113-line SortMergeJoin operator tree versus Direct SparkPlan Hook BroadcastHashJoin tree.
Stock Catalyst (left) shuffles and sorts 5.32M rows at L035–L039. DirectBroadcastRule (right) strips the left Exchange and Sort, keeping 4.53 MB on the build side.

02 / Bypassing SQL limits with SparkSessionExtensions

Mutating the physical SparkPlan on unmodified SQL.

Rewriting SQL by hand is brittle, and some teams cannot alter BI-generated queries at all. Spark exposes JVM extension hooks in SparkSessionExtensions that transform the physical operator tree after Catalyst plans it — with zero changes to incoming SQL.

SparkSessionExtensions pipeline showing QueryStagePrepRule and QueryStageOptimizerRule mutating the physical plan and caching HashedRelation across queries.
FlashpointPlanExtensions intercepts SortMergeJoinExec at QueryStagePrep, strips the streaming shuffle/sort, and reuses materialized HashedRelations via CachedBroadcastLeafExec.

01DirectBroadcastRule

Registered via injectQueryStagePrepRule. Detects SortMergeJoinExec whose build branch contains a compact HashAggregateExec, strips the streaming Exchange + SortExec, and rewrites it to BroadcastHashJoinExec.

02BroadcastStageCache

Captures materialized BroadcastExchangeExec relations in injectQueryStageOptimizerRule keyed by normalized leaf scan + mode. Repeat runs swap in CachedBroadcastLeafExec with zero build recompute.

Why automated SHA-256 verification caught a subtle SQL rewrite bug: When optimizing the Hacker News self-join by pre-aggregating comments before joining stories, writing AVG(s.score) shifted the average from per-comment weighting to per-story weighting (digest 1b2aba48c298 vs baseline e8a4c3fb4b0b). Rewriting to SUM(c.c_cnt * s.score) / SUM(c.c_cnt) restored exact parity — whereas mutating the physical join operator preserved e8a4c3fb4b0b automatically on the very first try.

03 / Multi-dataset empirical benchmark

42.36 million real rows, zero synthetic padding.

Every measurement below ran locally on Apache Spark 4.0.2 (local[4], 6 GB driver, default 10 MiB autoBroadcastJoinThreshold, AQE enabled) with ground-truth stage telemetry collected from Spark UI :4040/api/v1.

1. NYC Taxi Corridors — DinoPonjevic/NYC_TaxiData_RAW (19.7M rows)

SHA-256: 704d60709447 · Exact Match
split_stock (200 parts) 8,833.7 ms · 122.8 MB shuf
raw_stock_warm (1 RG) 6,290.4 ms · 107.5 MB shuf
raw_sql_opt (BROADCAST) 5,429.1 ms · 4.53 MB shuf
raw_ext_prime (hook only) 4,697.4 ms · 4.53 MB shuf
split_ext_cached (hook hit) 2,272.3 ms · 3.89× faster

2. US Aviation Weather — Arimancy/bts-flights-weather (22.28M rows)

EXACT_MATCH: True · 25/25 rows

Joining 2024 severe weather events back to multi-year station×month×hour climate norms forces Catalyst to scan 22.28M rows twice and execute a SortMergeJoin. Single-pass conditional aggregation computes both in one scan and broadcasts the 82 KB airports lookup.

baseline (2 scans + SMJ) 10,698.0 ms · 30.2s exec
single_pass_fusion 3,235.2 ms · 3.31× faster
Single-pass fusion eliminates the second 22.28M row scan and SortMergeJoin, cutting execution stages from 6 to 4.

3. Hacker News Threads — open-index/hacker-news (382,681 rows)

SHA-256: e8a4c3fb4b0b · Exact Match
hn_stock_cold 1,001.7 ms · 1,474 ms exec
hn_stock_warm 491.3 ms · 348 ms exec
hn_ext_prime (hook) 289.4 ms · 162 ms exec

Full telemetry breakdown (Spark UI :4040)

Workload Baseline Wall Optimized Wall Exec Compute Shuffle Write Verification
NYC Taxi (Split 16 RG) 8,833.7 ms 2,272.3 ms (3.89×) 31,611 → 7,208 ms (4.39×) 122.84 → 10.86 MB sha 704d60709447
NYC Taxi (Raw 1 RG) 6,290.4 ms 4,697.4 ms (1.34×) 16,517 → 4,506 ms (3.67×) 107.45 → 4.53 MB sha 704d60709447
Aviation Weather (22.28M) 10,698.0 ms 3,235.2 ms (3.31×) 30,178 → 10,788 ms (2.80×) 6.61 → 3.88 MB EXACT_MATCH: True
Hacker News (383K) 1,001.7 ms 289.4 ms (3.46×) 1,474 → 162 ms (9.10×) 0.99 → 0.89 MB sha e8a4c3fb4b0b

04 / Inspect the queries

What changed across each dataset.

Switch between workloads to compare the stock query against the physical hook or single-pass transformation.

Stock SQL (triggers 107.45 MB SortMergeJoin)

WITH feb_corridor AS (
  SELECT PULocationID AS pu, DOLocationID AS do_loc,
         HOUR(tpep_pickup_datetime) AS hr,
         COUNT(*) AS feb_yellow_trips,
         AVG(total_amount) AS feb_avg_fare,
         AVG(trip_distance) AS feb_avg_dist
  FROM yellow_raw
  WHERE total_amount > 0 AND PULocationID IS NOT NULL
  GROUP BY 1, 2, 3
)
SELECT m.PULocationID, m.hvfhs_license_num, COUNT(*), ...
FROM fhvhv_raw m
LEFT JOIN feb_corridor c
  ON m.PULocationID = c.pu AND m.DOLocationID = c.do_loc
 AND HOUR(m.pickup_datetime) = c.hr ...

With FlashpointPlanExtensions (SQL unchanged)

-- Exact same SQL submitted over Spark Connect.
-- DirectBroadcastRule @ QueryStagePrep rewrites:

SortMergeJoinExec(leftKeys, rightKeys, LeftOuter,
  SortExec(ShuffleExchangeExec(200, fhvhv_raw)),
  SortExec(ShuffleExchangeExec(200, HashAggregate(feb))))

  ===>

BroadcastHashJoinExec(leftKeys, rightKeys, LeftOuter,
  BuildRight, fhvhv_raw /* 0 MB shuffle */,
  CachedBroadcastLeafExec(feb_corridor))

Stock SQL (2 scans × 22.28M rows + SMJ)

WITH climo_norm AS (
  SELECT isd_station_id, MONTH(observation_hour_utc) AS mo,
         HOUR(observation_hour_utc) AS hr,
         AVG(temp_c) AS norm_temp_c,
         AVG(wind_speed_ms) AS norm_wind_ms
  FROM weather
  WHERE NOT obs_missing AND temp_c IS NOT NULL
  GROUP BY 1, 2, 3
)
SELECT a.iata_code, a.state, COUNT(*) AS severe_hours_2024, ...
FROM weather w
JOIN climo_norm c ON ...
JOIN airports a ON w.isd_station_id = a.isd_station_id
WHERE w.observation_hour_utc >= TIMESTAMP '2024-01-01' ...

Single-Pass Self-Join Fusion (1 scan, 3.31× faster)

WITH single_pass_station_cell AS (
  SELECT isd_station_id, MONTH(observation_hour_utc) AS mo,
         HOUR(observation_hour_utc) AS hr,
         AVG(temp_c) AS norm_temp_c, AVG(wind_speed_ms) AS norm_wind_ms,
         SUM(CASE WHEN <2024_severe> THEN 1 ELSE 0 END) AS cell_severe,
         SUM(CASE WHEN <2024_severe> THEN wind_speed_ms ELSE 0 END) AS w_sum
  FROM weather WHERE NOT obs_missing AND temp_c IS NOT NULL
  GROUP BY 1, 2, 3 HAVING cell_severe > 0
)
SELECT /*+ BROADCAST(a) */ a.iata_code, a.state, SUM(cell_severe),
       ROUND(SUM(w_sum - cell_severe * norm_wind_ms) / SUM(cell_severe), 2)
FROM single_pass_station_cell s JOIN airports a USING (isd_station_id)
GROUP BY 1, 2 ORDER BY 3 DESC, 1 ASC LIMIT 25;

Stock SQL (self-join across viral threads)

WITH story_authors AS (
  SELECT id AS story_id, by AS author,
         COUNT(*) AS dummy_cnt, AVG(score) AS story_score
  FROM hn WHERE parent = 0 AND by != ''
  GROUP BY id, by
)
SELECT s.author, COUNT(*) AS comment_cnt,
       ROUND(AVG(s.story_score), 2) AS avg_story_score
FROM hn c
JOIN story_authors s ON c.parent = s.story_id
WHERE c.parent > 0 AND c.by != ''
GROUP BY s.author ORDER BY comment_cnt DESC LIMIT 20;

DirectBroadcastRule + BroadcastStageCache

-- Query 1 (Prime): 289.4 ms | 162 ms exec | sha=e8a4c3fb4b0b
-- DirectBroadcastRule bypasses ShuffleExchange on comments,
-- and ReuseBroadcastCaptureRule caches story_authors HashedRelation.

-- Query 2 (Cached): 312.9 ms | 198 ms exec | sha=e8a4c3fb4b0b
-- ReuseBroadcastSwapRule hits [FP-SWAP-HIT] and injects
-- CachedBroadcastLeafExec directly into BroadcastHashJoinExec.

Flashpoint DB

See every operator cost inside your own AWS account.

Flashpoint renders every Spark query as an operator tree with per-node duration and per-second Fargate Spot billing. Join the waitlist or run the full stack locally in two minutes.

One email when a batch opens. Or try it tonight with the local quickstart.