Flink Checkpoints: How Exactly-Once Is Achieved

Stream processing and state in the main guide answers "how does Flink achieve exactly-once?" in three sentences: distributed checkpoints, based on Chandy-Lamport; snapshot everything at once; roll back on failure. That is true and almost useless — it hides every question an interviewer will actually ask. What does "simultaneously" mean when there is no global clock? What happens to records already in flight between two machines? Why does the guarantee survive a crash at all, when the crash may land halfway through a snapshot? And why does none of it help the moment you write to a database? This page answers all four.

"Exactly-Once" Is a Claim About State, Not About Delivery

Start from why the naive reading cannot be true. Sender S transmits a record to receiver R and waits for an ack. The ack is lost. S now faces a decision it cannot make correctly: resend (risking a duplicate) or give up (risking a loss). No number of extra round-trips resolves this — each additional message has the same problem. So on the wire, you get to choose at-most-once or at-least-once. That is the whole menu.

GuaranteeMechanismFailure outcomeWhere it's acceptable
At-most-onceFire and forget; no retryRecords vanishMetrics, sampled telemetry, log shipping
At-least-onceRetry until ackedDuplicates; counts inflateAnything with an idempotent sink (upsert by key)
Exactly-once (effect)At-least-once transport + deduplication at the state boundaryReprocessing happens but is invisible in the resultBilling, fraud counters, financial aggregation

This reframing is what makes the problem tractable, and it defines exactly what the mechanism must produce: a point in the past that every machine can agree on, such that "rewind everyone to there and replay" is indistinguishable from "never failed." That point is a checkpoint. Everything below is about constructing one correctly.

The precise Flink term is "exactly-once state consistency." Every operator's state reflects each input record exactly once. Output to the outside world is a separate problem with a separate mechanism — see The sink problem.

Why the Obvious Fixes Fail

Attempt 1 — Track every record individually (Storm's model)

Storm's original guarantee was at-least-once via an ack tree: every source tuple gets an ID, every derived tuple XORs into a running checksum, and an acker task tracks when the entire downstream tree of a source tuple has been fully processed. Fail to complete within a timeout and the source replays that tuple.

ProblemConsequence
Per-record bookkeepingOverhead scales with record count, not with state size — brutal at 500k events/sec
Replay is per-record, not per-jobAn aggregation that already incremented a counter has no idea it must un-increment
No state coordinationAcks tell you a record finished; they say nothing about which mutations it caused

This is why the main guide's table marks Storm exactly-once as "hard (manual)": the ack tree solves delivery, and delivery was never the hard part.

Attempt 2 — Deduplicate by record ID at every operator

Give every record a unique ID; each operator keeps a set of IDs it has already seen and drops repeats. Correct in principle, unusable in practice: the dedup set must cover the entire replay window, so it grows without bound (or you bound it with a TTL and silently break the guarantee for anything older). You have replaced a state-consistency problem with a much larger state-size problem.

Attempt 3 — Every operator snapshots its own state on a timer

This is the one that looks right, and its failure mode is the entire reason Chandy-Lamport exists. Operator A snapshots at wall-clock 12:00:00.000; operator B snapshots at 12:00:00.050. In those 50 milliseconds, A processed a record and forwarded a result to B.

A snapshots  (has consumed record #500)
   ↓ 50ms later
A forwards a result derived from #500 → B processes it
   ↓
B snapshots  (state already includes the effect of #500)

Crash. Restore both from their own snapshots:
  A resumes at #500 → re-processes #500 → forwards again → B applies it AGAIN
  B's state counted #500 twice.

The two snapshots describe moments that never coexisted. B's recorded state reflects a message that A's recorded state says has not been sent yet. Restoring from an inconsistent pair like this is worse than having no snapshot: it silently corrupts rather than loudly fails.

Chandy-Lamport: Snapshots Without a Global Clock

The model and its assumptions

TopologyProcesses connected by directed point-to-point channels
ChannelsFIFO and reliable — no reordering, no loss. This assumption is load-bearing
Global stateAll process states plus the contents of every in-flight channel
FailuresNone during the snapshot — the algorithm records state, it does not itself tolerate crashes

The algorithm

  1. Initiation. Some process records its own local state, then immediately sends a marker down every one of its outgoing channels — before sending any further data messages on those channels.
  2. First marker received. When a process receives a marker on channel C for the first time, it records its own local state right then, records the state of C as empty, and sends markers out on all its own outgoing channels.
  3. Recording channels. For every other incoming channel, the process starts logging the data messages it receives. It stops logging a given channel when the marker finally arrives on it. That log is the recorded state of that channel — the messages that were in flight when the cut was taken.
  4. Termination. A process is done once a marker has arrived on every incoming channel. The snapshot is complete when all processes are done; the union of process states and channel logs is the global state.

Crucially, the resulting global state may be one that never actually existed at any instant of wall-clock time — different processes recorded at different real moments. What the algorithm guarantees is that the recorded state is reachable: it is a legal state the system could have been in, consistent with causality. That is exactly the property "rewind and replay" needs.

Chandy-Lamport (1985)Flink ABS
TopologyArbitrary graph, no known entry pointKnown DAG; sources are identified up front
Who initiatesAny process, possibly severalA single CheckpointCoordinator on the JobManager, always via the sources
Marker nameMarkerCheckpoint barrier, carrying a monotonic checkpoint ID
In-flight messagesExplicitly logged as channel stateNot recorded — the operator aligns instead (see Barrier alignment), so nothing is in flight across the cut
Snapshot costProportional to in-flight volumeProportional to operator state size only
PurposeObserve a global state (deadlock detection, debugging)Restore a global state after failure

The alignment trade is the crux. Chandy-Lamport must record in-flight messages because it cannot make a process wait — it is an observation algorithm and must not perturb the system. Flink is allowed to perturb the system: it can stall one input channel for a few milliseconds. By waiting until the barrier has arrived on every input before snapshotting, an operator ensures there are no pre-checkpoint records still in flight toward it. The channel state is empty by construction, so there is nothing to log.

One Checkpoint, End to End

Checkpoint n across a four-operator job
Checkpoint n across a four-operator job

Phase by phase

  1. Trigger. The CheckpointCoordinator on the JobManager fires on execution.checkpointing.interval and RPCs only the source tasks. It does not contact the rest of the graph — the barrier does that job in-band.
  2. Source snapshot. Each source task pauses its own record emission briefly, records its read position — for a Kafka source, the offset of every partition it owns — into its operator state, and injects barrier(n) into its output stream. The barrier is a real record in the stream, ordered with the data around it.
  3. Propagation and alignment. Every downstream operator, on receiving barrier(n) on one input, stops consuming that input and waits for barrier(n) on all remaining inputs (see Barrier alignment). Once the last one arrives, the operator's state contains the effects of exactly the records that preceded the barrier everywhere — the consistent cut.
  4. Snapshot and forward. The operator captures an immutable view of its state (synchronous, milliseconds), forwards barrier(n) to all outputs, and resumes processing at once. The upload to durable storage proceeds on a background thread.
  5. Acknowledge. When the upload finishes, the task sends the coordinator an ack carrying a state handle — a pointer to the uploaded files, not the state itself. Large states never transit the JobManager.
  6. Completion. Once every task in the job has acked checkpoint n, the coordinator writes a _metadata file containing all the handles. This write is the commit point. Then, and only then, it sends notifyCheckpointComplete(n) to every task — the signal transactional sinks use to commit (see The sink problem).

Barrier Alignment — Where the Guarantee Is Actually Enforced

Consider an operator with two inputs. Channel 1 delivers barrier(n) at t=0; channel 2 is slower and delivers it at t=40ms. Records arriving on channel 1 during those 40ms logically belong to the next epoch — they were emitted after the upstream had already snapshotted. If the operator processed them, its state would include effects from after the cut, and on restore those records would be replayed and counted a second time.

Input 1:  ... r7 r6 [B(n)] │ r5 r4 r3 ────► must be buffered (epoch n+1)
Input 2:  ... r9 r8 r7 r6 r5 [B(n)] ───────► still arriving (epoch n)
                                  ▲
                        operator waits here, processing only input 2

After B(n) arrives on input 2:
  snapshot state → forward B(n) → unblock input 1 → drain buffer
ModeBehavior on early barrierGuaranteeLatency cost
EXACTLY_ONCE (aligned)Block the channel, buffer its recordsConsistent cut; no record counted twiceRecords wait for the slowest channel's barrier
AT_LEAST_ONCEKeep processing everything; snapshot on the first barrierPost-cut records may be applied twice on restoreNone — no buffering at all

Data skew produces the same symptom without any global backpressure: if one keyed partition receives 10× the traffic of its siblings, its barrier is consistently the last to arrive and every checkpoint pays for it. That case is fixed by re-keying, not by checkpoint configuration.

Unaligned Checkpoints — Buying Back Chandy-Lamport

The mechanism inverts the trade. Rather than making the barrier wait for the records ahead of it, the barrier is moved to the front of the input queue the instant it arrives, and every record it jumped over — plus everything already buffered on the other input channels — is captured as channel state and uploaded with the operator's state. On restore, those buffers are re-injected into the exact channels they came from before processing resumes, reconstructing the pre-crash in-flight picture.

AlignedUnaligned
Barrier vs. dataStrictly ordered — barrier waits its turnBarrier overtakes queued records
In-flight recordsNone across the cut, by constructionSnapshotted as channel state
Checkpoint duration under backpressureGrows with backpressure — can time outRoughly constant
Checkpoint sizeOperator state onlyOperator state + all in-flight buffers
RecoveryRestore state, rewind sourcesRestore state, re-inject buffers, rewind sources
Rescaling from itFully supportedSupported, but channel state must be redistributed — slower and historically the more fragile path
ConfigDefaultexecution.checkpointing.unaligned: true

Where the State Actually Lands

State backendWorking stateSnapshot behaviorUse when
HashMapStateBackendJava objects on the JVM heapFull snapshot every time; heap-sized, so GC pressure is the limitState fits comfortably in memory; lowest per-record latency
EmbeddedRocksDBStateBackendSerialized bytes in RocksDB on local diskSupports incremental checkpointsState exceeds memory — the only realistic option past tens of GB

Note the exact echo of Commit Semantics in the main guide: Kafka Streams also keeps local state in RocksDB co-partitioned with the input. Both systems reached the same conclusion — local embedded storage for reads, remote durable storage for recovery. What differs is the durable half: Streams backs RocksDB with a compacted Kafka topic; Flink backs it with snapshot files on a DFS. The Flink vs. Kafka Streams part works through what that difference buys and costs.

Incremental checkpoints

RocksDB is an LSM tree: writes land in a memtable, get flushed to immutable SST files, and background compaction merges them. Immutability is the opening — an SST file already uploaded for checkpoint n is byte-identical in checkpoint n+1, so it need not be uploaded again.

Checkpoint 5:  upload sst_001, sst_002, sst_003        (full: 50 GB)
Checkpoint 6:  sst_001..003 unchanged → reference them
               upload only sst_004                      (delta: 200 MB)
Checkpoint 7:  compaction merged 001+002 → sst_005
               upload sst_005, drop refs to 001, 002    (delta: 1.2 GB)

The coordinator's _metadata therefore holds handles into files shared across several checkpoints, and Flink reference-counts them so a file is deleted only once no retained checkpoint still points at it.

Checkpoint storage

JobManager storageState ships to and lives in JobManager memory. Testing only — it dies with the JobManager and caps out in megabytes
Filesystem storageS3, HDFS, GCS. The only production answer: durable, independent of any cluster node, and readable by a freshly-scheduled task on any machine
RetentionCheckpoints are deleted on job cancel unless externalized retention is configured — the single most commonly regretted default

Recovery — Restore, Rewind, Replay

  1. Detect & stop. A TaskManager loss or an operator exception fails the job's execution graph. Under the default region failover strategy, only the connected pipelined region containing the failure is restarted; a job with fully independent branches does not stop the branches that are fine.
  2. Pick a checkpoint. The coordinator selects the most recent checkpoint with a complete _metadata. Anything newer and half-finished is discarded outright.
  3. Redistribute state. Each restarted task fetches its state handles and rebuilds local state. Keyed state is stored in key groups — a fixed number of hash buckets set by maxParallelism — so on a parallelism change, key groups are simply reassigned to the new task count. Key groups are why rescaling from a checkpoint works at all.
  4. Rewind sources. The Kafka source's stored offsets are part of its restored operator state. It seeks to them and resumes. Everything produced after the checkpoint is read again.
  5. Replay. Reprocessing runs against rewound state, so counters, windows and joins reach exactly the values they would have had without the failure. Sinks resolve their own duplicates via the sink problem part.

Checkpoints vs. savepoints

CheckpointSavepoint
Owned byFlinkThe user
Triggered byThe system, periodicallyA human or a deploy pipeline
PurposeAutomatic failure recoveryVersion upgrades, code changes, planned rescaling, migration
FormatBackend-specific, incremental — optimized for write speedCanonical and portable by default — restorable after changing the state backend
LifecycleAuto-deleted, superseded by the next oneRetained until explicitly deleted

Both restore through the identical mechanism; the difference is ownership and format stability. Practical rule: never deploy new job code by cancelling and restarting from a checkpoint — take a savepoint, deploy, restore from the savepoint. And assign stable uid()s to your operators, because state is matched to operators by that ID; an auto-generated ID changes when the topology changes and the matching state is silently dropped.