Effects That Land Once

Concepts covered: 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 message to a user, changes one time, however many times the record was processed.

Processing count vs effect count

SemanticsTimes processedTimes the effect landsWhat goes wrong
At-most-once0 or 10 or 1A crash between read and write loses the record
At-least-once1 or more1 or moreA retry after a partial write lands the effect twice
Exactly-once1 or moreExactly 1Nothing, while all 3 legs below hold

An exactly-once pipeline still processes some records 2 or 3 times; it arranges for the extra runs to leave no trace. That is why engineers often call it effectively-once: the work repeats, the outcome does not.

The 3 legs

Exactly-once needs all 3

Break any leg and the guarantee falls to at-least-once or worse. A replayable source plus Spark's record of what it read covers the first leg, and deterministic code covers the second. The third is where most pipelines lose the guarantee: the sink lives outside Spark, and Spark cannot roll it back.

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?

import requests


def send_receipts(rows):
    session = requests.Session()
    for row in rows:
        session.post(
            "https://payments.internal/receipts",
            json={"user_id": row.user_id, "amount": row.amount},
        )


receipts.foreachPartition(send_receipts)

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.

import requests


def send_receipts(rows):
    session = requests.Session()
    for row in rows:
        session.post(
            "https://payments.internal/receipts",
            json={"user_id": row.user_id, "amount": row.amount},
            headers={"Idempotency-Key": row.event_uuid},
        )

The guarantee now sits at the sink. The key comes from the record, so every attempt sends the same one, and the receiver turns repeats into no-ops. Spark still processes those 300 rows twice; their effect lands once. The key must be deterministic: a UUID generated inside the task differs on each attempt and dedups nothing.

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.

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.