Fault Tolerance: Beginner
The setting behind this is spark.task.maxFailures, which defaults to 4: any single task may fail 4 times before Spark stops retrying and aborts the whole job. A retry repeats the work exactly: same partition, same rows, same code. That fact sorts every failure into 2 groups.
What changes between attempts
- The executor and machine running the task
- The network path to storage and to other executors
- Memory used by other tasks on the same executor
- The input partition, row for row
- Your transformations and the UDFs they call
- The size of the partition and of each key in it
A failure caused by something on the left is transient: the next attempt lands somewhere healthier and succeeds. A failure caused by something on the right is deterministic: the next attempt meets the same rows, code and sizes, and fails the same way. Spark can't tell the 2 kinds apart, so it retries both, and a deterministic failure burns all 4 attempts before the job aborts. Each attempt redoes the work up to the crash, so that abort can take a long time to arrive.
| Failure | Root cause | On retry | What the error shows |
|---|---|---|---|
| Executor lost | Machine reclaimed or process killed | Rescued | `ExecutorLostFailure` |
| Storage read times out | Brief network trouble | Rescued | `SocketTimeoutException` |
| Shuffle data unreachable | The executor holding it died | Rescued once the data is rebuilt | `FetchFailedException` |
| UDF raises on a bad value | A malformed row in the input | Repeats on all 4 attempts | `PythonException` with the traceback |
| Out of memory on a single task | A hot key makes a partition huge | Usually repeats | `OutOfMemoryError`, or the executor is killed |
A deterministic failure, attempt by attempt
One input file holds a row whose qty_text is 'N/A'. The task that reads it calls int('N/A'), which raises ValueError. Spark reschedules the task on another executor. That attempt reads the same file, reaches the same row and raises the same error. After the 4th failure the driver aborts with a message like Task 37 in stage 2.0 failed 4 times, most recent failure: Lost task 37.3 in stage 2.0.
Now 'N/A' becomes a null, the partition finishes on its first attempt, and the job completes. Count the nulls in qty afterwards so bad input stays visible.
The skewed partition that runs out of memory
A nightly job fails. Which of these failures would Spark's automatic task retry most likely rescue?
Telling them apart in the Spark UI
The driver log ends with Task 12 in stage 5.0 failed 4 times, most recent failure: Lost task 12.3 in stage 5.0. All 4 attempts show the same ArithmeticException, on 4 different executors. What should you do?
Every DataFrame knows how it was made
The lineage of by_region. Each arrow runs from a parent to the step built on it. Rebuilding a lost partition walks the arrows backwards until it reaches data that still exists.
Replicas versus recipes
- Every block stored 2 or 3 times on different machines
- Recovery reads a surviving copy, which is fast
- Pays the storage cost on every run, failure or not
- Works even if the original source is gone
- The steps are stored once, a few lines of plan
- Recovery recomputes the lost partition, which costs CPU
- Pays only when something actually fails
- Needs the source files to still be readable
A narrow chain rebuilds one partition
In that code, filter and selectExpr are narrow: partition 2 of gross comes only from partition 2 of completed, which comes only from split 2 of the files. If the executor holding partition 2 of gross dies, Spark reruns 1 task that reads split 2, filters it and computes gross_amount. No other partition is touched.
Behind a shuffle, the rebuild reaches wider
The groupBy adds a shuffle, so the job runs as 2 stages. In the first, each map task filters its split, adds up a partial sum for each region it saw, and writes those partial sums to local disk in buckets by region. In the second, each reduce task fetches its region's partial sums from every map task and adds them. A cut-down version of the job plays below: watch each region's partial sums cross between the stages.
completed = orders.filter("status = 'Completed'")by_region = completed.groupBy("region").sum("amount")by_region.collect()
The reducer that produces EU's total of 90 fetched from every map task, because any of them could hold EU rows. That's what a wide dependency costs on recovery. If a reduce task dies while every map output is still on a healthy executor's disk, Spark reruns that reduce task alone, and it fetches the same buckets again. If the executor that died also held map output, the reducers trying to fetch it fail with FetchFailedException. Spark then reruns the lost map tasks from the files, using their lineage, and reruns the reducers after them.
| What was lost | What Spark reruns |
|---|---|
| A task in a narrow chain | That task, from its own input split |
| A reduce task, with every map output intact | That reduce task, fetching the same shuffle files |
| An executor holding output from 20 of 200 map tasks | Those 20 map tasks, then the reduce tasks that could not fetch |
| A cached partition | The steps from the nearest parent that still exists, and the result is cached again |
| The source files | Nothing: the recipe has no ingredients left |
The map stage of this job ran 200 tasks across 10 executors. During the reduce stage, a machine fails and takes 1 executor with it. That executor had run 20 of the map tasks and was running 3 reduce tasks. What does Spark rerun?
_2, such as MEMORY_AND_DISK_2, are the opt-in replica: Spark keeps a second copy of each cached partition on another executor. Use one when a cached result took several shuffles to build and losing it would cost more than the extra memory.A result built through 3 shuffles is persisted with MEMORY_AND_DISK. An executor holding 6 of its cached partitions is lost. What happens the next time an action reads the result?
- ▸Reading never changes the input, so attempt 1 sees what attempt 0 saw.
- ▸A transformation builds new rows from its input and writes nothing in place.
- ▸Each attempt's output stays private until Spark accepts exactly 1 attempt per partition.
The input is identical on every attempt
Calling orders.filter("status = 'Completed'") reads the orders files and leaves them as they were. A transformation produces new rows from its input and writes nothing back into it, so a rerun task finds the same split, holding the same rows, that the failed attempt started from.
Same rows in, same rows out
This holds while the computation depends on its input alone. Functions that read something else, such as rand() without a seed or the current time, can give a replay different values, and a later lesson covers them.
One accepted result per partition
| order_id | status | what happened |
|---|---|---|
| 5 | Completed | kept, in executor memory |
| 6 | Cancelled | dropped by the filter |
| 7 | Completed | never reached |
| 8 | Completed | never reached |
| order_id | status | what happened |
|---|---|---|
| 5 | Completed | kept |
| 6 | Cancelled | dropped by the filter |
| 7 | Completed | kept |
| 8 | Completed | kept |
completed = orders.filter("status = 'Completed'")rows = completed.select("order_id", "region", "amount")rows.collect()
A count() runs over 50 partitions. The task for partition 9 fails twice with executor-lost errors and succeeds on its 3rd attempt. How many times are partition 9's rows included in the count?
Written files follow the same rule
Try a replay yourself. The cell below runs the same recipe over the practice order_items table twice, as 2 separate computations, and summarises each run in a row.
def build_line_totals():
items = spark.table("order_items")
return items.filter("order_id IS NOT NULL").selectExpr("quantity * unit_price AS line_total")
first_run = build_line_totals().selectExpr("1 AS run", "count(*) AS line_count", "round(sum(line_total), 2) AS revenue")
second_run = build_line_totals().selectExpr("2 AS run", "count(*) AS line_count", "round(sum(line_total), 2) AS revenue")
first_run.union(second_run).show()The property to check is idempotence: an operation is idempotent when running it twice leaves the same result as running it once. Setting a light switch to off is idempotent; flipping it is not. Whether a Spark job is idempotent depends almost entirely on its final write.
What each write mode does to existing output
| Mode | If the destination already holds data | Running the same job twice |
|---|---|---|
| `errorifexists` (the default) | The write fails with an error | The second run fails loudly, and the first run's output is untouched |
| `append` | New files are added beside the old ones | Every row appears twice |
| `overwrite` | Old files are removed, new ones written | Same output as a single run |
| `ignore` | Nothing is written, and no error is raised | The first run's output stays, even if the new input changed |
The append that doubles revenue
| store_id | sum(revenue) |
|---|---|
| 101 | 4820.5 |
| 102 | 3115 |
| 103 | 2760.25 |
| store_id | sum(revenue) |
|---|---|
| 101 | 4820.5 |
| 102 | 3115 |
| 103 | 2760.25 |
| 101 | 4820.5 |
| 102 | 3115 |
| 103 | 2760.25 |
Make the destination belong to the run
Run this once or 5 times and /warehouse/store_daily/2024-03-14/ holds the same output, because the date fixes the destination and overwrite replaces it whole.
- ▸Is the destination fixed by the run's input, such as its date, and nothing else?
- ▸Does the mode replace existing output or add to it?
- ▸Does any part of the path or the data come from the clock, like
datetime.now()? - ▸Would a rerun read the same input the first run read?
- Pass the logical date in as a parameter and build paths from it
- Overwrite a destination that holds exactly one run's output
- Keep errorifexists where a second run should never happen
- Append a whole job's output to a shared path with no guard
- Put the current time into an output path
- Use ignore when a rerun is meant to apply a fix
completed = spark.table("orders").filter("status = 'Completed'")
appended_twice = completed.union(completed)
one_run = completed.selectExpr("'once' AS runs", "count(*) AS row_count", "count(DISTINCT order_id) AS distinct_orders", "round(sum(profit), 2) AS total_profit")
two_runs = appended_twice.selectExpr("'twice' AS runs", "count(*) AS row_count", "count(DISTINCT order_id) AS distinct_orders", "round(sum(profit), 2) AS total_profit")
one_run.union(two_runs).show()The extra rows repeat existing order_id values, which is the tell. In a table where each ID should appear once, comparing the row count with the distinct ID count is the cheapest check for an append that ran twice.
A reporting job ends with this write, and the dashboard reads every directory under /warehouse/store_daily/. Is the job safe to run twice?
The nightly job. Step 2 appends to store_daily, step 3 builds region_rollup by reading store_daily back, and step 4 tells the dashboard to refresh.
Run by run
| Moment | store_daily rows for 2024-03-14 | region_rollup | State of the data |
|---|---|---|---|
| Before the job | 0 | empty | Nothing written yet |
| Run 1 fails in step 3 | 1,200 | empty | Incomplete, every row correct |
| Run 2, a full rerun, succeeds | 2,400 | 4 regions, revenue doubled | Corrupted, and the dashboard shows it |
Run 1 died in step 3, after step 2 had written 1,200 correct rows. Run 2 started again from step 1, added those rows a second time, and then built region_rollup by reading store_daily back, so the doubling spread into the rollup. The failure cost an hour of delay. The rerun produced wrong numbers that look plausible, which costs far more.
A single write can stop halfway too
A write is many tasks, so it can stop partway. Spark writes an empty file named _SUCCESS into the output directory only after the whole write completes, so a directory without it may hold partial output. What the half-done state looks like depends on the mode:
- The old data is intact
- Depending on how the write is committed, files from tasks that finished may already sit in the destination
- A full rerun adds a complete copy beside them
- Duplicates stay until someone finds and removes them
- The old data was removed before the new files were written
- The destination is empty or partial until the next success
- A full rerun replaces it whole
- Readers during the gap see missing data, never doubled data
The backfill loop
The loop dies on its 4th day, 2024-03-11. March 8 to 10 are complete in the table, and March 11 may have partial files. Rerunning the script from the top appends March 8, 9 and 10 a second time, and March 11 on top of its partial files. Restarting from March 11 avoids the first problem and keeps the second. Writing each day to its own directory with overwrite makes the loop safe to restart from any day.
- Write each logical date to its own directory, replaced whole on every run
- Check for _SUCCESS before a downstream step reads a directory
- Count rows and distinct IDs after a rerun to confirm nothing doubled
- Rerun an appending job without checking what the failed run already wrote
- Build a rollup by reading back a table the same job appended to
- Treat a quiet, successful rerun as proof the data is right
A nightly job reads raw events, appends a cleaned copy to /warehouse/events/, then writes a per-user count with overwrite. Tonight an executor was lost during the cleaning stage, and the job still finished. Last night the count step failed, and the on-call engineer reran the whole job. Which run put duplicates in /warehouse/events/?
completed = spark.table("orders").filter("status = 'Completed'")
left_by_failed_run = completed.filter("order_id % 2 = 0")
after_rerun = left_by_failed_run.union(completed)
copies = after_rerun.groupBy("order_id").count().withColumnRenamed("count", "copies")
copies.selectExpr("sum(copies) AS rows_in_table", "count(*) AS distinct_orders", "sum(CASE WHEN copies > 1 THEN 1 ELSE 0 END) AS doubled_orders").show()The row count on its own looks like a plausible table. The warning is rows_in_table running ahead of distinct_orders, and doubled_orders names how many orders the rerun wrote twice. When every extra row is an exact copy of another, dropDuplicates(["order_id"]) keeps 1 row for each order_id and brings the table back to what a single run wrote.
After a rerun, a table that should hold 1 row per order_id has 1,500 rows and 1,200 distinct order IDs. Every extra row is an exact copy. What brings it back to a single run's output?
> Picture Netflix's nightly plays job: it reads the previous day's playback events, cleans them, appends the cleaned rows to an events table, and then writes play counts per title for the morning dashboard. At 2 a.m. a machine is reclaimed mid-stage. At 3 a.m. the count step fails on a malformed title ID. The on-call engineer patches the parser and reruns the whole job, and the morning counts come out doubled.
_2 storage level.append doubles the output, while overwrite on a per-date path does not.A dead executor rarely kills a Spark job. A careless rerun of that job can quietly corrupt its output.
- Category
- Spark
- Difficulty
- beginner
- Duration
- 12 minutes
- Challenges
- 12 hands-on challenges
Topics covered: Failures a Retry Cannot Fix, Lineage as a Recipe, Why Replays Are Safe, Idempotent Re-runs, The Half-Finished Job
Lesson Sections
- Failures a Retry Cannot Fix (concepts: Spark Execution Model)
Machines fail during jobs: a cloud provider reclaims a node, a process runs out of memory, a read from storage times out. When a task fails, Spark launches the same task again on the same input partition, usually on a different executor, and the job carries on. Retries make a cluster far more dependable than any single machine in it. What changes between attempts A deterministic failure, attempt by attempt This daily cleanup job receives quantities as text and converts them with a Python UDF. Th
- Lineage as a Recipe (concepts: Spark Execution Model)
Retrying a task assumes its input still exists. A dead executor takes things with it: every partition it had cached, the task it was halfway through, and the shuffle files on its local disk. Spark keeps no second copy of any of these by default, so before it can retry, it has to recreate whatever the task needs. Every DataFrame knows how it was made A DataFrame is a description: the transformation that produces it and the parent DataFrame that transformation applies to. Following those parent li
- Why Replays Are Safe (concepts: Spark Execution Model)
Lineage means a task can run 2, 3 or 4 times inside a single job. Running work twice is the classic way data gets doubled, like a payment sent twice. Spark's own computation never doubles, and the reason is 3 design choices working together. The input is identical on every attempt Same rows in, same rows out A filter, a selectExpr and a groupBy with a sum each compute their output from their input and nothing else. Give attempt 1 the partition attempt 0 had, and it produces the rows attempt 0 wo
- Idempotent Re-runs (concepts: Configuration Tuning)
Everything so far happened inside a single job, and Spark's protection ends where the job ends. When an orchestrator retries a failed job, or you rerun last night's job after fixing a bug, Spark starts a fresh job with no memory of the earlier one. Whatever the earlier run wrote is still at the destination, and the new run's write lands on top of it. What each write mode does to existing output The append that doubles revenue This job writes a summary row per store for a day of sales. The first
- The Half-Finished Job (concepts: Distributed Primitives)
Most jobs write more than once: a detail table, then a rollup, then a signal telling a dashboard to refresh. A failure partway through leaves some of those writes done and the rest missing. That state is incomplete, but it is honest: no row is duplicated, and the gap is visible to anyone who looks. The damage comes later, from the rerun. Run by run A single write can stop halfway too Neither failure, on its own, leaves damage that a successful run can't repair. The append's rerun is what turns a