Flink Exactly-Once: Sinks, Kafka and Limits

The Sink Problem — Where Internal Exactly-Once Stops

The problem restated: the job emits record R to an external system, then crashes before the next checkpoint. On restore, the source rewinds and R is emitted again. Flink rewound its own state; it did not — and cannot — rewind the external system.

StrategyRequirement on the sinkCostExamples
Idempotent writesWrites are keyed upserts, so applying twice equals applying onceNone on latency; needs a deterministic key and a deterministic valueCassandra/JDBC upsert, Elasticsearch by document ID, Redis SET
Transactional (2PC)Sink supports open/prepare/commit with commit deferred to another processOutput visible only at checkpoint boundaries → latency ≈ checkpoint intervalKafka transactions, filesystem sinks via staged-then-renamed files, XA JDBC

Two-phase commit driven by the checkpoint protocol

Flink's transactional sinks piggyback on the checkpoint lifecycle, which already is a two-phase commit: the barrier pass is the prepare phase, and notifyCheckpointComplete is the commit phase. The sink implements four hooks (TwoPhaseCommitSinkFunction in the legacy API, the committer interfaces of the unified Sink API in current Flink):

  1. beginTransaction — opens a fresh external transaction; all records for the current checkpoint epoch are written into it.
  2. preCommit — called when barrier(n) arrives. Flush everything, make the transaction durable-but-uncommitted, and store its identifier in the sink's checkpointed state. Then open the next transaction for epoch n+1. This step is where the sink's fate becomes tied to checkpoint n.
  3. commit — called from notifyCheckpointComplete(n), after the coordinator has durably recorded that checkpoint n exists. Only now does the output become visible to the outside world.
  4. abort — called when a checkpoint fails, discarding the pending transaction's writes.
KafkaSource                         Flink operators                 KafkaSink
  offsets in operator state    →    ABS checkpoints    →    transactional producer
                                                            (PID + epoch, Exactly-once mechanism)
                                                                   │
                                                    commit on notifyCheckpointComplete
                                                                   │
                                                      downstream: read_committed

The sink's transactional layer is not something Flink invented — it is exactly the Kafka transactional producer from Exactly-once mechanism in the main guide: transactional.id, epoch bumping, zombie fencing, PREPARE_COMMIT in __transaction_state, commit markers in each partition, and the Last Stable Offset that keeps read_committed consumers from seeing uncommitted data. Flink's contribution is deciding when to call commitTransaction(): on checkpoint completion, and never otherwise.

Delivery guaranteeDeliveryGuarantee.EXACTLY_ONCE on the sink builder
Transactional ID prefixMust be set, and must be unique per job — two jobs sharing a prefix will fence each other into a crash loop
Checkpointing modeEXACTLY_ONCE; checkpointing must be enabled at all, or the sink cannot commit
Downstreamisolation.level=read_committed, or consumers see aborted data and the guarantee is pointless
Kafka Streams (exactly_once_v2)Flink (checkpointing)
Unit of atomicityOne Kafka transaction per commit interval, per taskOne global checkpoint across every operator in the job
Scope of the guaranteeKafka → Kafka onlyAny replayable source → any idempotent or transactional sink
CoordinationNone between tasks — each task's transaction is independentGlobal; the JobManager coordinates all tasks into one cut
Durable state recordCompacted changelog topic in KafkaSnapshot files on S3/HDFS, referenced by _metadata
RecoveryReplay the changelog partition to rebuild RocksDBDownload state files, restore, rewind sources
Recovery cost driverChangelog length (mitigated by standby replicas)State size and file count (mitigated by local recovery)
Cross-operator joins & complex DAGsAwkward — repartition topics between stages, each its own taskNative — the DAG is the unit that gets checkpointed
DeploymentA library; main() is the deploymentA cluster — JobManager + TaskManagers
Output visibility latencycommit.interval.ms (100ms under EOS)Checkpoint interval (seconds to minutes)

The consequence for design questions: if the pipeline is Kafka-to-Kafka and the topology is a chain, Kafka Streams gets you exactly-once with no extra infrastructure and much lower output latency. Flink earns its cluster when the job spans systems (Kafka in, JDBC out), when the DAG genuinely branches and joins, when state is large enough that DFS snapshots beat changelog replay, or when you need event-time windowing and watermarking machinery that Streams only partially provides.

What Checkpointing Does Not Give You

Not coveredWhy it breaksWhat to do instead
Non-deterministic logicReplay re-executes your code. System.currentTimeMillis(), Random, iteration over a HashMap, or processing-time windows produce different results the second time — so restored state and replayed output disagreeDerive time from event time and watermarks; seed randomness from record content; never let output depend on wall clock or ordering you did not impose
Side effects inside operatorsAn HTTP POST, an email, a push notification fired from a map() is executed again on replay and cannot be rolled backEmit an event to a sink and let a downstream service perform the effect — the same rule as the EOS callout in the Exactly-once scope and limits part
Enrichment from a mutable external storeA lookup against a database that has since changed returns a different value on replay, so the replayed result is not the original oneMaterialize the reference data into keyed state via CDC and join against state, not against a live remote store
Non-replayable sourcesA socket or an already-acked queue cannot be rewound; in-flight data at crash time is simply goneLand everything in Kafka first; make Kafka the replay boundary
Non-transactional, non-idempotent sinksAppending rows to a table with an auto-increment key duplicates on replay with nothing to dedupe againstUpsert on a deterministic business key, or use a transactional sink
Transactions that outlive their timeoutDowntime longer than transaction.timeout.ms loses committed-but-unacknowledged output silently (see Flink + Kafka, end to end)Size the timeout against worst-case recovery; alert on restore duration
State from a mismatched topologyOperator state is keyed by operator UID; change the topology without stable uid()s and matching state is dropped without errorAssign explicit uid() to every stateful operator on day one

The honest one-liner, in the same shape as the main guide's: Flink EOS = exactly-once effect on state you checkpointed and output you committed transactionally. Determinism of your own code is an assumption it makes, not a property it provides.

The Knobs and What They Actually Trade

SettingTypical defaultWhat moving it trades
execution.checkpointing.intervalOff — must be enabledShorter → less replay after failure and lower output latency with transactional sinks; more constant overhead
execution.checkpointing.modeEXACTLY_ONCEAT_LEAST_ONCE removes alignment buffering entirely — the right choice when the sink is idempotent anyway
execution.checkpointing.min-pause0Guarantees processing time between checkpoints; the real defence against a job that spends all its time checkpointing
execution.checkpointing.timeout10 minToo low and healthy-but-slow checkpoints get killed; too high and you discover breakage very late
execution.checkpointing.max-concurrent-checkpoints1Raising it lets a slow checkpoint overlap the next — but concurrent checkpoints break the ordering transactional sinks depend on; leave at 1
execution.checkpointing.unalignedfalseConstant checkpoint duration under backpressure, at the cost of checkpoint size (see Unaligned checkpoints)
execution.checkpointing.aligned-checkpoint-timeout0 (disabled)The hybrid: aligned normally, switching to unaligned only when alignment is slow. Usually the right setting
tolerable-failed-checkpoints00 means one failed checkpoint fails the job. Raise it if transient DFS errors are a fact of life for you
Incremental checkpoints (RocksDB)offFar cheaper writes, more expensive restore (see State backends)
Local recoveryoffKeeps a second copy of state on the TaskManager's local disk so a restart on the same node skips the DFS download — large win for big-state jobs, costs local disk
Externalized checkpoint retentiondelete on cancelRetain, or a cancelled job has nothing to resume from

Self-Test

Q1: Why can't each operator just snapshot on the same wall-clock schedule?

Assume perfectly synchronized NTP across the cluster. Does that fix it?

Q2: A TaskManager dies while 3 of 8 tasks have acked checkpoint 42.

What does recovery use, and what happens to the partial state already uploaded?

Q3: Checkpoints are timing out at 10 minutes. State is 2 GB.

2 GB should upload in seconds. Where do you look, and what's the likely fix?

Q4: The job commits a Kafka transaction, then crashes before the next checkpoint.

On restore it replays those same input records and produces the same output again. Duplicates in the output topic?

Postgres has no Kafka-style transactional producer. What's the design?

Sources: Chandy & Lamport, Distributed Snapshots (1985) · Carbone et al., Lightweight Asynchronous Snapshots for Distributed Dataflows (2015) · Apache Flink documentation