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()
batch
txn_refaccount_refamount_cents
T-1001A-172500
T-1002A-031200
T-1003A-17-400
T-1004A-229900
T-1005A-03310
T-1006A-22-1500
ledger
txn_refaccount_refamount_cents
T-0998A-03700
T-0999A-224100
T-1000A-17880
T-1001A-172500
T-1002A-031200

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 = 1

Downstream 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

DesignSink must offerWho paysMisuse looks like
TransactionalAtomic commit of data and progressThe writer, plus reader disciplineA reader bypassing the log sees orphan files
IdempotentA deterministic key with upsert or overwriteThe writer, on every writeA key that changes between attempts
Downstream dedupAppend onlyEvery reader, every queryOne 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?

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.