Fault Tolerance: Advanced
Processing count vs effect count
| Semantics | Times processed | Times the effect lands | What goes wrong |
|---|---|---|---|
| At-most-once | 0 or 1 | 0 or 1 | A crash between read and write loses the record |
| At-least-once | 1 or more | 1 or more | A retry after a partial write lands the effect twice |
| Exactly-once | 1 or more | Exactly 1 | Nothing, while all 3 legs below hold |
The 3 legs
- Replayable sourceRead the same records againAfter a failure the job can request exactly the records it read before, by offset, file list or table snapshot.
- Deterministic processingSame input, same outputThe replay must produce the rows the first run produced. A rand(), a current_timestamp() or an order-dependent first() breaks this.
- Idempotent or transactional sinkA repeat changes nothingEither writing the same output twice leaves the sink unchanged, or the write and the progress record commit together, so a replay finds its work already done.
Effects inside Spark and outside it
Inside its own boundary, Spark already makes effects land once. Shuffle files from a failed attempt are discarded, and when 2 speculative attempts of one write task both finish, the driver's OutputCommitCoordinator authorizes only one of them to commit its partition. The other attempt's files never become output.
Accumulators show where that boundary sits. For an accumulator updated inside an action such as foreach, Spark applies each task's update once. Inside a transformation, such as a map or a UDF, every successful run of a task applies its update, so a stage resubmitted after a fetch failure, or recomputed by a second action, counts its rows again.
A job counts malformed rows with an accumulator incremented inside a UDF and writes the clean rows to files. A lost node causes a fetch failure, and Spark resubmits a map stage whose tasks had already succeeded. Which numbers can you trust?
This job runs foreachPartition, an action, so Spark's own accounting is exact, and users still get duplicate receipts. The effect left Spark when the HTTP call returned. The retry reprocesses the whole partition, and the receiving service cannot tell the second POST from a new receipt.
The practice table app_event_deliveries holds 1 row per delivery an ingestion endpoint received. Run the cell: rows with no event_uuid account for the gap between the first 2 counts, and duplicate deliveries for the gap between the last 2, duplicates the pipeline must absorb before a single Spark retry adds more.
from pyspark.sql import functions as F
deliveries = spark.table("app_event_deliveries")
summary = deliveries.agg(
F.count("*").alias("deliveries"),
F.count("event_uuid").alias("keyed_deliveries"),
F.countDistinct("event_uuid").alias("distinct_events"),
)
summary.collect()Transactional sinks
A transactional sink commits the output and the record of progress in one atomic step. Spark's streaming file sink works this way: each micro-batch writes its files, then appends an entry for batch N to the _spark_metadata log in the output directory. A batch that crashed before that entry leaves files that no entry names, so a Spark reader skips them, and on restart the query sees batch N uncommitted and rewrites it.
The cost lands on readers: any tool that lists the directory without consulting _spark_metadata sees the failed attempt's orphan files and double counts.
Idempotent sinks
An idempotent sink makes the second write harmless instead of preventing it. The write is keyed by something deterministic, and writing a key twice leaves one result: a put to a key-value store, an upsert on a primary key, an overwrite of the partition ds=2024-03-14. The sink needs no transaction, only a key the replay reproduces exactly.
In Structured Streaming, foreachBatch is where most jobs build one. On its own it promises at-least-once, and Spark's documentation names the batchId it passes in as the key that closes the gap.
A table with no partition to overwrite gets an insert-if-absent instead: keep only incoming rows whose key the table does not already hold. The animation replays a batch of 6 postings against a ledger that already holds 2 of them. Broadcasting is off so the price shows: both sides shuffle by txn_ref, so matching keys meet on one task.
from pyspark.sql import functions as Fspark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)seen = ledger.select("txn_ref", F.lit(1).alias("seen"))fresh = (batch.join(seen, "txn_ref", "left").filter(F.col("seen").isNull()).drop("seen"))fresh.collect()
Downstream dedup
The third family gives up on the sink. The writer appends at-least-once, duplicates included, and every record carries a unique key such as event_uuid. Readers dedup by that key, or a scheduled job writes a clean copy.
Choosing and defending a design
| Design | Sink must offer | Who pays | Misuse looks like |
|---|---|---|---|
| Transactional | Atomic commit of data and progress | The writer, plus reader discipline | A reader bypassing the log sees orphan files |
| Idempotent | A deterministic key with upsert or overwrite | The writer, on every write | A key that changes between attempts |
| Downstream dedup | Append only | Every reader, every query | One reader skips the dedup and overcounts |
A nightly job writes revenue per merchant into a table that can overwrite 1 ds partition at a time but has no multi-partition transactions. Each run owns exactly 1 day, and records carry a stable txn_id. Which design fits?
The commit protocol you already know assumes renaming a directory is one atomic metadata operation. Tasks write under _temporary, task commit renames each attempt directory, job commit renames the results into place, and _SUCCESS appears last. On a cluster filesystem such as HDFS each rename edits the namenode's metadata and finishes in milliseconds.
An object store has no directories and no rename. A path like /sales/ds=2024-03-14/part-00007.parquet is one key in a flat namespace, and the slashes are ordinary characters. Renaming means copying each object to a new key and deleting the old one, so a rename costs time in proportion to bytes, and renaming a directory becomes thousands of independent copies that can stop halfway.
What the rename turns into
| Commit step (algorithm v1) | On a cluster filesystem | On an object store |
|---|---|---|
| Task commit | Rename the attempt directory: one metadata edit | Copy and delete every file the task wrote |
| Job commit | Rename each task's output: metadata edits | Copy and delete every file again, issued by the driver |
| Crash mid-commit | Each rename is all or nothing | Some files moved, some not |
Committers built for object stores
Tasks upload to final keys and leave each upload open; job commit sends one small completion request per file, and only then do readers see it.
Fast job commit narrows the danger window without closing it: a driver that dies after completing 600 of 1,000 uploads leaves 600 files visible. The guarantee is per file, and _SUCCESS is still the only sign that a directory is whole.
Table formats commit a pointer
- Visibility follows which files sit in the directory
- Commit cost grows with bytes written
- A crash mid-commit can leave a partial directory
- Readers trust _SUCCESS by convention
- Visibility follows which files the log lists
- Commit cost is one metadata write
- A crash leaves unreferenced files no reader sees
- Readers resolve a snapshot and get all or nothing
A job of 2,000 tasks, each writing 1 file, runs with algorithm v2 on an object store. The driver crashes after 1,200 task commits. What does a reader listing the destination see?
Which failure is the checkpoint for?
| Failure | How Spark recovers | What a checkpoint saves |
|---|---|---|
| Task failure | Retries the task from its stage's inputs | Nothing: the retry reads input that already exists |
| Executor or node loss | Recomputes lost partitions from lineage, plus shuffle files lost with a node | The walk back through a long lineage |
| Driver loss | It does not: the application ends | Everything since the last reliable write, if the rerun resumes from it |
Young's interval
| Checkpoint plan | Segments | Run time, no failures | Expected run time |
|---|---|---|---|
| None | 1 | 6.00 h | 8.94 h |
| Every 3 hours | 2 | 6.17 h | 7.52 h |
| Every 72 minutes (Young) | 5 | 6.42 h | 6.96 h |
| Every 10 minutes (habit) | 36 | 9.00 h | 9.14 h |
Inside a job: lineage depth
A 20-hour job faces a restart-forcing failure every 50 hours on average, and a reliable checkpoint costs 4 minutes. Roughly how often should it checkpoint?
Duplicates upstream of Spark
Exactly-once covers the edges it is built on and nothing upstream. A phone sends an event, loses its connection before the acknowledgement, and sends it again: the duplicate exists before Spark reads anything. Spark can carry both copies from the queue into a table with flawless exactly-once semantics, and the table holds both. The app_event_deliveries table from the first section models this case: 1 row per delivery, each tagged with the event_uuid its sender assigned.
Pricing the dedup
Dedup by key needs every copy of a key on one task, so it costs a shuffle. In the animation, the 2 input partitions each hold copies whose twins sit in the other partition. Each task first drops repeats within its own rows, then the shuffle routes each event_uuid to one reducer, where the remaining copies meet and collapse.
unique_events = deliveries.dropDuplicates(["event_uuid"])unique_events.collect()
The 10 deliveries became 6 events. Look at which received_ts survived for e-01: dropDuplicates keeps whichever copy its aggregation meets first, and that depends on task and partition order. When copies differ in any column, rank them explicitly so a replay keeps the same row. Duplicates are rare on a real table, so nearly every row survives the per-task step, and deduping 500GB of events is roughly a 500GB shuffle: pay it once in a materialized table rather than in every query.
Run the explicit version on the practice table. Rows with no event_uuid are filtered out first: a window would put them all in one partition and keep 1 of them at random. The window keeps the earliest received_ts per event_uuid and breaks ties on delivery_id, so every run keeps the same row.
from pyspark.sql import Window
from pyspark.sql import functions as F
deliveries = spark.table("app_event_deliveries")
first_delivery = Window.partitionBy("event_uuid").orderBy("received_ts", "delivery_id")
events = (
deliveries.filter(F.col("event_uuid").isNotNull())
.withColumn("rn", F.row_number().over(first_delivery))
.filter(F.col("rn") == 1)
.drop("rn")
)
events.collect()The result has 1 row per event_uuid, as many as the distinct_events count from the first section. The tie-break is what makes a rerun keep the same row: 2 copies received in the same second tie on received_ts, and without delivery_id a rerun could keep the other one.
Streaming dedup needs a bound
A streaming dedup must remember every key it has seen, and that state grows without limit unless a watermark bounds it. With a 2-hour watermark on event_ts, Spark forgets keys once the watermark passes them, so a copy arriving more than roughly 2 hours after its twin slips through. Spark 3.5 added dropDuplicatesWithinWatermark, which bounds state this way without putting event time in the dedup key.
State the guarantee per edge
Duplicates enter on the first 2 edges and leave at the silver dedup; every write after it is idempotent.
| Edge | Guarantee | Mechanism |
|---|---|---|
| App to queue | At-least-once | Client retries until acknowledged |
| Queue to bronze | At-least-once | Append; replays and client copies both land |
| Bronze to silver | Once per `event_uuid` | Rank by key, keep the earliest delivery |
| Silver to gold | Exactly-once per `ds` | Deterministic aggregate, partition overwrite |
| Silver to webhook | Once-only effect | Sends repeat; `event_uuid` is the idempotency key |
- Give every record a unique key where it is created
- Dedup once, into a materialized table every reader uses
- Size streaming dedup watermarks from observed retry delays
- Generate dedup keys inside a Spark task
- Claim end-to-end exactly-once from one transactional edge
- Use dropDuplicates when copies differ and the survivor matters
A team wants to make the queue-to-bronze edge transactional so the pipeline becomes exactly-once. Events come from mobile clients that retry, and silver already dedups by event_uuid. What does the change buy?
> Picture a team at Netflix computing daily viewing hours per title from playback events that phones and TVs send. Devices retry on flaky networks, the ingest stream runs on spot executors, the daily rollup lands in an object store, and a webhook tells partner teams when a title passes 1 million hours in a day.
Exactly-once as a property of effects: sinks, object-store commits, checkpoint math, and when at-least-once wins.
- Category
- Spark
- Difficulty
- advanced
- Duration
- 15 minutes
- Challenges
- 15 hands-on challenges
Topics covered: Effects That Land Once, Sink Taxonomy, The Object-Store Commit, Checkpoint Frequency, Choosing At-Least-Once
Lesson Sections
- Effects That Land Once (concepts: Structured Streaming)
Spark reprocesses data as a matter of routine. A failed task gets up to 4 attempts. A speculative copy races a slow task. A fetch failure sends a stage back to rebuild its map output, and a restarted streaming query replays its last micro-batch. Each of these runs the same records through the same code more than once. That is acceptable because the guarantee people want concerns effects. Exactly-once promises that whatever a record changes outside the job, a table row, an account balance, a mess
- Sink Taxonomy (concepts: Structured Streaming)
Once the sink carries the guarantee, every sink design falls into one of 3 families, and each puts the cost in a different place. Transactional sinks Idempotent sinks Legs 1 and 2 do the work here: the checkpointed offsets make the replayed batch 812 hold the same rows, and deterministic code turns them into the same output. The 2 replayed postings meet their ledger twins on one reducer and drop out; the 4 new ones pass. In production the ledger is large, so every write pays a scan of the ledger
- The Object-Store Commit (concepts: Distributed Primitives)
What the rename turns into Put numbers on it. A job writes 1,000 files of 128MB each. Algorithm v1 copies that output twice, and the job-commit copies run from the driver. Assume the store copies 100MB/s per object and the driver works through files one at a time. Algorithm v2 drops the second copy by having task commit move files straight into the destination. The job runs faster and loses its job-level guarantee: readers can see a half-finished job's output, and an attempt that fails mid-commi
- Checkpoint Frequency (concepts: Caching & Persistence)
Every checkpoint is a bet. You pay its write cost on every run and collect only on runs where something fails after it. Checkpoint too rarely and a failure throws away hours; too often and the writes cost more than the failures they insure against. The interval follows from 2 numbers you can measure: what a single checkpoint costs, and how often the failure it guards against happens. Which failure is the checkpoint for? Task failures need no checkpoint. Executor loss needs one only where lineage
- Choosing At-Least-Once (concepts: Structured Streaming)
Exactly-once machinery has running costs. A transactional sink adds a commit to every batch, which sets a floor on latency and on batch size. An idempotent sink needs a stable key and a lookup or overwrite on every write. Both tie the pipeline to sinks that support them. The duplicates they prevent appear only when something fails: if 1 task attempt in 500 fails after writing, replays touch roughly 0.2% of the rows, while the commit is paid on every batch. Duplicates upstream of Spark Any pipeli