Sub topic 16
Tuning size with a measure-and-adjust loop
This chapter assumes you know Spark jobs, stages, tasks, partitions, and shuffles. It also assumes you can run a notebook or job in a Databricks workspace and understand the cost split between DBUs and cloud instances, covered in earlier chapters.
Why sizing is a loop
Every sizing method in this tutorial gives you a starting point. Data volume, core counts, and partition counts produce an estimate, and the estimate is a guess. Real jobs differ in skew, join shape, caching, and file layout. The only reliable way to find the right size is to run the job, measure it, change one thing, and run it again.
The loop has five steps.
- Record a baseline: run time, cost, and key Spark metrics.
- Read the signals in the Spark UI and cluster metrics.
- Name the bottleneck.
- Change one setting.
- Re-run and compare against the baseline.
Step 1: record a baseline
Before changing anything, write down what the job does today. A baseline needs these values:
- Wall-clock duration of the job or the run.
- Cluster configuration: node type, worker count or autoscale range, runtime version, Photon on or off.
- Input data size, so you can tell a slow run from a bigger run.
- Estimated cost: DBUs consumed plus cloud instance cost for the time the cluster was up.
This notebook cell, from the earlier chapter on parallelism, gives the cluster-side facts:
total_cores = spark.sparkContext.defaultParallelism
shuffle_partitions = spark.conf.get("spark.sql.shuffle.partitions")
aqe_enabled = spark.conf.get("spark.sql.adaptive.enabled")
print(f"Default parallelism (approx. total cores): {total_cores}")
print(f"Shuffle partitions: {shuffle_partitions}")
print(f"Adaptive query execution enabled: {aqe_enabled}")Compare the shuffle partition count with total cores. If a stage has 200 tasks and the cluster has 64 slots, the stage runs in about four waves (200 / 64, rounded up). That ratio is the first thing to check when a run feels slow.
Step 2: read the signals
Use the Spark UI for what happened inside the job, and the cluster metrics page for how busy the machines were. Neither is enough alone.
| Signal | Where to find it | What it tells you |
|---|---|---|
| Stage duration and task count | Spark UI, Stages | Which stages dominate the run time |
| Task time distribution (min, median, max) | Spark UI, stage detail | Skew, when the max is far above the median |
| Spill (memory) and spill (disk) | Spark UI, stage detail | Executors lack memory for the partition size |
| GC time | Spark UI, Executors | Memory pressure in the JVM |
| Shuffle read and write size | Spark UI, stage detail | Network and disk load from wide transformations |
| CPU utilization per node | Cluster metrics | Idle capacity or saturation |
| Memory utilization per node | Cluster metrics | Headroom or risk of out-of-memory errors |
| Worker count over time | Cluster event log | Whether autoscaling resized the cluster during the run |
Look at the whole run, not one moment. A cluster that is busy for 10 minutes and idle for 50 is a different problem from one that is half busy the whole time.
Step 3: diagnose the bottleneck
Match the pattern you see to a likely cause. The fix column lists the setting to try first.
| Pattern | Likely cause | First change to try |
|---|---|---|
| CPU near 100% on all workers, tasks queue in many waves | Undersized: too few cores | Raise max workers or use a larger node |
| Spill to disk, high GC time, memory near limit | Memory-bound partitions | Memory-optimized nodes, or more partitions so each is smaller |
| CPU under 30% across the run, tasks finish in one wave | Oversized: more cores than tasks | Lower max workers or use smaller nodes |
| One task runs far longer than the median | Data skew | Fix the skew (salting, AQE skew handling). Do not add nodes |
| Long idle gaps at the end or between jobs | Cluster stays up after work ends | Lower auto-termination minutes |
| Workers repeatedly scale up and down within one job | Bursty stages, resize overhead | Raise min workers, or use a fixed size |
| Slow stage with low CPU and high shuffle read | Network or disk bound | Storage-optimized nodes or fewer, larger nodes |
Adding workers cannot fix skew, because the slow task still runs on one core. Check the task time distribution before you scale up.
Step 4: change one setting
Change one variable per run. If you raise max workers and change the node type together, you cannot tell which change helped. Keep the change small enough that a different result has an obvious cause.
When you benchmark, pin the size. Autoscaling adds noise, because the cluster may resize at different moments on each run. Test with a fixed worker count first:
{
"cluster_name": "etl-benchmark",
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"num_workers": 4,
"autotermination_minutes": 30
}Once you know what fixed size fits the heavy stages, turn that knowledge into autoscale bounds. A common choice is to set max workers near the size that fits the heaviest stage and min workers near what the lightest stage needs:
{
"cluster_name": "etl-autoscale",
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"autoscale": {
"min_workers": 2,
"max_workers": 8
},
"autotermination_minutes": 30
}Also keep spot instances out of your benchmark runs. A lost spot worker triggers task retries and distorts timing. Add SPOT_WITH_FALLBACK after the size is settled.
Step 5: compare on cost, not only speed
Faster is not the goal. The goal is the cheapest configuration that meets your run-time target. Doubling the workers rarely halves the run time, because shuffles, skew, and fixed overheads do not scale linearly. Cost per run is roughly the hourly price of the whole cluster multiplied by the run time. This script compares candidate runs:
runs = [
{"workers": 4, "minutes": 60, "node_hourly": 1.10},
{"workers": 8, "minutes": 36, "node_hourly": 1.10},
{"workers": 16, "minutes": 27, "node_hourly": 1.10},
]
for run in runs:
nodes = run["workers"] + 1 # workers plus the driver
cost = nodes * run["node_hourly"] * run["minutes"] / 60
print(f"{run['workers']:>2} workers: {run['minutes']} min, ${cost:.2f}")The node_hourly figure is a placeholder for your DBU plus instance cost per node-hour. In this example, going from 4 to 8 workers cuts time by 24 minutes and costs about the same. Going to 16 workers saves only 9 more minutes and costs noticeably more. The 8-worker run is the better choice unless the deadline demands the faster one.
Edge cases that mislead measurements
- Cold caches. The first run reads from cloud storage and fills disk caches. Later runs may be faster at the same size. Compare runs in the same cache state.
- Data growth. A job that fit last quarter may not fit now. Record input size so a slower run is not blamed on the cluster.
- Shared clusters. On an all-purpose cluster other users add load, so metrics mix several workloads. Test on a job cluster for a clean signal.
- Driver pressure. Workers can look idle while the driver is saturated, for example from large
collect()calls or many small files. Check driver CPU and memory too. - Autoscaling lag. If a cluster takes minutes to add workers, a short job may finish before the extra capacity arrives. Raise min workers rather than max.
Locking in the result
When the job meets its targets, make the result durable:
- Save the configuration in the job definition or infrastructure code, not only in the UI.
- Add a cluster policy so the tuned limits (for example max workers of 8 and auto-termination between 10 and 120 minutes) cannot be exceeded by accident.
- Note the date, input size, and run time, so you know when to re-measure.
- Schedule a recheck when the data volume, query logic, or runtime version changes substantially.
Exercise
A nightly job runs on 8 workers with 4 cores each. In the Spark UI, the slowest stage has 200 tasks. Median task time is 20 seconds, but one task takes 12 minutes. Cluster CPU averages 25% during the stage. Your teammate proposes raising max workers to 16. What do you recommend, and what do you check next?
Show answer
Do not add workers. The slowest stage has 32 slots, so it needs about 7 waves, but the 12-minute task dominates the stage time, which points to data skew. Extra workers would not speed up that one task and would raise cost. The low average CPU is consistent with most cores waiting on the skewed task. Next, check which key or partition is oversized, and try adaptive query execution skew handling or salting the key. Change one thing, re-run, and compare stage duration and cost against the baseline.