Choosing At-Least-Once
Concepts covered: 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
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.
Any pipeline fed by client retries therefore needs dedup by a record key somewhere. Once that dedup exists, it also absorbs every duplicate a Spark retry or replayed batch adds, and exactly-once machinery between the queue and the dedup step buys little. That is the case for at-least-once plus dedup: one mechanism handles both sources of duplicates.
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()| event_uuid | user_id | event_name | received_ts |
|---|---|---|---|
| e-01 | 7 | play | 2024-03-14 20:01:05 |
| e-02 | 9 | pause | 2024-03-14 20:01:09 |
| e-03 | 7 | play | 2024-03-14 20:02:30 |
| e-01 | 7 | play | 2024-03-14 20:01:41 |
| e-04 | 12 | search | 2024-03-14 20:03:02 |
| e-02 | 9 | pause | 2024-03-14 20:01:55 |
| e-05 | 12 | play | 2024-03-14 20:03:20 |
| e-03 | 7 | play | 2024-03-14 20:04:10 |
| e-06 | 4 | stop | 2024-03-14 20:05:00 |
| e-01 | 7 | play | 2024-03-14 20:06:12 |
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.
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.
events = (
raw_events.withWatermark("event_ts", "2 hours")
.dropDuplicatesWithinWatermark(["event_uuid"])
)The bound turns the guarantee into a sentence with a number in it: copies of an event arriving within 2 hours of each other are removed. Size it from observed behavior; if client retries finish within minutes and replays within one batch, 2 hours leaves wide margin.
State the guarantee per edge
Guarantees belong to edges. Each edge carries its own, set by the mechanism on it, and the end-to-end promise is whatever survives the weakest edge once the dedup steps after it have run.
- Mobile app (source, client SDK)
- Event queue (queue, log broker)
- Ingest stream (transform, Structured Streaming); on error: replay batch from offsets
- Bronze events (bronze, append-only table)
- Silver events (silver, deduped by event_uuid); idempotency: keep earliest delivery
- Gold daily plays (gold, daily aggregate); idempotency: overwrite ds partition
- Partner webhook (consumer, HTTP sink); idempotency: event_uuid as key
- Mobile app -> Event queue
- Event queue -> Ingest stream
- Ingest stream -> Bronze events
- Bronze events -> Silver events
- Silver events -> Gold daily plays
- Silver events -> Partner webhook
- Sources: Mobile app, Event queue
- Raw: Ingest stream, Bronze events
- Curated: Silver events
- Serving: Gold daily plays, Partner webhook
| 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 |
Written this way, the guarantee is something a teammate can check. Bronze promises nothing about duplicates and says so; anyone counting events reads silver. Gold is exact because its only input is deduplicated and its write is idempotent. Exactly-once machinery is worth its cost on an edge with no dedup after it, such as a payment or a notification, where no later step can take the duplicate back.
- Do
- 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
- Avoid
- 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?
- Exactly-once end to end, since the transaction removes duplicates at their source
- A simpler silver step, since silver no longer has to dedup client retries
- Little: bronze loses replay copies, which silver's dedup already removed
- Safety on the webhook edge, which then no longer needs an idempotency key
About this lesson
This section is part of the Fault Tolerance: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.