Shuffles, stages and tasks
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:30 on Thursday. Tess wants two numbers from the same 2 billion order lines. Revenue per day comes back in 30 seconds. Revenue per customer takes 25 minutes, and the Spark UI says Shuffle Write: 180 GB. Both queries are one groupBy. Nora reads the two timings and asks: "Same rows, same line of code. So what moved?"
You'll learn to
- Tell narrow steps from wide ones
- Say what a shuffle writes, fetches and costs
- Count the stages and tasks of a job
- Read a stage page by comparing the max with the median
Learn
Some steps need rows to travel
Both queries are one groupBy, so look at what a step needs.
Some steps handle a row wherever it already sits: filter, select, withColumn, map, coalesce. Each task works alone on its own partition and nothing crosses the network. Spark calls these steps narrow.
Other steps need rows from many partitions in one place. To add up the orders of customer 42, all of them must sit together, but they are scattered over every partition. Spark calls these steps wide: groupBy, join (unless it is broadcast, Lesson 12.4), distinct, orderBy, repartition, and a window with partitionBy.
A wide step makes Spark move every row to the partition its key belongs to. That move is called a shuffle. Think of a post office sorting letters by postcode: every letter is picked up, addressed and carried to the right bag.
Six sales through a shuffle
Six sales in three partitions are shuffled into two: each row gets a target partition from the hash of its city, each map task writes one file with a block per target, each reduce task fetches its block from every file, and the rows of one city end up together.
Before. Six sales sit in three partitions, in the order they arrived. London appears in all three. You want the sales grouped by city, in two partitions.
Every row gets an address. The address is hash(key) mod 2. The same city always gives the same hash, so Tokyo and Lagos get partition 0 and every London row gets partition 1.
The write. Each map task sorts its rows by address and writes one file to its own local disk: a block for partition 0, then a block for partition 1.
The read. Each reduce task fetches its own block from every file: 3 files x 2 reduce tasks = 6 blocks to fetch. Now each city is in one place.
After. Each reduce task groups what it fetched. All three London sales met in one partition, although they started in three.
Read each step top to bottom: the old partitions, the files on disk, the new partitions. The colour of a row is the partition its key is sent to.
What the move costs
The move had two halves, and Spark has a name for each.
- Shuffle write. Each task of the earlier stage (a map task) sorts its rows by target partition and writes them to its executor's local disk: one data file, plus a small index file that says where each block starts.
- Shuffle read. Each task of the next stage (a reduce task) fetches its block from every map task's file, over the network when the file is on another machine.
So M map tasks and R reduce tasks make M x R blocks. 200 x 200 is 40,000 fetches. 2,000 x 2,000 is 4 million.
Every row is turned into bytes, written to disk, sent over the network and often sorted. Nothing else Spark does costs as much. Lesson 12.9 goes inside the files.
Every map task writes a block for every reduce task
Three map tasks of stage 0 each write one data and index file; each of the two reduce tasks of stage 1 fetches its block from all three files.
Count the arrows on the right: 3 map tasks x 2 reduce tasks = 6 blocks. The files are named after the shuffle id and the map task, and they stay on the executor that wrote them until the shuffle is no longer needed.
The same shuffle in minispark
import minispark as ms
sales = [('London', 20), ('Tokyo', 5), ('London', 7),
('Lagos', 3), ('Tokyo', 1), ('London', 2)]
rdd = ms.parallelize(sales, 3)
print('before:', rdd.glom())
grouped = rdd.groupByKey(2)
print('after: ', grouped.glom())
print(ms.last_job())
The walkthrough, run for real. last_job() reports 2 stages, 3 + 2 = 5 tasks, and shuffled: 6: all six records were written to the shuffle. minispark sends an integer key to partition key % n and any other key to zlib.crc32(key) % n. Real Spark uses a hash called Murmur3, with the same promise: one key, one partition. Keys do not spread evenly: partition 1 got every London sale.
A shuffle ends a stage
Lesson 12.1 said the DAGScheduler cuts a job into stages "wherever rows move". Now you know the move. The cut is at every shuffle.
- A stage that ends by writing shuffle files is a ShuffleMapStage.
- The last stage, the one that produces the action's answer, is the ResultStage.
Narrow steps never cut. A read, three filters and two maps run as one stage: one pass over each partition.
Each stage runs one task per partition. A read stage has one task per input split. A stage after a shuffle has spark.sql.shuffle.partitions tasks.
And there is a barrier. A reduce task needs a block from every map task, so a stage starts only when all the stages before it have finished. The slowest task decides when a stage ends.
The stage barrier
Four cores run seven tasks of stage 0; one slow task runs until 31 seconds, and the three tasks of stage 1 only start after it.
Each row is one core and time runs left to right. Three cores sit idle from about 20 s to 31 s. Stage 1 cannot start early, because each of its tasks needs a block from every map task, including the slow T2.
Two shuffles, three stages
import minispark as ms
orders = ms.read_csv('data/orders.csv', 4)
per_status = (orders
.map(lambda r: (r['status'], 1))
.reduceByKey(lambda a, b: a + b, 3)
.repartition(2))
per_status.explain()
print(sorted(per_status.collect()))
print(ms.last_job())
explain() lists the stages in the order they run, with one task per partition: 4 + 3 + 2 = 9 tasks. Each shuffle (reduceByKey, then repartition) ended a stage. The first two are ShuffleMapStages and the last is the ResultStage.
Why 200 partitions?
After a shuffle, Spark makes spark.sql.shuffle.partitions partitions: 200 by default, whatever the size of the data.
- For 50 MB, that is 200 tiny tasks that each do almost nothing.
- For 2 TB, it is 200 tasks of 10 GB each, far too big for memory, so they spill to disk.
Adaptive query execution (AQE), on by default since Spark 3.2, fixes the small case. Once the map stage has run, it reads the real block sizes and merges small neighbouring partitions. The driver knows those sizes because its MapOutputTracker records where every block is and how big it is.
For the big case you raise the setting yourself, aiming at 100 to 200 MB per partition. Lessons 12.5 and 12.10 show the sums.
A groupBy, stage by stage
Spark running a groupBy: in stage 1 each input partition is read and partly aggregated by its own task, a shuffle sends every key to one shuffle partition, and in stage 2 one task per shuffle partition finishes the totals.
Press Next step and watch the three parts: stage 1 works inside each partition, the shuffle sends each key to one shuffle partition, and stage 2 finishes the totals. Then move the Shuffle partitions slider and watch stage 2 get more, smaller tasks. Notice that stage 1 already adds up inside each partition before anything moves. The next section says why that matters.
Per day against per customer
Now Tess's two numbers. Adding up does not need every row to travel. Each map task can first add up its own rows per key and ship one record per key. This is called a map-side combine.
Revenue per day: a task's rows shrink to a few hundred partial sums, one per day. Almost nothing crosses the network. 30 seconds.
Revenue per customer: there are millions of customers, so the combine barely shrinks anything. Nearly every row is still shuffled, 180 GB of it. 25 minutes.
DataFrames combine for you: groupBy().agg(F.sum(...)) becomes a partial sum before the shuffle and a final sum after it. In the RDD API you choose: groupByKey ships every value, reduceByKey ships partial sums.
groupByKey against reduceByKey
import minispark as ms
pairs = ms.read_csv('data/orders.csv', 4).map(lambda r: (r['status'], 1))
totals = pairs.groupByKey(3).mapValues(sum)
print(sorted(totals.collect()))
print('groupByKey shuffled', ms.last_job()['shuffled'], 'records')
totals = pairs.reduceByKey(lambda a, b: a + b, 3)
print(sorted(totals.collect()))
print('reduceByKey shuffled', ms.last_job()['shuffled'], 'records')
Same answer, a quarter of the traffic. With groupByKey all 80 rows crossed the shuffle. With reduceByKey each of the 4 tasks shipped one partial count per status, 5 each: 20 records.
The same thing in a real plan
Runs on Databricks:
from pyspark.sql import functions as F
lines = spark.read.parquet("/Volumes/swiftkart/raw/order_lines")
revenue = lines.groupBy("country").agg(F.sum("amount").alias("revenue"))
revenue.explain()
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[country#12], functions=[sum(amount#20)])
+- Exchange hashpartitioning(country#12, 200), ENSURE_REQUIREMENTS, [plan_id=41]
+- HashAggregate(keys=[country#12], functions=[partial_sum(amount#20)])
+- FileScan parquet [country#12,amount#20] Batched: true, DataFilters: [], Format: Parquet, Location: InMemoryFileIndex(1 paths)[/Volumes/swiftkart/raw/order_lines], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<country:string,amount:double>
Read it from the bottom. partial_sum is the map-side combine. Exchange is the plan's word for a shuffle: hashpartitioning(country, 200) sends each row to partition hash(country) mod 200. ENSURE_REQUIREMENTS means the planner added it because the final sum needs all rows of a key together. Count the Exchange lines and you know how many ShuffleMapStages the query has.
The trap: wide steps hide in innocent code. distinct(), dropDuplicates(), orderBy(), a window function with partitionBy, and every join that is not broadcast each add an Exchange. A window with no partitionBy is worse: Spark moves every row into one partition, and its log warns "No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation." Count the Exchange lines in explain() before you blame the cluster.
Skipped stages and lost files
Shuffle files stay on disk after the stage that wrote them. That has a good side and a bad side.
The good side: when a later job needs the same shuffle again (an action repeated on the same DataFrame object, for example), the DAGScheduler does not run those map tasks again. The Jobs page lists the stage as skipped. That is free reuse, not an error.
The bad side: the files sit on one executor. If that executor dies, the next stage's fetches fail with a FetchFailedException, and the DAGScheduler runs the earlier stage again to rebuild the missing files. After 4 failed attempts in a row (spark.stage.maxConsecutiveAttempts) the job is aborted.
An executor dies and takes its files with it
A sequence between the driver and two executors: executor 1 writes shuffle files and dies, a reduce task on executor 2 fails to fetch its block, and the driver reruns the lost map tasks before retrying the reduce task.
Read it top to bottom, in time order. The reduce task did nothing wrong: the files it needed were on a machine that no longer exists, so the earlier stage has to produce them again.
Read the stage page like evidence
Open a slow stage in the Spark UI. For every metric the stage page shows a summary row: the minimum, the median and the maximum over all tasks. Reading it is mostly one habit: compare the max with the median.
If every task is slow, the stage has too much work. That is Tess's per-customer query: 180 GB under Shuffle Write says nearly every row was shipped.
If one task is far slower than the median, one partition got far more rows than the others. That is called skew. The picture shows the stage page of last night's join.
Task durations in last night's join stage
Five bars for the task durations of one stage: minimum, 25th percentile, median and 75th percentile are a few seconds, and the maximum is 2,280 seconds.
Made-up numbers, in the five points the Spark UI shows for a stage. Four bars are too short to see next to the last one. That gap between the max and the median is what skew looks like.
What each stage metric points to
| Metric (summary row) | What it measures | Suspicious when |
|---|---|---|
| Duration | Wall time per task | Max many times the median: one partition is far bigger (skew) |
| Shuffle Read Size / Records | Bytes and rows a task fetched | One task's read dwarfs the median: the hot key |
| Shuffle Read Fetch Wait Time | Time blocked waiting for remote blocks | A big share of duration: slow or lost map-side executors, overloaded disks |
| Shuffle Write Size / Records | Map output written for the next stage | Close to the input size: the combine did not shrink the data |
| Spill (Memory) / Spill (Disk) | Data that did not fit and went to disk | Above zero on most tasks: partitions too big for task memory |
| GC Time | JVM garbage collection | Over about 10% of duration: memory pressure (Lesson 12.8) |
| Scheduler Delay, Task Deserialization Time | Waiting to start, unpacking the task | Large next to tiny durations: too many small tasks, or a huge task |
| Peak Execution Memory | Largest hash table or sort buffer | Near the task's share of memory: a spill is coming |
Spill (Memory) is the size of the data as objects in memory. Spill (Disk) is the same data written as bytes on disk, so it is usually much smaller. Lesson 12.12 works through whole case files with these numbers.
Remember: a shuffle moves every row to the partition of its key, and it ends a stage. The cheapest row to shuffle is the one you filtered out or combined away first.
Numbers to remember
| Thing | Value | What it means |
|---|---|---|
| spark.sql.shuffle.partitions | 200 | Partitions after every shuffle, whatever the data size |
| Adaptive query execution | on by default since Spark 3.2 | Merges small shuffle partitions once the real sizes are known (Lesson 12.10) |
| Blocks in one shuffle | M x R | 200 x 200 = 40,000 fetches; 2,000 x 2,000 = 4,000,000 |
| A good shuffle partition | 100 to 200 MB | Raise the partition count until partitions are about this size |
| spark.stage.maxConsecutiveAttempts | 4 | Failed attempts of one stage before the job is aborted |
| Files per map task | 1 data file + 1 index file | Named after the shuffle id and the map task, kept on the executor that wrote them |
| GC Time | over about 10% of task duration | A sign of memory pressure |
What changed at SwiftKart
You cannot make millions of customers combine the way 365 days do. What you can do is send less into the shuffle.
Tess only needs this quarter, and only two columns. So you filter to the quarter and select customer_id and amount before the groupBy. Fewer rows and narrower rows reach the shuffle, and the Shuffle Write number on the stage page drops with them.
Nora's rule: "Filter early, select early, combine before you shuffle."
One stage page still looks wrong. In the nightly join, 199 tasks finish in seconds and one runs for 38 minutes. Max against median says skew. Lesson 12.4 picks it up: joins at scale.
In one line
A wide step shuffles every row to the partition of its key, which ends a stage and costs disk, network and sorting, so combine or filter before the shuffle and read the stage page by comparing the max with the median.
Interview corner
What is the difference between a narrow and a wide transformation?
In a narrow transformation each output partition depends on one input partition, so tasks run independently with no data movement: filter, select, withColumn, map, coalesce. A wide transformation needs data from many partitions, such as groupBy, join, distinct or orderBy, so it causes a shuffle and starts a new stage.
What is a shuffle, and why is it expensive?
A shuffle redistributes rows so that rows with the same key end up in the same partition. Each map task sorts its rows by target partition and writes a data file and an index to local disk; each reduce task fetches its block from every map task, so there are M x R blocks. It costs serialisation, disk I/O, network and sorting, and the next stage cannot start until every map task has finished.
How does Spark decide where one stage ends and the next begins, and how many tasks each has?
The DAGScheduler cuts the lineage at every shuffle dependency: everything before a shuffle is a ShuffleMapStage that writes map output, and the last stage is the ResultStage that produces the action's answer. Narrow steps are fused into the stage they belong to. A stage has one task per partition of its last step: input splits for a read stage, spark.sql.shuffle.partitions (or AQE's coalesced count) after a shuffle.
A stage is slow. Which metrics do you read first, and what does each tell you?
Max against median Duration and Shuffle Read Size first: a task far above the median with a matching read is skew. Spill on most tasks means partitions too big for task memory; GC Time above about 10% means memory pressure; high Shuffle Read Fetch Wait Time means tasks wait on remote blocks. Tiny durations with large scheduler delay mean too many small tasks.