Sink Taxonomy
Concepts covered: 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
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.
def write_batch(batch_df, batch_id):
(
batch_df.write.mode("overwrite")
.parquet(f"/lake/payouts/batch_id={batch_id}")
)
query = (
payouts.writeStream.foreachBatch(write_batch)
.option("checkpointLocation", "/chk/payouts")
.start()
)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.
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 F
spark.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()| txn_ref | account_ref | amount_cents |
|---|---|---|
| T-1001 | A-17 | 2500 |
| T-1002 | A-03 | 1200 |
| T-1003 | A-17 | -400 |
| T-1004 | A-22 | 9900 |
| T-1005 | A-03 | 310 |
| T-1006 | A-22 | -1500 |
| txn_ref | account_ref | amount_cents |
|---|---|---|
| T-0998 | A-03 | 700 |
| T-0999 | A-22 | 4100 |
| T-1000 | A-17 | 880 |
| T-1001 | A-17 | 2500 |
| T-1002 | A-03 | 1200 |
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's keys and a shuffle of both sides.
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.
SELECT
event_uuid,
user_id,
event_name,
event_ts
FROM (
SELECT
event_uuid,
user_id,
event_name,
event_ts,
ROW_NUMBER() OVER (PARTITION BY event_uuid ORDER BY received_ts) AS rn
FROM app_event_deliveries
) AS ranked
WHERE rn = 1Downstream dedup asks nothing of the sink, so it works where neither transactions nor keyed writes exist. The bill goes to readers: each pays a shuffle on the key, and a reader who forgets the dedup gets inflated numbers and no error.
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 |
Defend a choice by starting from the sink's capability. If it commits atomically and every reader goes through the commit, use that. If it accepts keyed writes and records carry a stable key, make writes idempotent: this survives replays, reruns and manual backfills alike. Fall back to downstream dedup when the sink can only append, and materialize the deduped table once so no reader can skip it.
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?
- Idempotent: overwrite the run's ds partition, so a rerun replaces that day exactly
- Transactional: add a commit log, because no rerun is safe without one
- Downstream dedup: append every run and let dashboards dedup by txn_id
- Idempotent: upsert each row by txn_id, since overwrites break on rerun
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.