Inside a shuffle

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 2:50 a.m. on Thursday. Forty minutes into the nightly join, stage 9 fails with FetchFailedException. Then stage 8, which finished half an hour ago, starts running again. Nora asks one question: "Stage 8 was done. Where did its work go?"

You'll learn to

  • Say what a shuffle leaves on disk, and who reads it
  • Follow one map task as it fills memory, spills and merges
  • Explain why a failed fetch reruns a stage that had finished
  • Work out the number of shuffle partitions from the bytes

Learn

Where did stage 8's work go?

The join needs every order of one customer in the same task. So Spark moves rows between machines: a shuffle (Lesson 12.3).

Stage 8 is the sending side. Its tasks are called map tasks. Stage 9 is the receiving side: reduce tasks.

Between the two, the rows wait on disk. Each map task writes its output to the local disk of its own worker, and each reduce task comes to fetch its share later.

Disk is a choice. The map stage can finish and free its memory before any reduce task starts. And a reduce task that fails can fetch again without the maps running twice. Unless the files are gone.

A shuffle on disk: three map tasks, two reduce tasks

Three map tasks each write one data file and one index file to local disk; each of the two reduce tasks fetches its own byte range from every one of the three files.

Read it left to right: every map task writes one pair of files, and every reduce task reads a piece of every pair. The names follow Spark's pattern shuffle___0; since Spark 3.0 the map id is the task's unique id, so real names carry bigger numbers.

One tray and one card per map task

Think of a post office sorting letters by postcode. A clerk does not keep one tray per postcode. They fill one long tray, ordered by postcode, and write a card saying where each postcode starts.

A map task does the same. Its tray is the data file: all its rows, grouped by the reduce task they are for. That group is the row's partition. Its card is the index file: for R partitions it holds R + 1 numbers, the byte where each partition starts and where the last one ends.

So a shuffle leaves two files per map task. Early Spark wrote one file per map task per reduce task instead: 1,000 map tasks into 1,000 partitions made a million files. Today's design is called the sort-based shuffle.

Write one map output, then fetch from it

import os, struct, zlib

def partition_of(key, n):
    """Which reducer a key goes to (Spark uses Murmur3; crc32 keeps the same promise)."""
    return zlib.crc32(key.encode()) % n

def write_map_output(rows, n, folder, shuffle_id=3, map_id=0):
    """One map task's output: rows sorted by partition in a .data file, n + 1 offsets in an .index file."""
    os.makedirs(folder, exist_ok=True)
    rows = sorted(rows, key=lambda r: partition_of(r[0], n))   # stable: arrival order within a partition
    base = os.path.join(folder, f'shuffle_{shuffle_id}_{map_id}_0')
    offsets = [0]
    with open(base + '.data', 'wb') as data:
        for p in range(n):
            for key, amount in rows:
                if partition_of(key, n) == p:
                    data.write(f'{key},{amount}\n'.encode())
            offsets.append(data.tell())
    with open(base + '.index', 'wb') as index:
        index.write(struct.pack(f'>{n + 1}q', *offsets))      # big-endian 8-byte numbers, as Spark writes them
    return base

def fetch(base, p):
    """What reducer p reads from this map output: two offsets from the index, then one byte range."""
    with open(base + '.index', 'rb') as f:
        f.seek(8 * p)
        start, end = struct.unpack('>2q', f.read(16))
    with open(base + '.data', 'rb') as f:
        f.seek(start)
        return f.read(end - start).decode().splitlines()

rows = [('London', 20), ('Tokyo', 5), ('Madrid', 12), ('London', 7), ('Toronto', 30), ('Lagos', 9)]
base = write_map_output(rows, 4, 'shuffle')
print(sorted(os.listdir('shuffle')))
print('index:', struct.unpack('>5q', open(base + '.index', 'rb').read()))
for p in range(4):
    print('reducer', p, 'reads', fetch(base, p))

A reduce task never scans the whole file: it reads 16 bytes of index, then exactly its own range. Spark does the same, over the network when the file is on another machine.

Six rows before, four partitions after

PartitionRows, in arrival orderBytes in the data fileIndex entries
0Tokyo,5 Lagos,90 to 160, 16
1Madrid,1216 to 2616, 26
2Toronto,3026 to 3726, 37
3London,20 London,737 to 5637, 56

Before: London, Tokyo, Madrid, London, Toronto, Lagos, as they arrived. After: grouped by partition, still in arrival order inside each group, because the writer sorts by partition id only. The index is 5 numbers for 4 partitions: 0, 16, 26, 37, 56.

Inside one map task

How does a map task get its rows into that order? It cannot hold them all. It only has its share of the workbench (Lesson 12.8).

For every row it works out the partition id: hash the key, divide by R, keep the remainder. R is spark.sql.shuffle.partitions, 200 unless you change it.

The row goes into memory as raw bytes, and the task keeps a small pointer to it. When memory runs out, the task sorts the pointers by partition id, writes the rows to disk in that order, and frees the memory. That file is a spill. At the end the task merges its spills into the data file.

Step through a tiny one: the six rows from the table, with room for two.

Six rows, room for two

One map task with room for two rows in memory, in six steps: two rows fill the memory and are spilled sorted by partition, two more are spilled, the last two stay in memory, then the spills and the memory are merged into one data file and an index of five offsets is written.

  1. Two rows arrive. London,20 hashes to partition 3 (p3 for short) and Tokyo,5 to partition 0. The memory is full.

  2. The first spill. The task sorts the two rows by partition id and writes them to disk: Tokyo first, then London. The memory is free again.

  3. Two more rows, a second spill. Madrid,12 (partition 1) and London,7 (partition 3) fill the memory and are spilled the same way.

  4. The last two rows stay in memory. Toronto,30 (partition 2) and Lagos,9 (partition 0). The input is finished, so there is nothing to make room for.

  5. The merge. The task takes partition 0's rows from each spill and from memory, then partition 1's, and so on, and writes them as one data file. The spills are deleted.

  6. The index. Five numbers for four partitions: 0, 16, 26, 37, 56. Reduce task 3 will read bytes 37 to 56 and nothing else.

Watch the two boxes: rows move from memory, on the left, to files on disk, on the right. The data file that comes out is the one in the table above, byte for byte.

A spill is a cost, not a crash

A spill is not a failure. It is extra work: every spilled row is compressed, written, read back and merged.

The stage page of the Spark UI shows two numbers for it. Spill (Memory) is how big the spilled data was while it sat in memory. Spill (Disk) is its size in the files, compressed, so it is smaller.

A little spill is normal. Spill of several times a task's input, on every task, tells you something: each partition is too big for one task's share of memory. The cure is more partitions, or more memory per core. You will size the partitions at the end of this lesson.

A spilling sort, in a few lines

import heapq, json, os

def external_sort(records, limit, folder='spill'):
    """Sort (partition, key) records while holding at most `limit` of them in memory."""
    os.makedirs(folder, exist_ok=True)
    runs, buffer = [], []
    for i, rec in enumerate(records):
        buffer.append(rec)
        if len(buffer) == limit and i < len(records) - 1:   # memory full, more to come: spill
            path = os.path.join(folder, f'run{len(runs)}.json')
            with open(path, 'w') as fh:
                json.dump(sorted(buffer), fh)
            runs.append(path)
            buffer = []
    streams = [map(tuple, json.load(open(p))) for p in runs]
    return list(heapq.merge(*streams, sorted(buffer))), len(runs)

keys = [107, 103, 112, 105, 109, 101, 114, 106, 102, 111]
out, spills = external_sort([(k % 4, k) for k in keys], limit=3)
print('spills:', spills, '| files:', sorted(os.listdir('spill')))
print(out)

heapq.merge reads the sorted runs side by side and always takes the smallest head. That is how Spark merges its spill files. Try limit=10: no spill files at all.

Three writers, and Spark picks

What you stepped through is one of three shuffle writers. Spark picks one for each shuffle. You do not choose.

  • Bypass: for 200 partitions or fewer. The task skips the sort. It writes one small file per reduce task, straight through, then glues them into the one data file. No sort and no spill, but 200 files open at once.
  • Serialized: above 200 partitions. Rows as raw bytes plus pointers: the walkthrough.
  • Sort: when rows must be combined before they leave the map task (a map-side combine), as in an RDD reduceByKey. It keeps whole objects, which is slower.

A DataFrame groupBy does its combining in an earlier step of the plan, before the shuffle. So its shuffle has nothing left to combine.

How Spark picks the writer

A decision flow of three questions: rows combined before leaving leads to the sort writer; otherwise 200 partitions or fewer leads to the bypass writer; otherwise rows that can move as raw bytes lead to the serialized writer, and the rest to the sort writer.

Start at the first question and follow the answers. A DataFrame shuffle has nothing to combine at this point, so it ends at bypass or at serialized.

Now a bigger one: slide the memory

A map task reads 32 blocks into a buffer that holds 10, spills three sorted runs to disk, merges them with the last buffer into one data file with an index of five offsets, and four reducers fetch their segment from every map task.

Step through it first: the same fill, spill and merge as the walkthrough. Then slide the memory up to 1,024 MB: nothing spills, and every byte is written once instead of twice. Then try the other two writers.

The reduce side comes to collect

Now stage 9. A reduce task does not know where its rows are. It asks the driver, which keeps a list of every map output: which machine holds it, and how big each piece is. The map tasks reported that when they finished.

Then the reduce task fetches its piece of every map output. Spark calls one such piece a block. Blocks on its own machine come straight from disk. The rest come over the network, a few at a time: at most 48 MB in flight.

Count the blocks. M map tasks and R reduce tasks make M × R of them. 2,000 map tasks into 20,000 partitions is 40 million small reads. Too many partitions hurts as much as too few.

Thursday, 2:50 a.m.: one fetch fails

A conversation between a reduce task, the driver and executor 2 in five steps: the reduce task asks the driver where the map outputs are, fetches its pieces, executor 2 is killed, the next fetch is refused, and the driver reruns the map stage.

  1. Where are my rows? The reduce task asks the driver for the map outputs of shuffle 3. The driver answers with a host and a size for each one.

  2. The fetch. The reduce task asks each host for its block, and the bytes come back. So far, a normal night.

  3. An executor dies. Executor 2 wrote map output 7. It is killed for using too much memory: exit code 137, the container kill of Lesson 12.8. Its files on local disk go with it.

  4. The fetch fails. The reduce task asks for map 7's block. Connection refused. It tries 3 more times, 5 seconds apart, then gives up with FetchFailedException.

  5. The driver reruns the map stage. Running the reduce task again would fail again, because the data is gone. So the driver runs stage 8 again for the missing outputs, and then stage 9.

Read it top to bottom: each arrow is one message, and a dashed arrow is a reply.

The files died with the executor

That is the answer to Nora's question. Stage 8 was done, but its work lived on local disks. Unless you set it up otherwise, the executor that wrote a shuffle file is also the one that serves it. Thursday's container kill took executor 2, and its files went with it.

So read FetchFailedException as an echo, not a cause. Look in the log for an executor lost right before it: killed for memory, a machine taken back by the cloud, a long garbage-collection pause, a full disk.

Spark gives a stage 4 attempts in a row, then fails the job.

Some clusters protect the files: the external shuffle service, a small process on every machine, serves them even after the executor is gone.

The echo, in the driver log

Runs in the cloud:

WARN TaskSetManager: Lost task 41.0 in stage 9.0 (TID 3120) (10.0.1.15 executor 4): FetchFailed(BlockManagerId(2, 10.0.1.12, 7337, None), shuffleId=3, mapIndex=7, mapId=1873, reduceId=41, message=
org.apache.spark.shuffle.FetchFailedException: Failed to connect to /10.0.1.12:7337
INFO DAGScheduler: Marking ResultStage 9 (save at NativeMethodAccessorImpl.java:0) as failed due to a fetch failure from ShuffleMapStage 8 (save at NativeMethodAccessorImpl.java:0)
INFO DAGScheduler: Resubmitting ShuffleMapStage 8 (save at NativeMethodAccessorImpl.java:0) and ResultStage 9 (save at NativeMethodAccessorImpl.java:0) due to fetch failure

Trimmed. Two minutes earlier the same log says executor 2 exited with code 137: the real cause was a container kill, and the fetch failure was its echo. When an executor's outputs are missing from the driver's records you see MetadataFetchFailedException: Missing an output location for shuffle 3 partition 41 instead.

Remember: a shuffle is files on local disks. Lose the executor and you lose its files, and the stage that wrote them runs again.

Size the partitions from the bytes

One number is left: R. The default 200 is a guess, and you can do better. A common rule of thumb is 100 to 200 MB of shuffle data per partition.

SwiftKart's month-end job writes 600 GB of shuffle data (read Shuffle Write on the stage page) on 150 cores. One line per step:

  • 600 GB is 614,400 MB.
  • 614,400 / 200 = 3,072 partitions.
  • Round up to a multiple of the cores: 3,150. That is 21 full waves of 150 tasks.
  • Check the memory: on 30 GB, 5-core executors a task may hold 3,650 MB (Lesson 12.8). Plenty for 200 MB, even after it grows in memory.

The default 200 would make 3 GB partitions that spill every time.

600 GB of shuffle, cut four ways

Bars comparing the size of each shuffle partition for 600 GB of shuffle data at 200, 1,000, 3,150 and 20,000 partitions.

Each bar is the size of one partition. At 20,000 partitions each is only 31 MB, but 2,000 map tasks would write 40 million blocks to fetch.

Do not read spill as an error, or a FetchFailedException as a cause. Spill is a cost to measure. A fetch failure is the echo of a lost executor, so find out why it was lost. And do not set spark.sql.shuffle.partitions once for every job: 200 suits about 20 to 40 GB of shuffle and is wrong for 2 GB or 2 TB.

Numbers to remember

SettingDefaultWhat it is
spark.sql.shuffle.partitions200R: how many partitions a DataFrame shuffle makes. Spark hashes the key with Murmur3 to pick one.
Sort-based shuffledefault since Spark 1.2, the only one since 2.0Two files per map task. The old hash shuffle wrote M × R files.
spark.shuffle.sort.bypassMergeThreshold200At or under it, with nothing to combine, Spark uses the bypass writer.
spark.shuffle.file.buffer32 KBThe buffer of each open file. The bypass writer with 200 partitions holds 200 × 32 KB = 6,400 KB per task.
Serialized writerup to 16,777,216 partitionsIts 8-byte pointer packs the partition id (24 bits) with the row's address. It needs nothing to combine and a serializer that can move rows as raw bytes: Spark SQL's own, or Kryo.
spark.shuffle.compress, spark.shuffle.spill.compresstrueShuffle files and spills are compressed, with spark.io.compression.codec (lz4).
spark.reducer.maxSizeInFlight48 MBHow much one reduce task fetches at a time. Very large blocks go to disk, not memory. Waiting shows as Shuffle Read Fetch Wait Time.
spark.shuffle.io.maxRetries, spark.shuffle.io.retryWait3, 5 sRetries of one fetch before FetchFailedException.
spark.stage.maxConsecutiveAttempts4Failed attempts of one stage in a row before the job is aborted.
spark.shuffle.service.enabledfalse (port 7337)The external shuffle service: a long-running process on each node (a YARN auxiliary service, or part of the standalone worker). It makes dynamic allocation (Spark adding and removing executors as the load changes) safe on YARN: idle executors can leave without losing shuffle output.
spark.dynamicAllocation.shuffleTracking.enabledtrue in Spark 4.0Kubernetes has no shuffle service. This keeps executors that hold shuffle data alive instead.
spark.shuffle.push.enabledfalsePush-based shuffle (Spark 3.2+, YARN with the shuffle service only): map tasks also push their blocks to shuffle services that merge them per partition, so reduce tasks read a few large files.
spark.sql.adaptive.advisoryPartitionSizeInBytes64 MBThe size AQE aims for when it merges small partitions (next lesson). AQE never makes more partitions, except by splitting skewed ones in a join: an R that is too low stays too low.

The driver's list of map outputs is called the MapOutputTracker. After the fetch, the blocks feed a sort (for a sort-merge join) or a hash table (for a group-by) on the reduce side, and that step can spill in turn.

On Databricks, spark.sql.shuffle.partitions=auto lets the platform choose the count from the data. Teams on YARN run the external shuffle service so dynamic allocation can scale down safely. On Kubernetes they rely on shuffle tracking, on executor decommissioning, or on a remote shuffle service such as Apache Celeborn, which keeps shuffle data off the executors entirely.

What changed at SwiftKart

The memory fix from Lesson 12.8 stopped the kills, so no executor takes its shuffle files down with it. Stage 8 now runs once.

You also stopped using 200 partitions for everything. Each nightly job works out its count from yesterday's shuffle bytes. The month-end job went from 200 partitions of 3 GB to 3,150 of 195 MB, and its spill is gone.

Nora's next question: "Why do we set this number by hand at all? Once the map stage has finished, Spark can see the real sizes." It can. Changing the plan in the middle of a run is the next lesson: Adaptive query execution.

In one line

A shuffle is files on local disk: each map task sorts its rows by partition, spilling when memory runs out, into one data file plus an index, each reduce task fetches its byte range from every map output, a lost executor means a failed fetch and a rerun of the map stage, and you size partitions at 100 to 200 MB of shuffle data.

Interview corner

Walk through what happens on disk during a shuffle.

Each map task computes a partition id for every row from a hash of the key, mod the number of shuffle partitions. With the serialized writer the rows go into memory pages and 8-byte pointers into an array; when memory runs out the pointers are sorted by partition id and the rows written to a spill file. At the end the spills and what is left are merged into one data file, partition 0 first, plus an index file of R + 1 offsets. A reducer asks the driver where the outputs are, then fetches its byte range from every map task, at most 48 MB in flight.

Why does Spark rerun a stage that already finished after a FetchFailedException?

A fetch failure means the map output a reducer needs no longer exists, usually because the executor holding it was lost. Retrying the reducer cannot help, so the DAGScheduler marks those outputs lost, resubmits the parent map stage to recompute just the missing outputs, then reruns the failed stage. After 4 consecutive failed attempts (spark.stage.maxConsecutiveAttempts) it aborts the job. The useful question is why the executor was lost: an OOM kill, a preempted node, a long GC pause or a full disk.

What does the external shuffle service do, and when do you need it?

It is a long-running process on each node that serves shuffle files written by executors on that node, so the files survive when the executor exits. You need it for dynamic allocation on YARN, so idle executors can be removed without losing shuffle output, and it also protects against an executor crashing after its map stage. It listens on port 7337 by default. Kubernetes has no shuffle service, so Spark there uses shuffle tracking or decommissioning, or a remote shuffle service.

How many shuffle partitions would you use for 600 GB of shuffle data?

I aim for about 100 to 200 MB per partition: 614,400 MB / 200 MB = 3,072, rounded up to a multiple of the cores, say 3,150 on 150 cores, so the waves are full. I check that a task's share of execution memory, about 3.6 GB on 30 GB 5-core executors, comfortably holds a 200 MB block. The default 200 would give 3 GB partitions that spill; 20,000 would give 31 MB partitions and 40 million blocks to fetch. With AQE on I can start higher and let it coalesce, since it merges but never adds partitions.