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.
| Strategy | Requirement on the sink | Cost | Examples |
|---|---|---|---|
| Idempotent writes | Writes are keyed upserts, so applying twice equals applying once | None on latency; needs a deterministic key and a deterministic value | Cassandra/JDBC upsert, Elasticsearch by document ID, Redis SET |
| Transactional (2PC) | Sink supports open/prepare/commit with commit deferred to another process | Output visible only at checkpoint boundaries → latency ≈ checkpoint interval | Kafka 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):
beginTransaction— opens a fresh external transaction; all records for the current checkpoint epoch are written into it.preCommit— called whenbarrier(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.commit— called fromnotifyCheckpointComplete(n), after the coordinator has durably recorded that checkpoint n exists. Only now does the output become visible to the outside world.abort— called when a checkpoint fails, discarding the pending transaction's writes.
Flink + Kafka, Wired End to End
KafkaSource Flink operators KafkaSink
offsets in operator state → ABS checkpoints → transactional producer
(PID + epoch, Exactly-once mechanism)
│
commit on notifyCheckpointComplete
│
downstream: read_committedThe 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 guarantee | DeliveryGuarantee.EXACTLY_ONCE on the sink builder |
|---|---|
| Transactional ID prefix | Must be set, and must be unique per job — two jobs sharing a prefix will fence each other into a crash loop |
| Checkpointing mode | EXACTLY_ONCE; checkpointing must be enabled at all, or the sink cannot commit |
| Downstream | isolation.level=read_committed, or consumers see aborted data and the guarantee is pointless |
Flink Checkpoints vs. Kafka Streams EOS
Kafka Streams (exactly_once_v2) | Flink (checkpointing) | |
|---|---|---|
| Unit of atomicity | One Kafka transaction per commit interval, per task | One global checkpoint across every operator in the job |
| Scope of the guarantee | Kafka → Kafka only | Any replayable source → any idempotent or transactional sink |
| Coordination | None between tasks — each task's transaction is independent | Global; the JobManager coordinates all tasks into one cut |
| Durable state record | Compacted changelog topic in Kafka | Snapshot files on S3/HDFS, referenced by _metadata |
| Recovery | Replay the changelog partition to rebuild RocksDB | Download state files, restore, rewind sources |
| Recovery cost driver | Changelog length (mitigated by standby replicas) | State size and file count (mitigated by local recovery) |
| Cross-operator joins & complex DAGs | Awkward — repartition topics between stages, each its own task | Native — the DAG is the unit that gets checkpointed |
| Deployment | A library; main() is the deployment | A cluster — JobManager + TaskManagers |
| Output visibility latency | commit.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 covered | Why it breaks | What to do instead |
|---|---|---|
| Non-deterministic logic | Replay 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 disagree | Derive 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 operators | An HTTP POST, an email, a push notification fired from a map() is executed again on replay and cannot be rolled back | Emit 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 store | A lookup against a database that has since changed returns a different value on replay, so the replayed result is not the original one | Materialize the reference data into keyed state via CDC and join against state, not against a live remote store |
| Non-replayable sources | A socket or an already-acked queue cannot be rewound; in-flight data at crash time is simply gone | Land everything in Kafka first; make Kafka the replay boundary |
| Non-transactional, non-idempotent sinks | Appending rows to a table with an auto-increment key duplicates on replay with nothing to dedupe against | Upsert on a deterministic business key, or use a transactional sink |
| Transactions that outlive their timeout | Downtime 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 topology | Operator state is keyed by operator UID; change the topology without stable uid()s and matching state is dropped without error | Assign 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
| Setting | Typical default | What moving it trades |
|---|---|---|
execution.checkpointing.interval | Off — must be enabled | Shorter → less replay after failure and lower output latency with transactional sinks; more constant overhead |
execution.checkpointing.mode | EXACTLY_ONCE | AT_LEAST_ONCE removes alignment buffering entirely — the right choice when the sink is idempotent anyway |
execution.checkpointing.min-pause | 0 | Guarantees processing time between checkpoints; the real defence against a job that spends all its time checkpointing |
execution.checkpointing.timeout | 10 min | Too low and healthy-but-slow checkpoints get killed; too high and you discover breakage very late |
execution.checkpointing.max-concurrent-checkpoints | 1 | Raising it lets a slow checkpoint overlap the next — but concurrent checkpoints break the ordering transactional sinks depend on; leave at 1 |
execution.checkpointing.unaligned | false | Constant checkpoint duration under backpressure, at the cost of checkpoint size (see Unaligned checkpoints) |
execution.checkpointing.aligned-checkpoint-timeout | 0 (disabled) | The hybrid: aligned normally, switching to unaligned only when alignment is slow. Usually the right setting |
tolerable-failed-checkpoints | 0 | 0 means one failed checkpoint fails the job. Raise it if transient DFS errors are a fact of life for you |
| Incremental checkpoints (RocksDB) | off | Far cheaper writes, more expensive restore (see State backends) |
| Local recovery | off | Keeps 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 retention | delete on cancel | Retain, 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?
Q5: Where would you put exactly-once in a Kafka → Flink → Postgres pipeline?
Postgres has no Kafka-style transactional producer. What's the design?
Related pages
- ← Stream Processing & State Management — Where this page is linked from: Storm vs. Samza vs. Flink, data flow graphs, and the local-index-plus-changelog state model that Flink's RocksDB backend mirrors.
- Kafka EOS — Two-Layer Mechanism — The idempotent producer and the transactional API in full — the machinery Flink's Kafka sink uses as its 2PC participant in the Flink + Kafka, end to end part above.
- Companion lab — Count-Per-User-Per-Hour — The Kafka Streams side of the Flink vs. Kafka Streams part, built by hand: a real broker, a real topology, RocksDB and the changelog inspected on disk, and a deliberate crash to watch state rebuild.
Sources: Chandy & Lamport, Distributed Snapshots (1985) · Carbone et al., Lightweight Asynchronous Snapshots for Distributed Dataflows (2015) · Apache Flink documentation