Skip to content
Silver 6 min read · spark.dynamicAllocation.enabled 2 practice problems ↓

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

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

  1. Backlog

    Tasks have been pending for schedulerBacklogTimeout (1 s)

  2. Ramp up

    Request 1, then 2, 4, 8 more executors each round while the backlog persists

  3. Cap

    Never beyond what pending tasks need, or maxExecutors

  4. 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.

ConfigDefaultMeaning
spark.dynamicAllocation.enabledfalseTurn it on
...minExecutors / ...maxExecutors0 / unlimitedBounds. Always set a max on shared clusters.
...initialExecutorsminExecutorsExecutors at start (spark.executor.instances is used if larger)
...schedulerBacklogTimeout1sHow long tasks must wait before asking for more
...executorIdleTimeout60sIdle time before an executor is released
...cachedExecutorIdleTimeoutinfinityIdle 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 fitPoor fit
Shared clusters and notebooks with idle time between queriesShort, latency-sensitive jobs: requesting and starting executors takes seconds to minutes
Jobs whose stages vary a lot in task countJobs that cache heavily: cached executors are never released by default
Many applications competing for one clusterLong-running streaming queries with steady load, where a fixed size is simpler and predictable
Note: dynamic allocation scales executors inside one application. Cluster autoscaling (Kubernetes cluster autoscaler, Databricks or EMR autoscaling) adds and removes machines. They work together: Spark asks for executors, and the cluster grows to fit them.

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.

Production patternPySpark · Dynamic allocation for a batch job on Kubernetes
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-submit flags: use either form, not both.
  • shuffleTracking is what makes this work on Kubernetes, which has no external shuffle service. On YARN with the shuffle service, set spark.shuffle.service.enabled=true instead.
  • 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?"

Spark requests executors when tasks have been pending longer than schedulerBacklogTimeout, ramping up exponentially (1, 2, 4, 8) up to maxExecutors, and releases executors idle for executorIdleTimeout. Shuffle files live on executor disks, so removing an executor would lose map output needed by later stages. An external shuffle service on each node serves those files independently of executors. Alternatives are shuffle tracking (Spark 3.0+, keeps executors with live shuffle data) and decommissioning, which migrates blocks before removal; on Kubernetes, shuffle tracking is the usual choice.

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?"
Usually because those executors hold cached blocks, and 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?"
Kubernetes has no external shuffle service by default, and Spark refuses to enable dynamic allocation without a way to protect shuffle files. Set 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."
Not necessarily. It starts at 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 questions

Why 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 read
Adaptive Query Execution
Spark re-plans a running query from real statistics: coalescing, join switching and skew splitting.

Related lessons

Previous: Broadcast variables and accumulators

Primary sources: Job scheduling: dynamic resource allocation · Configuration: dynamic allocation