Home / Data Platform / Databricks & Spark

Data PlatformHow-toAdvanced

Spark speculative execution: when it fixes stragglers, when it duplicates writes, and how to tune it

Turn on Spark speculation only where it helps. How the scheduler picks stragglers, which sinks duplicate data under speculation, and the settings to tune per version.

Deepak Bhardwaj10 min read

Applies toApache Spark 3.x and 4.x, Databricks Runtime, Amazon EMR, Azure HDInsight / Synapse Spark

A stage gets stuck on its last few tasks. Nobody can find data skew, and the same tasks finish in seconds on a rerun. That pattern points to a slow node, not slow data, and it is the one case speculative execution is built for. Speculation launches a second copy of a slow task on another executor and keeps whichever copy finishes first.

It also runs your task code twice. If that code writes to something that is not protected by Spark's commit protocol, you can end up with duplicate rows. This post covers how the scheduler decides a task is slow, how to tell if speculation will help, which writes it makes unsafe, and how to tune it.

How the scheduler decides a task is a straggler

With spark.speculation=true, the task scheduler checks every running stage every spark.speculation.interval. A task becomes a candidate when all of these hold:

  1. At least spark.speculation.quantile of the stage's tasks have finished successfully.
  2. The task has been running longer than spark.speculation.multiplier × the median duration of the successful tasks.
  3. The task has been running longer than spark.speculation.minTaskRuntime.

Spark then launches one extra attempt on a different host. When either attempt succeeds, Spark kills the other one. The killed attempt's reason in the UI and event log is "another attempt succeeded".

Setting What it controls Notes
spark.speculation Master switch Off by default in open-source Spark and Databricks
spark.speculation.interval How often stages are checked Rarely needs changing
spark.speculation.multiplier How much slower than the median counts as slow 1.5 before Spark 4.0, 3 from Spark 4.0
spark.speculation.quantile Fraction of tasks that must finish first 0.75 before Spark 4.0, 0.9 from Spark 4.0
spark.speculation.minTaskRuntime Minimum runtime before a task can be speculated Stops copies of short tasks
spark.speculation.task.duration.threshold Speculate stages with few tasks once a task passes this duration Only applies when the stage has no more tasks than one executor can run at once
spark.speculation.efficiency.enabled Spark 3.4+: speculate only tasks that are actually processing slowly Uses per-task processing rate, not just elapsed time

Tip

Spark 4.0 made speculation much less aggressive. If you upgrade a job that relied on speculation and its tail latency gets worse, that change is the likely cause. To restore the old behaviour, set spark.speculation.multiplier=1.5 and spark.speculation.quantile=0.75 explicitly. Check the configuration page for your exact Spark version, because vendor runtimes can ship different defaults.

Why the quantile matters more than the multiplier

Speculation does nothing until the quantile is reached. On a 200-task stage with quantile=0.9, 180 tasks have to finish before the scheduler even looks at the remaining 20. On short stages that is fine. On a stage where every task runs for 20 minutes, a straggler on a bad disk can run for 40 minutes before it is considered. Lowering the quantile on long-task stages has more effect than lowering the multiplier.

Will speculation help this job?

Speculation helps when the second attempt can finish faster than the first. That only happens when the slowness comes from where the task runs, not from what it processes.

Symptom Likely cause Does speculation help? Better fix
Slow tasks land on the same one or two hosts Bad disk, noisy neighbour, throttled VM, failing NIC Yes Exclude or replace the node
Slow task reads far more input or shuffle bytes than the median Data skew No. The copy reads the same data AQE skew join, salting, pre-aggregation
Slow tasks are spread randomly, durations close to the median Normal variance Very little, and it adds cost Leave it off
Slow tasks spend their time in GC Executor memory pressure Sometimes, if another executor has headroom Fix memory sizing
Slow task waiting on an external system (JDBC, REST, object store throttling) Remote bottleneck No. The copy adds more load Throttle or fix the remote side

Check before you enable it. In the Spark UI, open the slow stage and sort the task table by duration. Compare Input Size / Records or Shuffle Read Size / Records for the slow tasks against the median, and look at the Executor ID / Host column. If the slow tasks read the same amount of data as the median and are clustered on one host, speculation will help.

The same check from an event log, which is easier when you have hundreds of stages:

import json, statistics
from collections import defaultdict

durations = defaultdict(list)   # stage -> [(duration_ms, host, input_bytes, speculative)]

with open("eventlog") as f:      # uncompressed Spark event log, one JSON event per line
    for line in f:
        e = json.loads(line)
        if e.get("Event") != "SparkListenerTaskEnd":
            continue
        ti = e["Task Info"]
        m = e.get("Task Metrics") or {}
        inp = m.get("Input Metrics", {}).get("Bytes Read", 0)
        shuf = m.get("Shuffle Read Metrics", {})
        inp += shuf.get("Remote Bytes Read", 0) + shuf.get("Local Bytes Read", 0)
        durations[e["Stage ID"]].append(
            (ti["Finish Time"] - ti["Launch Time"], ti["Host"], inp, ti.get("Speculative", False)))

for stage, tasks in sorted(durations.items()):
    if len(tasks) < 10:
        continue
    med = statistics.median(t[0] for t in tasks)
    med_bytes = statistics.median(t[2] for t in tasks) or 1
    slow = [t for t in tasks if t[0] > 3 * med]
    for d, host, b, spec in slow:
        print(f"stage={stage} dur={d/1000:.0f}s median={med/1000:.0f}s "
              f"bytes_ratio={b/med_bytes:.1f} host={host} speculative={spec}")

A bytes_ratio close to 1 on the same host points to an environment problem. A ratio of 5 or more means skew, and speculation will only waste executors.

Writes that speculation makes unsafe

Spark protects file output with the output commit coordinator. Only one attempt of each task is allowed to commit, and the losing attempt's temporary files are discarded. Anything that bypasses that protocol has no such protection.

Write path Safe under speculation? Why
DataFrame writes to Parquet/ORC/Delta/Iceberg through the standard writer Yes Commit coordinator authorises one attempt per task
Delta Lake and Iceberg table writes Yes Files from killed attempts are never added to the table log or metadata
Hadoop FileOutputCommitter algorithm version 2 Not reliably Task commit moves files straight to the final directory, so a failed or killed attempt can leave partial output
df.write.jdbc(...) / format("jdbc") No Each partition inserts and commits its own transaction with no coordinator. Both attempts can commit
foreach / foreachPartition calling an API, queue or database No Side effects run in whichever attempt reaches them
Kafka sink No exactly-once guarantee anyway Speculation adds more duplicates on top of normal retries
Structured Streaming foreachBatch Depends on the code inside Spark-managed file/Delta writes are safe; direct JDBC or API calls are not

Caution

Never enable speculation cluster-wide on a cluster that runs JDBC exports or foreachPartition side effects into non-idempotent targets. You will get duplicate rows, and they will look like random retries. Make those writes idempotent (MERGE/upsert on a business key, or staging table plus swap), or turn speculation off for those jobs.

Task retries after executor loss cause the same duplicates, so an idempotent sink is worth having even without speculation. Speculation just makes the duplicates happen on every run instead of only after failures.

Check the committer setting on Hadoop-based platforms:

spark-submit \
  --conf spark.speculation=true \
  --conf spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version=1 \
  ...

Cloud-specific committers, such as the S3A magic committer or EMRFS S3-optimized committer, have their own rules for task attempts. Check your platform's documentation before you combine them with speculation.

Tuning it per job, not per cluster

Speculation is a scheduler setting, so you set it when the application starts, not halfway through a session. Set it on the job cluster or in spark-submit for the jobs that need it.

A conservative starting point for long batch stages with occasional bad nodes:

spark-submit \
  --conf spark.speculation=true \
  --conf spark.speculation.multiplier=2 \
  --conf spark.speculation.quantile=0.75 \
  --conf spark.speculation.minTaskRuntime=60s \
  --conf spark.speculation.efficiency.enabled=true \
  my_job.py

On Databricks, put the same keys in the job cluster's Spark config (one key value per line). Leave them off shared all-purpose clusters.

spark.speculation true
spark.speculation.multiplier 2
spark.speculation.quantile 0.75
spark.speculation.minTaskRuntime 60s

Interaction with dynamic allocation

With dynamic allocation enabled, pending speculative tasks count toward the executors Spark requests. An aggressive multiplier on a large stage can scale the cluster up just to run copies. Watch executor counts and cost for a few runs after you enable it, and raise minTaskRuntime if copies of short tasks are adding executors.

Few-task stages

A stage with only a handful of tasks may never reach the quantile while a single task hangs. spark.speculation.task.duration.threshold covers this. When the stage has no more tasks than one executor can run at once, any task running longer than the threshold is speculated. Set it to something well above the task's normal runtime, such as 10min for a task that normally takes three.

Measure whether it is working

After enabling it, check that copies are winning and not just burning slots. In the event log, count speculative attempts that finished successfully against those killed:

won = killed = 0
with open("eventlog") as f:
    for line in f:
        e = json.loads(line)
        if e.get("Event") == "SparkListenerTaskEnd" and e["Task Info"].get("Speculative"):
            reason = e.get("Task End Reason", {}).get("Reason")
            if reason == "Success":
                won += 1
            elif reason == "TaskKilled":
                killed += 1
print(f"speculative attempts won={won} killed={killed}")

If most speculative attempts are killed, the original usually finishes first. You are paying for copies that do not help, so raise the multiplier or minTaskRuntime. If copies win consistently on the same hosts, the real problem is those hosts.

Prevent it next time

  • Treat repeated speculation wins on one host as a hardware signal. Drain and replace the node rather than relying on copies forever. spark.excludeOnFailure.enabled handles hosts that fail tasks, but not hosts that are only slow.
  • Make every sink idempotent: MERGE on a key, write to a staging table, or use a table format with transactional commits. Then speculation and retries are both safe.
  • Run the skew check before enabling speculation. It does not fix skew, and turning it on hides the real cause.
  • Pin speculation settings explicitly in job definitions so a Spark 4.x upgrade does not quietly change behaviour.
  • Keep speculation off for jobs with JDBC exports, API calls or Kafka writes unless those targets deduplicate.