Dynamic allocation
A Spark application can hold the same number of executors from start to finish, or grow and shrink with the work. The second, dynamic allocation, saves a lot of money on bursty jobs, but it needs a way to keep shuffle files when executors leave. This lesson shows how it works and how to configure it.
Step 2 · Spark internals · Silver · Memory and resources, lesson 3 of 3
On this page
Read first: Driver, executors and the cluster manager · Jobs, stages and tasks (skip if you know them)
In plain words first
A restaurant can keep the same staff all day, or call in extra cooks for the lunch rush and send them home in the quiet afternoon. The second costs less, as long as nothing a cook was preparing is thrown away when they leave.
Dynamic allocation is calling in and sending home executorsexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more →. The "nothing thrown away" part is about shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → files, explained below.
Static vs dynamic
With static allocation, an application holds spark.executor.instances executors from start to finish. A notebook that runs one query an hour keeps 50 executors idle in between, and a job whose last stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → has 10 taskstask: The work for one partition in one stage, run on one CPU core. Learn more → keeps 40 executors waiting. Dynamic allocation sizes the application to its current backlog of tasks.
How it scales
-
Backlog
Tasks have been pending for schedulerBacklogTimeout (1 s)
-
Ramp up
Request 1, then 2, 4, 8 more executors each round while the backlog persists
-
Cap
Never beyond what pending tasks need, or maxExecutors
-
Idle
An executor with no tasks for executorIdleTimeout (60 s) is released
The exponential ramp is deliberate: start cautiously in case a few executors are enough, then grow fast if they are not.
| Config | Default | Meaning |
|---|---|---|
spark.dynamicAllocation.enabled | false | Turn it on |
...minExecutors / ...maxExecutors | 0 / unlimited | Bounds. Always set a max on shared clusters. |
...initialExecutors | minExecutors | Executors at start (spark.executor.instances is used if larger) |
...schedulerBacklogTimeout | 1s | How long tasks must wait before asking for more |
...executorIdleTimeout | 60s | Idle time before an executor is released |
...cachedExecutorIdleTimeout | infinity | Idle time before an executor holding cachedcache: Keeping a computed DataFrame in memory (or on disk) so later actions reuse it instead of recomputing it. Learn more → data is released |
The shuffle file problem
Map tasks write shuffle files to their executor's local disk, and reducers fetch them later, possibly in a later job. If an idle executor is removed, its shuffle files go with it and the stages that wrote them must re-run. Spark therefore refuses to start with dynamic allocation unless one of these is in place:
External shuffle service
spark.shuffle.service.enabled=true. A long-running service on each node (a YARN NodeManager auxiliary service, or a standalone worker service) serves shuffle files, so they outlive the executor that wrote them. The classic setup on YARN.Shuffle tracking
spark.dynamicAllocation.shuffleTracking.enabled=true (Spark 3.0+). Spark simply does not release executors that hold shuffle data still needed by an active job. No extra service; the usual choice on Kubernetes, at the cost of releasing executors later.Decommissioning
spark.decommission.enabled with spark.storage.decommission.shuffleBlocks.enabled (Spark 3.1+). Before an executor leaves, its shuffle and cached blocks are migrated to other executors or to fallback storage. Also protects against spot instance loss.When it helps, and when it hurts
| Good fit | Poor fit |
|---|---|
| Shared clusters and notebooks with idle time between queries | Short, latency-sensitive jobs: requesting and starting executors takes seconds to minutes |
| Jobs whose stages vary a lot in task count | Jobs that cache heavily: cached executors are never released by default |
| Many applications competing for one cluster | Long-running streaming queries with steady load, where a fixed size is simpler and predictable |
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Configure a batch job on Kubernetes to add and remove executors as the work changes.
from pyspark.sql import SparkSession # Static settings: they apply when the application starts (spark-submit or the builder). DYNAMIC_ALLOCATION = { "spark.dynamicAllocation.enabled": "true", # no shuffle service on k8s "spark.dynamicAllocation.shuffleTracking.enabled": "true", "spark.dynamicAllocation.minExecutors": "2", # always cap shared clusters "spark.dynamicAllocation.maxExecutors": "50", "spark.dynamicAllocation.executorIdleTimeout": "60s", "spark.dynamicAllocation.cachedExecutorIdleTimeout": "30min", } builder = SparkSession.builder.appName("nightly-orders") for key, value in DYNAMIC_ALLOCATION.items(): builder = builder.config(key, value) # spark = builder.getOrCreate() # in the job's entry point for key, value in DYNAMIC_ALLOCATION.items(): # the same, as spark-submit flags print(f"--conf {key}={value}")
Output from a real run
--conf spark.dynamicAllocation.enabled=true --conf spark.dynamicAllocation.shuffleTracking.enabled=true --conf spark.dynamicAllocation.minExecutors=2 --conf spark.dynamicAllocation.maxExecutors=50 --conf spark.dynamicAllocation.executorIdleTimeout=60s --conf spark.dynamicAllocation.cachedExecutorIdleTimeout=30min
What to notice:
- The output is the same settings as
spark-submitflags: use either form, not both. shuffleTrackingis what makes this work on Kubernetes, which has no external shuffle service. On YARN with the shuffle service, setspark.shuffle.service.enabled=trueinstead.- Local mode has one fixed executor, so these settings only do something on a cluster.
Common mistakes
- Enabling it without a shuffle service or tracking — Spark refuses to start the application.
- No maxExecutors on a shared cluster — One big job takes every executor the cluster manager will give.
- Caching and expecting executors to scale down — Executors holding cached blocks stay until cachedExecutorIdleTimeout, which is infinite by default.
- Setting spark.executor.instances as well — It becomes the initial count, which can surprise you.
Key takeaways
- Dynamic allocation grows executors with the task backlog and releases idle ones.
- Requests ramp up exponentially; idle executors leave after 60 seconds.
- Shuffle files must survive executor removal: external shuffle service, shuffle tracking or decommissioning.
- Set maxExecutors; cached data keeps executors alive.
Interview prep
THE QUESTION
"How does dynamic allocation work, and why does it need an external shuffle service?"
Avoid: describing scaling and forgetting shuffle files. Without an external shuffle service, shuffle tracking or decommissioning, removing executors loses map output.
Follow-ups · answer out loud, then open
Follow-up"Why does an application with dynamic allocation keep 50 executors after its work is done?"
cachedExecutorIdleTimeout defaults to infinity. With shuffle tracking, executors that hold shuffle data needed by an active job are also kept. Unpersist the cache, or set the cached idle timeout.Scenario"On Kubernetes, enabling dynamic allocation makes the application fail at startup. Why?"
spark.dynamicAllocation.shuffleTracking.enabled=true, or configure decommissioning with shuffle block migration.Trap"With dynamic allocation, jobs always start faster because Spark only asks for what it needs."
initialExecutors and ramps up exponentially after a backlog of at least a second, and new executors take time to start. Short latency-sensitive jobs can be slower than with a fixed, pre-allocated set.Check yourself
3 questionsWhy does dynamic allocation need an external shuffle service or shuffle tracking?
Show the answer
Removed executors would take their shuffle files with them. Shuffle output lives on executor disks and is read by later stages.
By default, when is an executor holding cached data released?
Show the answer
Never, unless cachedExecutorIdleTimeout is set. cachedExecutorIdleTimeout defaults to infinity.
Tasks have been pending for a while. How does Spark request executors?
Show the answer
Exponentially: 1, 2, 4, 8 per round. Requests double each round while the backlog persists.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · new module: Self-tuning and file layout · 7 min readAdaptive Query Execution
Spark re-plans a running query from real statistics: coalescing, join switching and skew splitting.
Related lessons
Driver, executors and the cluster managerSpark internals · 8 min read
Shuffle internalsSpark internals · 6 min read
Caching and persistence
Previous: Broadcast variables and accumulators
Primary sources: Job scheduling: dynamic resource allocation · Configuration: dynamic allocation