Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 2

State, Checkpoints and Delivery Guarantees

Learn what state a streaming job keeps and where, read the checkpoint that lesson 2 left behind, compare how Spark and Flink save state and source positions together, and simulate one crash with four kinds of sink to see which delivery guarantee each gives.

Contentsand lesson path

What you will learn

  • Explain how stream processors keep state and checkpoints, and choose a delivery guarantee for a sink (at-least-once with idempotent writes or exactly-once transactions).

Prerequisites: Messaging & Event Streaming

01. Why it matters

Streaming jobs run for months, and in that time machines fail, deployments restart them and networks drop connections. Every restart raises two questions. Where was I in the input? And what had I computed so far? If the job answers them wrongly, it either loses events or counts some of them twice, and nobody notices, because the job keeps running.

This lesson explains the three pieces that answer those questions: the state that a job keeps, the checkpoint that saves state and input position together, and the sink, the system that receives the output, whose abilities decide which delivery guarantee you can promise. You will read a real Spark checkpoint and run a small simulation of a crash. Lab 4 then applies all of it to a job that reads Kafka and writes a Delta table.

02. What state a streaming job keeps

An operator is stateless when each output row depends only on one input row: a filter, a projection, or a join with a static table such as the page lookup in lab 4. Spark's documentation notes that stream-static joins keep no state. An operator is stateful when it must remember earlier rows. The common stateful operators are:

  • aggregations, including windowed counts, which keep a running value per key and window;
  • deduplication, which remembers the ids it has already seen;
  • stream-stream joins, which buffer rows of each side until a match can arrive from the other;
  • custom state, written with transformWithState in Spark 4 (recommended since Spark 4.0) or with keyed state in Flink.

State lives in a state store on the executors. Spark's default store, the HDFS-backed provider, keeps state in a hash map in the JVM memory and writes each new version to files in the checkpoint folder. For large state, Spark offers a RocksDB provider, which keeps state in native memory and on local disk, and can upload only the changes at each checkpoint (changelog checkpointing). Flink offers the same choice: HashMapStateBackend, the default, holds state as objects on the Java heap, and EmbeddedRocksDBStateBackend holds it in RocksDB, which allows state larger than memory and incremental checkpoints.

State must also be bounded. A watermark lets Spark delete windows and remembered ids that can no longer change; without one, a deduplication or an aggregation keeps every key for ever and eventually runs out of memory.

03. Checkpoints save state and position together

A Spark checkpoint is a folder, given by the checkpointLocation option, that holds everything needed to restart a query. The script below reads the checkpoint of the tumbling-window query from lesson 2, so run it in stream-lab/ after that lesson.

Python · stream-lab/read_checkpoint.py
"""Look inside the checkpoint that lesson 2's tumbling-window query left behind."""
import datetime as dt
import json
from pathlib import Path

chk = Path("wm/checkpoint-tumbling")


def batches(folder):
    return sorted(int(p.name) for p in (chk / folder).iterdir() if p.name.isdigit())


def clock(ms):
    if not ms:
        return "none"
    return f"{dt.datetime.fromtimestamp(ms / 1000, dt.timezone.utc):%H:%M}"


print("folders:", sorted(p.name for p in chk.iterdir() if not p.name.startswith(".")))
print("offsets (planned):", batches("offsets"), "| commits (done):", batches("commits"))
for batch in batches("offsets"):
    _v, meta, source = (chk / "offsets" / str(batch)).read_text().splitlines()
    mark = json.loads(meta)["batchWatermarkMs"]
    done = json.loads((chk / "commits" / str(batch)).read_text().splitlines()[1])
    print(f"batch {batch}: source {source}, watermark {clock(mark)},"
          f" next {clock(done['nextBatchWatermarkMs'])}")
for part in sorted((chk / "state" / "0").iterdir()):
    if part.name.isdigit():
        versions = sorted(int(f.stem) for f in part.glob("*.delta"))
        print(f"state partition {part.name}: versions {versions}")
Terminal
python3 read_checkpoint.py
Expected output
folders: ['commits', 'metadata', 'offsets', 'sources', 'state']
offsets (planned): [0, 1, 2, 3, 4, 5] | commits (done): [0, 1, 2, 3, 4, 5]
batch 0: source {"logOffset":0}, watermark none, next 11:57
batch 1: source {"logOffset":1}, watermark 11:57, next 12:04
batch 2: source {"logOffset":2}, watermark 12:04, next 12:08
batch 3: source {"logOffset":3}, watermark 12:08, next 12:16
batch 4: source {"logOffset":4}, watermark 12:16, next 12:21
batch 5: source {"logOffset":4}, watermark 12:21, next 12:21
state partition 0: versions [1, 2, 3, 4, 5, 6]
state partition 1: versions [1, 2, 3, 4, 5, 6]
state partition 2: versions [1, 2, 3, 4, 5, 6]
state partition 3: versions [1, 2, 3, 4, 5, 6]

The folders tell the restart story. Before Spark processes batch n, it writes offsets/n: the exact input range of the batch, here a position in the file source log, plus the watermark and some settings. This is a write-ahead log: the plan is saved before any work is done. When the batch has been written to the sink, Spark writes commits/n, which also records the watermark for the next batch. The state folder holds one version of each state partition per batch; batch n writes version n + 1. sources holds source details such as the starting position, and metadata holds the query id.

On restart, Spark finds the last batch in offsets. If commits has the same batch, everything is done, and the next batch starts from the end of that range. If commits is one behind, the batch was interrupted, so Spark loads the state version from before it and runs it again with the same input range. Lab 4 makes this happen with kill -9. Because the range is fixed in the log, the rerun processes exactly the same events, so the state is never updated twice. The checkpoint also pins some settings: the number of shuffle partitions cannot change, because state is partitioned by a hash of its key.

Flink reaches the same result differently. Its sources inject checkpoint barriers into the stream. A barrier flows with the records and never overtakes them. When an operator has received barrier n on all of its inputs, it snapshots its state and passes the barrier on; an operator with two inputs aligns them by holding back the input whose barrier came first. A completed checkpoint contains the source positions, such as Kafka offsets, and a pointer to every operator's state. After a failure, Flink restores all operators from the latest completed checkpoint and rewinds the sources to its positions. Unaligned checkpoints skip the waiting by storing in-flight buffers in the checkpoint, which helps under backpressure, and savepoints are checkpoints that you trigger yourself, for example before an upgrade.

04. Delivery guarantees end to end

A checkpoint protects the job's own state. The output is another matter, because a crash can happen after the sink has received a batch and before the checkpoint records that the batch is done. The delivery guarantee describes what the sink ends up with:

  • at-most-once: each event affects the output once or not at all; a crash can lose data;
  • at-least-once: nothing is lost, but a replayed batch can be written twice;
  • exactly-once: the output looks as if each event was processed once. Events may still be processed twice internally; the effect is applied once, which is why some people say effectively once.

The simulation reads six orders in batches of two, crashes once in the middle of batch 1, restarts and finishes. Only the way it writes changes.

Python · stream-lab/delivery.py
"""One crash, four ways to write the output: what ends up in the sink?"""
SOURCE = [("o1", 20), ("o2", 35), ("o3", 12), ("o4", 80), ("o5", 44), ("o6", 9)]
BATCH = 2                  # records per micro-batch
CRASH_IN_BATCH = 1         # the job dies once, in the middle of batch 1


def run(mode):
    sink_rows, sink_offset = [], 0      # what the sink holds (plus its own offset)
    committed = 0                       # the offset the job has committed
    crashed = False
    while True:
        start = sink_offset if mode == "transactional" else committed
        records = SOURCE[start:start + BATCH]
        if not records:
            break
        batch_id = start // BATCH
        crash_now = batch_id == CRASH_IN_BATCH and not crashed
        if mode == "at-most-once":
            committed = start + len(records)            # commit first ...
            if crash_now:
                crashed = True
                continue                                # ... then die before writing
            sink_rows += records
            continue
        if mode == "transactional":                     # rows and offset, atomically
            sink_rows, sink_offset = sink_rows + records, start + len(records)
        elif mode == "idempotent":                      # upsert by key
            keyed = dict(sink_rows) | dict(records)
            sink_rows = list(keyed.items())
        else:                                           # plain append
            sink_rows += records
        if crash_now:                                   # written, but not committed
            crashed = True
            continue
        committed = start + len(records)
    total = sum(amount for _, amount in sink_rows)
    print(f"{mode:<15} rows {len(sink_rows)}  total {total:>3}")


print("expected        rows 6  total", sum(amount for _, amount in SOURCE))
for mode in ("at-most-once", "at-least-once", "idempotent", "transactional"):
    run(mode)
Terminal
python3 delivery.py
Expected output
expected        rows 6  total 200
at-most-once    rows 4  total 108
at-least-once   rows 8  total 292
idempotent      rows 6  total 200
transactional   rows 6  total 200

Committing the position before writing loses batch 1 (orders o3 and o4). Writing and then committing replays batch 1 after the crash, so a plain append holds eight rows and the total is too high. Two designs give the right answer. An idempotent sink can receive the same write twice without changing the result: here an upsert keyed by order id simply overwrites o3 and o4 with the same values. A transactional sink stores the output and the input position in one atomic commit, so after a crash either both exist or neither does.

End-to-end exactly-once therefore needs three things together: a replayable source, such as Kafka, which can deliver the same records again from an offset; deterministic processing, so that a replay produces the same rows; and an idempotent or transactional sink. Spark's sinks differ. The file sink and the Delta Lake sink are exactly-once: Delta records the query id and batch id in its transaction log, and skips a batch it has already committed. The Kafka sink is only at-least-once, and so is the foreach sink. With foreachBatch, the guarantee depends on your code; the batch id it receives lets you skip or overwrite a repeated batch, for example with Delta's txnAppId and txnVersion write options.

Flink's KafkaSink with DeliveryGuarantee.EXACTLY_ONCE writes each checkpoint's output in a Kafka transaction and commits it only when the checkpoint completes, a two-phase commit. Consumers must read with isolation.level=read_committed, output becomes visible only at checkpoints, and the Kafka transaction timeout must be longer than the longest checkpoint plus restart, or data can be lost when Kafka aborts an expired transaction.

Choose by the sink. If it can overwrite by a key that you compute from the input, such as an order id or a window and page, idempotent writes give correct results with less delay. If it can only append, such as a Kafka topic that other teams read, you need transactions and readers that respect them. Effects outside the sink, such as sending an email from a foreach writer, are not covered by either and happen at least once.

05. Check your understanding

Practice check · 3 questions

State, checkpoints and guarantees

Pick the best answer for each situation.

Q1. A `foreachBatch` function inserts each micro-batch into a PostgreSQL table with a plain `INSERT`. After a crash, Spark runs batch 41 again with the same input range. Which change makes the repeated batch harmless?
Q2. A Flink join receives checkpoint barrier 7 on its left input, while barrier 7 has not yet reached its right input. With aligned checkpoints, what does the operator do?
Q3. A Spark query removes duplicate events by id with a two-day watermark and holds about 300 million ids in state. Executors run out of memory with the default state store. What is the usual fix?
Practice only: not graded, not saved, not evidence.

06. Apply it

For the practice project, write the delivery contract of the job you will build in lab 4, in three lines:

  1. Source: which Kafka topic, and why it can replay. What retention does it need so that a stopped job can catch up?
  2. Checkpoint: where it lives, on storage that survives the loss of the machine, and which changes to the query would force a new one.
  3. Sink: which Delta tables the job writes, why the Delta sink makes repeated batches harmless, and what a reader of the table sees between two batches.

Keep the contract; lab 4 tests each line with a real crash.

07. Review prompt

Without looking back, explain in your own words:

  • the difference between a stateless and a stateful operator, with two examples of each;
  • what Spark writes to offsets and commits, in which order, and how a restart uses them;
  • how a Flink checkpoint barrier makes a consistent snapshot, and what alignment does;
  • why at-least-once delivery plus an idempotent sink gives correct results;
  • why Spark's Kafka sink is at-least-once while its Delta sink is exactly-once.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check