Execution Model: Advanced
Two schedulers in one driver
| Question | DAGScheduler | TaskScheduler |
|---|---|---|
| Unit it reasons in | Stages | Tasks |
| What it receives | A job, from an action | A TaskSet, from the DAGScheduler |
| What it decides | Where stage boundaries fall and which stage runs next | Which executor slot runs each task, and when |
| On a task failure | Nothing, until the retry budget is spent | Re-launches the task as a new attempt |
| On lost shuffle output | Re-runs the parent stage for the lost partitions | Nothing, hands the FetchFailed upward |
| What it tracks | Map output locations per shuffle | Running, finished and failed attempts per task |
Downward, a job becomes stages, each stage a TaskSet, each task a launch on an offered slot. Upward along the same path travel every finish, failure and fetch failure, until the DAGScheduler hears that a stage is complete.
The 2 handoffs in a 2-stage job
from pyspark.sql import functions as Ftotals = rides.groupBy("city").agg(F.sum("fare").alias("total_fare"))totals.collect()
Reading the handoff in the driver log
| Logger | Line | What happened |
|---|---|---|
| DAGScheduler | Got job 0 (collect at ...) with 3 output partitions | The action arrived; the final stage has 3 partitions |
| DAGScheduler | Submitting 3 missing tasks from ShuffleMapStage 0 | Stage 0 became a TaskSet of 3 tasks |
| TaskSetManager | Starting task 0.0 in stage 0.0 (TID 0) (executor 1, partition 0, PROCESS_LOCAL) | Attempt 0 of task 0 was placed on executor 1 |
| TaskSetManager | Finished task 2.0 in stage 0.0 (TID 2) in 412 ms (3/3) | The last map task reported back |
| DAGScheduler | ShuffleMapStage 0 finished in 0.611 s | All 3 map outputs are registered |
| DAGScheduler | Submitting 3 missing tasks from ResultStage 1 | The handoff repeats for the reduce stage |
task 7.3 means task 7 is on its 4th try, and stage 0.1 means the DAGScheduler re-submitted a whole stage. The first points at a slot, the second at a lost shuffle output.A reducer in stage 1 fails with FetchFailed because the executor holding stage 0's output for partition 2 died. Which component acts, and how?
Four attempts, then the job dies
A task fails when its code throws, when its executor dies, or when a heartbeat timeout fires. Each failure arrives at the TaskSetManager that owns the stage, and the manager answers by scheduling the same partition again as a new attempt: the index stays, the attempt counter moves, so task 7.0 becomes task 7.1. The budget is spark.task.maxFailures, default 4, counted per task: 4 attempts, so 3 retries. The 4th failure of the same task aborts the stage, the DAGScheduler fails the job, and the exception surfaces at the line that called the action. Failures on different tasks do not add up. A stage of 400 tasks where each fails once and then succeeds is a slow job with 400 retries, and it finishes. One task failing 4 times kills it.
| What failed | Scope | Who handles it | What re-runs |
|---|---|---|---|
| Exception in task code (bad record, cast error) | 1 task | TaskSetManager | The same partition, as a new attempt |
| Executor killed (memory limit, preemption) | Every task running on it | TaskSetManager | Each of those tasks, as new attempts elsewhere |
| Shuffle output lost with the executor | Reducers that read from it | DAGScheduler | The parent stage, only for the lost map partitions |
| Same task fails 4 times | The job | DAGScheduler | Nothing; the job aborts and the action throws |
A retry pays only for a cause outside the task
When a shuffle output disappears
Map tasks write their shuffle files to the local disk of the executor that ran them. When that executor dies, those files go with it unless an external shuffle service holds them. Every reducer that later asks for a block from that executor gets a FetchFailedException. This failure skips the TaskSetManager's retry budget. The manager marks its TaskSet as a zombie, lets reducers already running finish, and passes the failure to the DAGScheduler, which marks that executor's map outputs missing, re-submits the ShuffleMapStage as attempt 1 with only the lost partitions, and then re-submits the reduce stage for the partitions that had not finished. Each round is a stage attempt, bounded by spark.stage.maxConsecutiveAttempts, default 4. In the UI the stage appears twice in the job's stage list, once per attempt.
Setting the budgets
The scheduler reads these 3 settings once, when the session starts, so they belong in the builder or in a submit-time --conf, and a spark.conf.set afterwards leaves them unchanged. The third one, exclusion, is off by default. Without it, attempt 1 of a task that died on a sick executor can be placed right back on that executor. With it on, a task that failed on an executor is kept off that executor for the rest of the stage, and an executor that fails 2 different tasks in 1 stage is kept out of that stage altogether.
A stage of 400 map tasks finished 38 minutes ago and its reducers are mid-run when executor 9, which ran 20 of those map tasks, dies. There is no external shuffle service and the config is default. What happens?
A second copy of the slowest task
Speculation is the TaskSetManager launching a duplicate attempt of a task that is still running while most of its stage has finished. The 2 attempts run the same partition on different executors. The first to finish wins, its result is accepted, and the manager kills the other. It is off by default, through spark.speculation, and when on it follows 3 rules: it waits until a fraction of the stage's tasks have finished, it takes the median duration of those finished tasks, and it marks any still-running task as a straggler once its runtime passes a multiple of that median, re-checking on a fixed interval.
| Setting | Default | What it controls |
|---|---|---|
| spark.speculation | false | Master switch |
| spark.speculation.quantile | 0.75 | Fraction of the stage's tasks that must finish before any copy launches |
| spark.speculation.multiplier | 1.5 | A running task is a straggler once its runtime exceeds this times the median |
| spark.speculation.interval | 100ms | How often the TaskSetManager re-checks running tasks |
| spark.speculation.minTaskRuntime | 100ms | Tasks shorter than this are never speculated (Spark 3.2 and later) |
Worked: 200 tasks and 1 slow disk
| Time | Event |
|---|---|
| 0 s | 160 tasks launch, 137.0 among them on executor 6; 40 tasks wait for slots |
| 40 s | Over 150 of 200 tasks are done and the quantile gate opens; with a median near 40 s, the straggler threshold is 60 s |
| 60 s | 137.0 passes 60 s, still reading its 300 MB |
| 60.1 s | The next check fires; the manager launches 137.1 on executor 12 |
| 101 s | 137.1 finishes in 41 s; 137.0 is killed; the stage completes |
Speculation fixes a slow machine, never a heavy partition
A copy also repeats side effects, because both attempts run the task's code in full. File writes are safe: Spark's commit protocol lets only 1 attempt commit its output. A task that posts a row to an external service inside a foreachPartition posts it twice. Enable speculation for jobs whose tasks read, shuffle and write files, and leave it off when a task calls out to anything that remembers the call.
spark.speculation.task.duration.threshold, added in Spark 3.0, speculates any task past an absolute duration before the quantile gate opens, and applies only when a stage has no more tasks than 1 executor has slots.
Speculation is on with defaults in a stage of 1,000 tasks. Task 412 has run for 4 times the median; its shuffle read is 9 GB while the median task reads 300 MB. What does speculation do?
Everything in this lesson runs on 1 process
Both schedulers live in the driver, and so does every result an action brings home. The driver builds the plan, creates each TaskSet, serializes every task and sends it over the network, receives every task's completion message with its metrics, updates both schedulers through a single event loop, and holds whatever collect() returns. Executors scale out to hundreds of machines. The driver scales up to 1 machine and stops. It saturates in 3 ways: too many rows coming back, too many tasks to launch, and too much coordination state to hold.
Too many rows coming back
from pyspark.sql import functions as Fus_events = events.filter(F.col("country") == "US")us_events.collect()
Spark guards this with spark.driver.maxResultSize, default 1g. The driver adds up the serialized size of results as they arrive and aborts the job once the total crosses the limit, with an error naming how many tasks' results exceeded it. Raising the limit moves the failure from an error message to an out-of-memory crash of the driver. The fix is to reduce on the executors first and move only the reduction. The cell below reads every completed order on the executors and brings back 1 row.
from pyspark.sql import functions as F
completed = orders.filter(F.col("status") == "Completed")
summary = completed.agg(
F.count("*").alias("completed_orders"),
F.sum("profit").alias("total_profit"),
)
summary.collect()Too many tasks to launch
Every task costs the driver a fixed amount of work regardless of how much data it processes: build the task description, serialize it, send it, then on completion deserialize the result and metrics and update the TaskSetManager and the DAGScheduler, the last part on a single thread. A driver launches on the order of a few thousand tasks per second. A stage of 3 million 20 ms tasks, from 3 million small files or from spark.sql.shuffle.partitions left at a huge value across many stages, keeps 400 slots waiting on that thread. The Spark tuning guide puts the floor for an efficient task near 200 ms, and the tell in the UI is Scheduler Delay climbing while executor CPU stays low and the driver's CPU sits at 100%.
Too much state to hold
The driver also keeps the map of where every shuffle block lives. A shuffle with M map tasks and R reduce partitions produces M map statuses, each describing R block sizes. At 50,000 maps and 50,000 reducers that is 2.5 billion sizes. Spark switches to a compressed status, a bitmap of empty blocks plus an average size, once reduce partitions pass spark.shuffle.minNumPartitionsToHighlyCompress, default 2000, which is why a very wide shuffle costs the driver memory rather than crashing it. Broadcast variables are built on the driver too: a 2 GB broadcast is 2 GB of driver heap before any executor sees a byte of it.
- ▸
spark.driver.memorymust hold the plan, the map statuses, every broadcast, and the largest result that will ever come back. - ▸
spark.driver.cores: scheduling runs mostly on 1 thread, so 2 to 4 cores cover serialization and the UI, and more buys little. - ▸
spark.driver.maxResultSizestays below the heap, so an oversized collect fails with a message instead of an out-of-memory crash. - ▸Client mode over a slow link adds that link's latency to every task launch; run the driver inside the cluster for large stages.
A stage of 3 million tasks, each 20 ms, runs with executors mostly idle and the driver's CPU pinned at 100%. Which change fixes it?
Each task names where it would rather run
| Level | Meaning | Typical case |
|---|---|---|
| PROCESS_LOCAL | The same executor JVM holds the data | A cached partition, or map output this executor wrote |
| NODE_LOCAL | The same machine, a different process | A filesystem block replica stored on this host |
| NO_PREF | The task has no preferred place | Reading from an object store over the network |
| RACK_LOCAL | The same rack, a different machine | A block replica 1 switch away |
| ANY | Anywhere | The fallback when no closer slot frees up |
The wait before falling back
When the preferred slot is busy and a lower-level slot is free, the TaskSetManager does not take it. It waits, on the chance that a slot at the preferred level frees up, and only when the wait expires does it step down 1 level and start waiting again. The wait is spark.locality.wait, default 3 s, and each level has its own override: spark.locality.wait.process, .node and .rack. A task graded NO_PREF skips every wait, which is why object-store jobs rarely feel this setting at all.
| Second | What the manager does with task 41, cached on executor 3 |
|---|---|
| 0 | Executor 3 is busy; a slot is free on executor 9, graded ANY; the manager waits for PROCESS_LOCAL |
| 3 | The PROCESS_LOCAL wait expires; executor 3 is still busy; the manager now accepts NODE_LOCAL and waits again |
| 6 | The NODE_LOCAL wait expires; nothing on executor 3's host is free; the manager accepts ANY |
| 6 | Task 41 launches on executor 9 and reads the partition over the network in 0.4 s |
Scheduler Delay in the task table
from pyspark.sql import functions as F
totals = user_sessions.agg(
F.count("*").alias("sessions"),
F.sum("pages_viewed").alias("pages"),
F.avg("session_duration_sec").alias("avg_seconds"),
)
totals.collect()- Read Locality Level and Scheduler Delay together before touching spark.locality.wait
- Keep the process-level wait when a stage reads cached data it will reuse
- Broadcast any object over a few hundred KB that a task function closes over
- Raise spark.locality.wait on object-store jobs; NO_PREF tasks never waited
- Read a long Scheduler Delay as a slow executor; it is driver, network or task size
- Blame locality for a stall when the Locality Level column shows NO_PREF
A stage reads from an object store. Its tasks run for 300 ms, the median Scheduler Delay is 450 ms, and executors sit mostly idle. What is the cause and fix?
> Picture a nightly Spotify job that aggregates a day of listening events into per-country totals across 12,000 tasks on preemptible machines. At minute 30, 2 executors are reclaimed mid-stage, a third has a disk that reads at a tenth of its speed, and the last step collects the totals into a dashboard feed.
Two schedulers, one driver: how Spark places tasks, retries them, duplicates stragglers, and where it all jams.
- Category
- Spark
- Difficulty
- advanced
- Duration
- 14 minutes
- Challenges
- 7 hands-on challenges
Topics covered: DAGScheduler vs TaskScheduler, Task Failure and Retry, Speculative Execution, The Driver as Bottleneck, Locality and Scheduling Delay
Lesson Sections
- DAGScheduler vs TaskScheduler (concepts: Spark Execution Model)
Two schedulers in one driver An action turns a chain of transformations into a job, and 2 components inside the driver split the work of running it. The DAGScheduler takes the chain, walks it backwards from the result, and cuts it at every shuffle into stages. It submits those stages in dependency order, each one as a TaskSet holding 1 task per partition. The TaskScheduler receives each TaskSet and does the placing: it matches tasks to free slots on executors, launches them, hears back when each
- Task Failure and Retry (concepts: Spark Execution Model)
Four attempts, then the job dies A retry pays only for a cause outside the task A new attempt helps when the cause was the machine: a container killed for memory, a preempted node, a network blip during a shuffle read. It does nothing for a cause inside the data. A task that throws a cast error on a malformed row throws the same error on attempts 1, 2 and 3, wherever they land, and a 10-minute task spends 40 minutes proving it before the job aborts. Read the stack trace of attempt 0 in the stage
- Speculative Execution (concepts: Data Skew)
A second copy of the slowest task Worked: 200 tasks and 1 slow disk A stage has 200 tasks on 160 slots, each task reading about the same 300 MB. Executor 6 has a disk that reads at a tenth of its rated speed. Every task takes close to 40 s, except the ones on executor 6. Here is the timeline for task 137, which landed there at the start. Without speculation the stage ends when 137.0 ends, near 400 s. With it, the stage ends at 101 s, and the costs are 41 s of 1 extra slot plus the 60 s executor
- The Driver as Bottleneck (concepts: Spark Execution Model)
Everything in this lesson runs on 1 process Too many rows coming back The program below filters 12 events to the 7 from the US and collects them, with the table read as 4 partitions. The filter runs as 4 tasks, each keeping its own US rows. Then each task serializes its rows, ships them to the driver, and the driver deserializes all 4 result sets into 1 list. For 12 rows this costs nothing. For 400 million rows of 200 bytes it is 80 GB arriving at a process with 8 GB of heap, and the shape of th
- Locality and Scheduling Delay (concepts: Spark Execution Model)
Each task names where it would rather run When the TaskScheduler places a task, it reads the task's preferred locations, which come from the data the task will read. A cached partition prefers the executor whose memory holds it. A block in a distributed filesystem prefers the hosts that hold a replica. A reducer prefers the executor holding most of its map output, when 1 executor holds more than a fifth of it and the shuffle has fewer than 1,000 partitions on each side. A read from an object sto