Tuning from evidence
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 Friday, 9:15. The nightly job normally takes 90 seconds. On Tuesday it took 41 minutes. Twice it took four and a half. Once it took two, and since the cluster was rebuilt it has stayed above two. Nora drops five log files on your desk: "No guesses. For each one I want the cause, and the proof."
You'll learn to
- Follow a method from "it is slow" to a measured fix
- Find the right number in the Spark UI or the event log
- Boil a stage down to five numbers with plain Python
- Tell skew, spill, small files, a bad broadcast and GC apart
Learn
No guesses: a method
"It got slow" is a symptom, like a fever. A good doctor does not start with the pills. Nora's method has six steps:
- Symptom and scope. Since when? Every run, or one? What changed: the data, the code, the settings, the cluster?
- Find the slow part. The slowest job, then its slowest stage.
- Read that stage's numbers. How many tasks, how their times spread, how much they read, spilled and paused.
- Name the cause the numbers point to, and fix that. One change at a time.
- Measure on the same input: the time, the number that was wrong, and the result.
- Prevent it: an alert on run time and input size, and the evidence kept.
Every step uses data Spark already records.
The method, as a loop
Six steps from symptom and scope through the slowest stage, its metrics, the cause and fix, measuring on the same input, to preventing a repeat, with a loop back when the fix did not help.
Read it top to bottom. If the measurement shows no gain, the arrow at the bottom sends you back to step 3, not to a new guess.
Spark keeps a diary
Spark writes down everything a job does, in two places.
While the application runs, the Spark UI shows it live: a web page with six tabs, each answering one kind of question.
When the application ends, the UI is gone. What stays is the event log: a file with one line for every event. A stage started. A task ended, and here is how long it ran, how much it read, how much it spilled. A program called the history server can replay that file and rebuild the UI.
The event log is off unless you turn it on (spark.eventLog.enabled=true). SwiftKart did, long ago. That is why Nora had five files to hand you.
Six tabs, six questions
The six tabs of the Spark UI as boxes, each with the question it answers: Jobs, Stages, SQL / DataFrame, Storage, Executors and Environment.
Read each box as one tab and the question it answers. The Stages tab also has the table of tasks and a drawing of the stage. The SQL tab shows the plan AQE ended with, and the size of a broadcast.
Question, tab, number
| Question | Where | What to read |
|---|---|---|
| Which stage is slow? | Jobs, then Stages | Duration; the stage the job waited on |
| Is it skew? | Stage summary metrics | Max against median and 75th percentile of duration and shuffle read |
| Is it spilling? | Stage summary metrics | Spill (Memory), Spill (Disk) |
| Is GC hurting? | Executors; stage tasks | GC Time against task time |
| Too many tiny tasks? | Stages | Task count; input or shuffle read per task |
| Did it broadcast? | SQL / DataFrame | BroadcastHashJoin or SortMergeJoin; the broadcast data size |
| Which settings ran? | Environment | Shuffle partitions, AQE, executor memory and cores |
Databricks' rule of thumb for skew: a max task duration 50% or more above the 75th percentile is worth a look.
One line of the diary: a task ends
Runs on Databricks:
{
"Event": "SparkListenerTaskEnd",
"Stage ID": 2,
"Stage Attempt ID": 0,
"Task Type": "ShuffleMapTask",
"Task End Reason": {"Reason": "Success"},
"Task Info": {
"Task ID": 221, "Index": 117, "Attempt": 0,
"Launch Time": 1749266152292, "Finish Time": 1749268552312,
"Executor ID": "4", "Host": "10.0.1.14"
},
"Task Metrics": {
"Executor Run Time": 2400000,
"JVM GC Time": 216000,
"Peak Execution Memory": 2495610880,
"Memory Bytes Spilled": 30094131200,
"Disk Bytes Spilled": 9332326400,
"Shuffle Read Metrics": {
"Remote Bytes Read": 8808038400, "Local Bytes Read": 1258291200,
"Fetch Wait Time": 48000, "Total Records Read": 26000000
},
"Shuffle Write Metrics": {
"Shuffle Bytes Written": 524288, "Shuffle Write Time": 4718592,
"Shuffle Records Written": 2000
}
}
}
A line from Tuesday's log, trimmed and spread over several lines (a real one also carries more metrics). Spark writes one of these, a SparkListenerTaskEnd, when a task ends. Mind the units: run time and GC time (the pauses Java takes to clean up memory) are in milliseconds, sizes in bytes, and Shuffle Write Time in nanoseconds. This task ran 40 minutes, read 9.4 GB of shuffle data and spilled 8.7 GB to disk. Its peak execution memory, 2,380 MB, is its 1/N share of a 16 GB, 4-core executor.
Open a log
import json
from collections import Counter
import sparklog
path = sparklog.write('skew')
print(path, '|', sparklog.describe('skew'))
events = [json.loads(line) for line in open(path)]
print(Counter(e['Event'] for e in events).most_common(4))
ends = [e for e in events if e['Event'] == 'SparkListenerTaskEnd']
print('tasks per stage:', dict(sorted(Counter(e['Stage ID'] for e in ends).items())))
conf = next(e for e in events if e['Event'] == 'SparkListenerEnvironmentUpdate')['Spark Properties']
print('AQE on?', conf['spark.sql.adaptive.enabled'])
The sparklog helper writes the five nights' logs for this lesson. Every task appears twice, once when it starts and once when it ends: count SparkListenerTaskEnd lines, not lines with a Stage ID. And the last line printed already holds a clue.
Five numbers per stage
A stage has hundreds of task lines. Boil them down to five numbers:
- Tasks: how many.
- Median and max of the run time. The median is the middle task when you sort them: the typical one.
- Skew ratio: max divided by median. 1 to 2 is normal. 10 or more means one task does the work of many.
- Spill: the total bytes spilled to disk.
- GC share: GC is garbage collection, the pauses Java takes to clean up memory. Divide total GC time by total run time. Under 10% is fine.
For a stage that reads files, add bytes per task. Tiny inputs read slowly mean a cost per file, not per byte.
Why the median, not the average? One 40-minute task pulls an average up and hides inside it.
Stage numbers from the log
import json, math
import sparklog
def pct(xs, p):
"""Nearest-rank percentile: sort, then take the value at position ceil(p/100 * n)."""
xs = sorted(xs)
return xs[max(0, math.ceil(p / 100 * len(xs)) - 1)]
def stage_metrics(path):
"""Task Metrics of every finished task, by stage."""
out = {}
for line in open(path):
e = json.loads(line)
if e['Event'] == 'SparkListenerTaskEnd':
out.setdefault(e['Stage ID'], []).append(e['Task Metrics'])
return out
MB = 1024 * 1024
for case in ('skew', 'spill'):
print(case + ':', sparklog.describe(case))
for sid, ms in sorted(stage_metrics(sparklog.write(case)).items()):
run = [m['Executor Run Time'] for m in ms]
gc = sum(m['JVM GC Time'] for m in ms) / sum(run)
spill = sum(m['Disk Bytes Spilled'] for m in ms) / MB
print(f' stage {sid}: {len(ms):3} tasks, median {pct(run, 50) / 1000:5.1f} s, '
f'max {max(run) / 1000:6.1f} s, skew {max(run) / pct(run, 50):5.1f}, '
f'spill {spill:5.0f} MB, gc {gc:.0%}')
pct is the nearest-rank percentile: sort, then take the value at position ceil(p/100 × n). The UI can land one task away. Two very different slow stages come out: in the skew run one task out of 200 is 533 times the median, in the spill run every task is slow and every task spills. Change the cases to 'gc' and 'small-files' and read those too.
Tuesday: 41 minutes
Start with the worst night. Tuesday: 41 minutes.
Follow the method. First the job, then its stages, then the tasks of the slowest stage, then the slowest task. Each step narrows the search, and each is a number you can read in the log.
Step through it. Watch for the moment a slow stage turns out to be one slow task.
Tuesday, drilled down: job, stage, task
A tree of Tuesday's run in five steps: the job took 2,455 seconds, stage 2 took 2,414 of them, one of its 200 tasks ran 2,400 seconds and read 9.4 GB, and after turning adaptive query execution back on the stage has 349 tasks and the job takes 91 seconds.
The symptom. The job took 2,455 seconds, where 90 is normal. One run, on Tuesday. The code did not change that day.
Find the slowest stage. Three stages took what they always take. Stage 2, the join, took 2,414 seconds. Read that one.
Read the stage. It had 200 tasks. The median ran 4.5 seconds. The slowest ran 2,400: 533 times the median. Not a slow stage, then. One slow task.
Read the task. It read 9.4 GB of shuffle data, where the median task read 77 MB. Rows with the same key go to the same task, and every guest checkout has
customer_id0. One key holding most of the rows is called skew.Fix one thing, then measure. AQE had been switched off by an old setting. Turned back on, it splits the big partition: 349 tasks, the slowest 5.4 seconds, and the run is back to 91 seconds.
Read the tree top down: the job, its four stages, then the tasks of the slow stage. The number on the right is time. Every number is computed from the two skew logs, before and after the fix.
Stage 2 on Tuesday: 31 cores wait for one
A timeline of stage 2 in the skew run: 31 cores finish 199 tasks within 32 seconds, while one core runs task 117 for 40 minutes, and stage 3 only starts when it ends.
Time runs left to right, and each row is one or more cores. For 40 minutes, 31 of the 32 cores sit idle: more machines cannot help a stage that waits for one task. Computed from the skew log.
The same stage, as the Spark UI shows it
Runs on Databricks:
Details for Stage 2 (Attempt 0)
Summary Metrics for 200 Completed Tasks
Metric Min 25th pct Median 75th pct Max
Duration 3.6 s 4.0 s 4.5 s 5.0 s 40 min
GC Time 0.1 s 0.1 s 0.1 s 0.2 s 3.6 min
Shuffle Read Size 62 MB 69 MB 77 MB 85 MB 9.4 GB
Spill (Memory) 0.0 B 0.0 B 0.0 B 0.0 B 28 GB
Spill (Disk) 0.0 B 0.0 B 0.0 B 0.0 B 8.7 GB
A sketch of the stage page, with the numbers of the log above; the real page shows more rows. Read across one row: the max is about 480 times the 75th percentile, far past Databricks' 50% rule. And the max shuffle read is 124 times the median: skew on a key, not on time alone.
Tuesday's fix, replayed: AQE splits the big partition
A join of orders and customers with 12 shuffle partitions, one of them the 2,600 MB partition of guest checkouts: adaptive query execution reads the real sizes after the map stage and splits the big partition into several tasks.
Step through it: after the map stage Spark knows every partition's real size, and cuts the big one into pieces. AQE does this only in joins, and only when it is on: check the Environment tab.
Two nights at four and a half minutes
Two runs took about 270 seconds. From outside they look the same. Inside they are not.
The first is slow in stage 2. It has only 24 tasks, all slow and all alike: the skew ratio is 1.2. And every one spilled about 1 GB to disk. Even and spilling means each partition is too big for one task's share of memory. Someone left spark.sql.shuffle.partitions=24 behind after a test.
The second is slow in stage 0, the scan. It has 1,276 tasks where it used to have 96. Each reads only 9.6 MB, at 1.9 MB per second where 14 is normal. A streaming job had written the orders as 37,000 tiny files, and every file costs an open and a read of its footer, however small it is.
Nothing spills, and it is still slow
The last two runs show no skew and no spill. Their clue is GC: while Java cleans up memory, the tasks in that executor stand still.
One run spent 31% of stage 2 in GC, and a small stage before it sent 1.6 GB back to the driver. That is the mark of a broadcast join: the driver gathers the small table and copies it to every executor. Someone forced it with a broadcast() hint, and the customers table has since grown to 1.6 GB.
The other shows 22% and 36% GC in the stages that work hard. The job did not change. The cluster did: it was rebuilt as 2 executors of 16 cores with a 64 GB heap each. Many busy threads in one huge heap means long pauses.
Five case files
| Case | Symptom | Evidence | Cause | Fix | Measured |
|---|---|---|---|---|---|
| Skew | 90 s became 41 min | Stage 2: median 4.5 s, max 2,400 s (533 times); one task read 9.4 GB and spilled 8.7 GB | Guest checkouts share customerid 0; AQE switched off by an old config | Turn AQE back on (skew join split), or salt the key | Stage 2: 349 tasks, max 5.4 s; run 91 s |
| Spill | 90 s became 4.5 min | Stage 2: 24 even tasks of about 1 GB shuffle read, each spilling about 1 GB to disk | spark.sql.shuffle.partitions=24, left from a test run | 200 partitions, about 125 MB each | No spill; stage 2 from 227 s to 49 s |
| Small files | 90 s became 4.5 min | Stage 0: 1,276 tasks of 9.6 MB each at 1.9 MB/s per task (healthy: 96 tasks of 128 MB at 14 MB/s) | 37,000 files of 0.33 MB: Spark packs 29 per task, and each one costs an open and a footer read | Compact to files of about 128 MB | Stage 0 from 211 s to 31 s |
| Bad broadcast | 90 s became 2 min; the driver near its limit | Stage 1 returned 1.6 GB of results to the driver; stage 2 spent 31% of task time in GC | A broadcast() hint on a customers table that grew to 1.6 GB | Drop the hint; let the planner choose a sort-merge join | GC back to 3%; run 90 s |
| GC pressure | 90 s became 2.2 min after a rebuild | GC share 22% in stage 0 and 36% in stage 2; no spill, no skew | 2 executors of 16 cores with 64 GB heaps: long pauses, no compressed pointers | 8 executors of 4 cores and 16 GB | GC 3%; run 90 s |
Every number comes from the sparklog logs: sparklog.write(case) before the fix and sparklog.write(case, fixed=True) after it. Skew is the one case more machines cannot help. And more cores do not cure spill: it needs more partitions.
Measure the fix, on the same input
import json
import sparklog
def run_seconds(path):
"""Application end minus application start, from the log."""
t = {}
for line in open(path):
e = json.loads(line)
if e['Event'] in ('SparkListenerApplicationStart', 'SparkListenerApplicationEnd'):
t[e['Event']] = e['Timestamp']
return (t['SparkListenerApplicationEnd'] - t['SparkListenerApplicationStart']) / 1000
print(f"{'healthy':12} {run_seconds(sparklog.write('healthy')):7.1f} s")
for case in sparklog.CASES[1:]:
before = run_seconds(sparklog.write(case))
after = run_seconds(sparklog.write(case, fixed=True))
print(f'{case:12} {before:7.1f} s -> {after:5.1f} s after the fix ({before / after:4.1f}x)')
Time is only half the proof. Also check the number that was wrong (the skew ratio, the spill, the GC share) and that the job's output did not change: a fix that changes the answer is not a fix.
Run time before each fix
Bars comparing the healthy run time of 90 seconds with the spill, small files, bad broadcast and GC pressure runs before their fixes.
Compare each bar with the green one. The skew run, 2,455 s, is left out so the others stay readable: it would be 27 times the healthy bar.
Remember: find the slowest stage, then compare its max with its median. One task far above the rest is skew. Every task slow and alike is something else: read the spill, the GC share and the bytes per task.
Change one thing, then measure on the same input. Three settings changed at once leave you unable to say which one helped, and a faster run on a smaller day proves nothing. And do not tune from a list of "best" settings: every number in this module, partitions, overhead, cores, follows from the data and the evidence.
Numbers to remember
| What | Number | Notes |
|---|---|---|
| spark.eventLog.enabled | false | Turns the event log on. Spark writes it to spark.eventLog.dir, one JSON object per line. Since Spark 4.0 the log rolls over into several files by default (spark.eventLog.rolling.enabled). |
| Events to know | four | SparkListenerEnvironmentUpdate (the settings), SparkListenerStageSubmitted and SparkListenerStageCompleted (when each stage ran), SparkListenerTaskEnd (one per task, with Task Info and Task Metrics). |
| Units in a task line | ms, bytes, ns | Executor Run Time and JVM GC Time: milliseconds. Memory Bytes Spilled, Disk Bytes Spilled and the read sizes: bytes. Shuffle Write Time: nanoseconds. |
| Skew ratio | 1 to 2 is normal | Max over median. 10 or more is one task doing the work of many. |
| GC share | under 10% | The Executors tab turns task time red past it. |
| Wall time of a stage | completion minus submission | What the job waits for. Both times are in the SparkListenerStageCompleted line. |
| AQE skew split | over 5 times the median and over 256 MB | Only in joins, and only when AQE is on. AQE can merge partitions but never makes more, so it cannot fix a count that is too low. |
| Small files per task | up to 128 MB | Spark packs small files into one task and counts each file as 4 MB extra (spark.sql.files.openCostInBytes). So 37,000 files of 0.33 MB became 1,276 tasks of 29 files. |
| spark.sql.autoBroadcastJoinThreshold | 10 MB | Without a hint, the planner broadcasts only a table under this size. A hint forces a broadcast whatever the size. |
Teams keep event logs on object storage (spark.eventLog.dir on S3, ADLS or GCS) and run a script like the ones here after every run, writing each stage's numbers to a table. On Databricks classic compute the Spark UI sits on the cluster's page; serverless compute shows a query profile instead.
What changed at SwiftKart
Five files, five causes, five proofs.
- AQE is back on. Tuesday's 41 minutes became 91 seconds.
- The partition count is back at 200, and the spill is gone.
- The orders are compacted into files of about 128 MB.
- The
broadcast()hint is deleted. - The cluster is 8 executors of 4 cores and 16 GB again.
And one change so there is no next time: after every run a small script reads the event log and writes each stage's five numbers to a table. "It got slow" is now a query.
That is the end of the engine room. So far Spark has run in your browser, on a stand-in. Module 13 gives you a real one: The lakehouse on Databricks, starting with your free workspace.
In one line
To fix a slow Spark job, find the slowest stage, boil its tasks down to a few numbers (max against median, spill, GC share, bytes per task), let them name the cause (skew, spill, small files, a bad broadcast or GC), change one thing, and measure on the same input.
Interview corner
A Spark job that took 20 minutes now takes three hours. Walk me through it.
First scope it: since when, every run, and what changed in data volume, code, configuration or cluster. Then find the slowest job and its slowest stage, and read that stage's numbers: task count, median against 75th percentile and max of task time, shuffle read per task, spill and GC share. Max far above the median with one huge shuffle read is skew; even tasks that all spill mean partitions too big; tiny inputs at low throughput mean small files; high GC with no spill points at executor shape. I change one thing, rerun on the same input, compare time, the bad metric and the output, then add an alert on run time and input size.
How do you tell skew from partitions that are simply too big, using the stage page?
Look at the spread. Skew shows a max task time and shuffle read far above the median and 75th percentile: in one case the max was 533 times the median and read 9.4 GB while the median read 77 MB. Partitions that are too big show even task times that are all long, and spill on every task. The fixes differ: skew needs the key spread (AQE skew join, salting), big partitions need more shuffle partitions or more memory per core.
What is in a Spark event log, and what would you do with it?
It is one JSON object per line, one per SparkListener event: the environment, jobs and stages starting and finishing, and a TaskEnd line per task with its metrics: run time and GC time in milliseconds, spill bytes, input and shuffle bytes, and shuffle write time in nanoseconds. The history server rebuilds the UI from it. I would keep the logs on object storage and compute per-stage summaries after each run, task percentiles, skew ratio, spill and GC share, into a table, so regressions show up as a query instead of a complaint.
GC time is 35% of task time. What do you check and change?
I check the executor shape first: very large heaps and many cores per JVM, especially heaps past 32 GB that lose compressed pointers, make long pauses. Then what makes garbage: RDD code or UDFs that build many objects, caching deserialized objects, or a big broadcast held on every executor. Fixes are smaller executors (4 or 5 cores, heaps under 32 GB), DataFrame code instead of objects, dropping a bad broadcast, and serialized or off-heap storage; then I measure the GC share again, aiming under 10%.