Data Engineering for AnalyticsVol. 21 · Analytics
0 / 0

Shelves / Data Engineering for Analytics

DE·03

Batch Processing and Spark

Processing data too big or too slow for one query on one machine: the map–shuffle–reduce idea, Spark's driver, executors, partitions, lazy plans, stages and tasks, narrow and wide transformations, why shuffles dominate cost, join strategies (broadcast, sort-merge, shuffle hash), data skew and its fixes (broadcasting, salting, adaptive query execution), partition sizing, spills, caching and output files, and when not to use Spark at all; with a lab on 5 million orders comparing join strategies and measuring how one hot key bounds a stage.

17 topics · ~9 min read · 16-question quiz
Updated Suggest a correction

Start here: splitting work across machines

Chapter 01's engines answered questions on 5 million orders in tens of milliseconds on one machine. But some jobs don't fit: years of rider GPS points, every app event, joins of billions of rows, or transformations too complex for SQL. Then the work must be split across many cores and machines, and the central question becomes: how much data has to move between them?

The idea, from MapReduce (2004) onwards:

Text
map:      each worker processes its own slice of the input (filter, parse, compute a key)
shuffle:  rows are sent across the network so that all rows with the same key meet on one worker
reduce:   each worker aggregates or joins the rows for its keys

Map steps are cheap and parallel; shuffles are expensive (serialise, write to disk, send over the network, read back, sort or hash). Almost every Spark optimisation is about avoiding, shrinking or balancing shuffles.

Measured on 5 million orders

Experiment (Spark, local, 2 cores) Time
join orders to 400 kitchens, aggregate by area, sort-merge join (both sides shuffled) 1.70 s
same, broadcast join (the 400 kitchens copied to every task, orders not shuffled) 0.60 s
One hot key: half of all orders on kitchen 1 Largest shuffle partition Bound on the stage with that many cores
no skew, 8 partitions 14% of rows 1.2× the ideal
skewed, 8 partitions 55% of rows 4.4×
skewed, 64 partitions 51% of rows 32.5×

Adding partitions and cores does nothing for skew: the one partition holding the hot key still holds half the data, and the whole stage waits for it.

How deep to go

Volume 17 defines six mastery levels. For batch processing:

Level What you can do
L1 Explain map, shuffle and reduce
L2 Write Spark DataFrame jobs that read, transform and write Parquet
L3 Explain stages, tasks, partitions, join strategies and the optimiser's plan
L4 Diagnose slow jobs from the Spark UI: skew, spills, small files, bad joins
L5 Design batch pipelines: partitioning, incremental processing, cost
L6 Run Spark platforms: cluster sizing, autoscaling, upgrades, multi-tenant fairness

Spark's model

  • A driver builds the plan and schedules work; executors (JVM processes, each with several cores) run tasks, one per partition of data.
  • A DataFrame is a distributed table with a schema; operations build a logical plan; Catalyst optimises it (predicate pushdown into Parquet, column pruning, constant folding, join reordering); the planner picks physical operators; Tungsten executes them with compact binary rows and generated code.
  • An action triggers a job, split into stages at shuffle boundaries; each stage runs one task per partition.
  • explain() prints the plan; the Spark UI shows stages, task times, shuffle sizes, spills and skew. Read both.

Narrow and wide transformations

Narrow (no shuffle) Wide (shuffle)
filter, select, withColumn, map, union, reading files groupBy().agg, join (unless broadcast), distinct, orderBy, repartition, window functions with partitionBy

Chain narrow operations freely; count your wide ones. A job with one shuffle is usually fine; five shuffles on a billion rows is a design problem.

Joins

Strategy How When
broadcast hash join copy the small side to every task; hash it; stream the large side one side small (default threshold 10 MB; raise carefully)
sort-merge join shuffle both sides by key, sort, merge both sides large (Spark's default for big joins)
shuffle hash join shuffle both, build a hash table per partition one side moderately smaller; avoids sorting
bucketed join both tables pre-partitioned and sorted by the key on disk repeated joins on the same key

Before tuning, filter and project early: fewer rows and columns entering a shuffle is the cheapest optimisation. The lab's broadcast join was ~3× faster than sort-merge on one machine; across a network the gap grows.

Skew

A few keys with most of the data (a celebrity kitchen, a default value like 0 or 'unknown', a null) make one task run far longer than the rest; the stage waits for it. Symptoms in the UI: one task's duration and shuffle-read size far above the median.

Fix How
broadcast the other side no shuffle of the skewed side at all
adaptive query execution (AQE) on by default in Spark 3.2+: at runtime, splits oversized shuffle partitions in joins and replicates the matching other side (spark.sql.adaptive.skewJoin.enabled)
salting add a random suffix 0..N−1 to the hot key on the big side, replicate the small side N times, join on (key, salt)
handle the hot value separately process kitchen_id = 1 (or nulls) in its own branch, union the results
two-phase aggregation aggregate by (key, salt), then by key (Spark already pre-aggregates map-side for most aggregates)

The lab's partition measurement shows why: with half the orders on one kitchen, the largest partition held ~50% of rows whether there were 8 or 64 partitions.

Partitions, spills and caching

  • Input partitions follow files (default up to 128 MB each); shuffle partitions default to 200 (spark.sql.shuffle.partitions); AQE coalesces small ones at runtime. Aim for tasks of ~100–200 MB of shuffle data, and at least 2–3 tasks per core.
  • Spills: when a task's data doesn't fit its memory share, Spark writes to disk and merges: correct but slow. Fix by more partitions (smaller tasks), less data (filter, project), or more memory per core.
  • Caching (cache(), persist()) keeps a DataFrame in memory for reuse; useful when it's read several times in one job, wasteful otherwise. Unpersist when done.
  • Driver collections (collect()) bring everything to one machine: use only for small results.

Writing output

  • Write Parquet (or a table format, chapter 07), partitioned by the most common filter (usually date), sorted within files by the next most common.
  • Control file sizes: too many tiny files (one per task per partition) slow every later read; repartition by the partition column before writing, or use the table format's compaction.
  • Make jobs idempotent: write each date partition by overwriting it (dynamic partition overwrite), so retries and backfills don't duplicate (chapter 05's lab).

When not to use Spark

  • Data fits on one machine (up to hundreds of GB with DuckDB or Polars).
  • Data already lives in a warehouse with enough compute: SQL there is simpler.
  • Latency matters in seconds: use stream processing (chapter 06) or a database.

Use Spark when data is very large, processing is complex (custom parsing, ML feature pipelines, graph processing), or your platform (Databricks, EMR, Dataproc) is built around it.

Common traps

  • Unnecessary shuffles (repartition everywhere, orderBy before writing).
  • Ignoring skew, then adding executors that sit idle.
  • Python UDFs in hot paths (rows serialised to Python and back; prefer built-in functions or vectorised pandas UDFs).
  • collect() on big data.
  • Thousands of tiny output files.

Lab: join strategies and a hot key in Spark

Setup. Apache Spark 4 (PySpark) in local mode on the lab machine: local[2] (one JVM, 2 cores), 2 GB driver memory, 8 shuffle partitions, UI off. Input: chapter 01's 5 million orders (Parquet, cached in memory) and a 400-row kitchen table with areas. Times are wall-clock for count() of the aggregated result; the second run of each is reported (the first includes warm-up).

Experiment 1: broadcast vs sort-merge join

orders ⋈ kitchens → group by area → sum(amount), with automatic broadcasting disabled and AQE off so the strategy is the one requested:

Strategy First run Second run Physical plan
sort-merge join 3.68 s 1.70 s SortMergeJoin (both sides shuffled and sorted)
broadcast join (F.broadcast(kitchens)) 0.86 s 0.60 s BroadcastHashJoin

Experiment 2: skew

Half of all orders were reassigned to kitchen 1. To force a shuffle join, the kitchen table was expanded to 2,000 rows (5 per kitchen) and broadcasting disabled.

Run Time
unskewed keys, AQE off 1.92 s
skewed keys, AQE off 2.55 s
skewed keys, AQE with skew-join splitting 2.43 s

With only 2 cores, skew barely showed: one core worked on the hot partition while the other worked through the rest. So the lab also measured shuffle partition sizes (repartitioning by kitchen_id):

Keys Shuffle partitions Largest partition Share of rows Stage bound with one core per partition
unskewed 8 725,000 14% 1.2× ideal
unskewed 64 212,500 4% 2.7× ideal (400 keys hash unevenly into 64 buckets)
skewed 8 2,737,500 55% 4.4× ideal
skewed 64 2,537,500 51% 32.5× ideal

What it shows

  • Avoiding a shuffle beats optimising one: broadcasting the small table made the join ~3× faster, even on one machine with no network.
  • Skew is a scaling problem. On 2 cores it cost little; on a 64-core cluster, the hot partition would take 32× longer than a balanced one while 63 cores sat idle. Measure partition sizes (or read the Spark UI's task metrics) before blaming the cluster.
  • More partitions don't split a key. Only AQE's skew handling, salting, broadcasting, or treating the hot key separately do.
  • First runs include JIT warm-up and planning: compare second runs, and benchmark on realistic data and clusters before deciding.

Try it yourself

  1. Implement salting: add salt = rand() * 16 on the orders side, explode the kitchens side to 16 copies, join on (kitchen_id, salt), and measure partition sizes.
  2. Run Experiment 2 with local[8] on a machine with more cores and compare AQE off and on.
  3. Read explain("formatted") for both joins and find where the exchange (shuffle) happens.
  4. Rewrite Experiment 1 in DuckDB SQL and compare the time with Spark's.

Revision sheet: batch processing and Spark

Key ideas

  • Map (local, parallel) → shuffle (expensive) → reduce.
  • Spark: driver, executors, partitions, lazy logical plans, Catalyst, stages split at shuffles, one task per partition.
  • Narrow vs wide transformations; count your shuffles.
  • Joins: broadcast (small side), sort-merge (default for large), shuffle hash, bucketed.
  • Skew: one key, one partition; fix with broadcast, AQE, salting, separate handling.
  • Partition sizing, spills, caching with care, no collect() on big data.
  • Partitioned, sorted Parquet output with controlled file sizes; idempotent partition overwrites.
  • Don't use Spark when one machine or the warehouse suffices.

Numbers to remember

  • Lab: sort-merge 1.70 s vs broadcast 0.60 s; skew: largest partition ~50% regardless of partition count; bound 32.5× at 64 partitions.
  • Defaults: auto-broadcast 10 MB; 200 shuffle partitions; ~128 MB input splits.

Glossary

  • Stage: a set of tasks between shuffles.
  • Catalyst: Spark's query optimiser.
  • AQE: adaptive query execution.
  • Salting: splitting a hot key with random suffixes.
  • Spill: writing intermediate data to disk when memory is short.