DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stream Processing on the Mainframe With Apache Flink: Genius or a Glitch in the Matrix?
  • Dead Letter Queue Patterns in Apache Flink: Handling Poison Messages Without Stopping Your Stream
  • Superior Stream Processing: Apache Flink's Impact on Data Lakehouse Architecture
  • Should Developers Switch From SQLite to DuckDB?

Trending

  • Where the Model Stops and the Code Starts: Lessons From an AI Procurement Agent
  • How We Cut DynamoDB Ingestion Reads With an S3 Hash Pre-Filter
  • From Theory to Practice: Building an Enterprise Ontology With Python and Kubernetes
  • Why Your CI Pipeline Is Flaky and How to Make It Reliable

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Big Data
  4. Exactly-Once Stream Processing With Apache Flink

Exactly-Once Stream Processing With Apache Flink

Learn how Apache Flink achieves exactly-once processing through checkpointing, state backends, transactional sinks, and production configuration.

By 
Prudhvi Kashyap Jamalapuram
·
Nov. 27, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
43 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Exactly-once semantics is one of the most cited — and most misunderstood — promises in stream processing. This article explains how Apache Flink actually delivers exactly-once guarantees: distributed checkpointing, state backend selection, two-phase-commit sinks, and the operational tuning that separates a working demo from a reliable production pipeline. It also covers the failure modes that show up most often in real deployments and how to configure around them.

What "Exactly-Once" Really Means

Ask five engineers what exactly-once means, and you will get five answers. In Flink, the useful distinction is between processing semantics and end-to-end semantics.

Processing semantics cover what happens inside the Flink job: each record updates operator state exactly once, even across failures. Flink achieves this through distributed checkpointing, and it is genuinely exactly-once for stateful computation.

End-to-end semantics cover the full path from source to sink. This is harder, because it depends on the sink's ability to participate in a transaction. A Flink job reading from Kafka and writing to a filesystem can be end-to-end exactly-once. The same job writing to a sink that only supports appends cannot — no matter what the checkpointing mode says.

Checkpointing: The Core Mechanism

Flink's checkpointing is based on the Chandy–Lamport distributed snapshot algorithm. Source operators inject checkpoint barriers into the data streams; as barriers flow through the operators, each operator snapshots its state. When every operator has acknowledged its snapshot, the checkpoint is complete, and the JobManager records it as the new recovery point.

A minimal production-ready checkpointing configuration looks like this:

Java
 
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(60_000); // checkpoint every 60 seconds
env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
env.getCheckpointConfig().setMinPauseBetweenCheckpoints(30_000);
env.getCheckpointConfig().setCheckpointTimeout(10 * 60_000);
env.getCheckpointConfig().setTolerableCheckpointFailureNumber(3);
env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);


Every one of these numbers is a tradeoff, and the defaults are tuned for demos, not production.

Choosing a State Backend

The state backend determines where operator state lives and how it is snapshotted. The two realistic choices:

  • HashMapStateBackend keeps working state on the TaskManager heap and snapshots it to the configured checkpoint storage. It is fast for small-to-medium state (tens of GB per operator) but couples your state size to the JVM heap, which invites long GC pauses and out-of-memory kills as state grows.
  • EmbeddedRocksDBStateBackend keeps working state in RocksDB (off-heap / local disk) and snapshots incrementally. It handles hundreds of GBs of state per operator and supports incremental checkpoints, which dramatically shrink checkpoint size and duration for large state.

The rule of thumb: if your keyed state is small and latency-sensitive, HashMap is simpler and faster. If state grows unboundedly — session windows, long-lived aggregations, deduplication tables — RocksDB with incremental checkpoints is the only sustainable choice.

Java
 
env.setStateBackend(new EmbeddedRocksDBStateBackend(true)); // incremental checkpoints enabled
env.getCheckpointConfig().setCheckpointStorage("hdfs://namenode:8020/flink/checkpoints");


Checkpoint storage should always be a durable distributed filesystem (HDFS, S3), never local disk. A checkpoint that dies with the TaskManager is not a recovery point.

Tuning Checkpoints for Production

Four knobs matter most:

  1. Checkpoint interval. Shorter intervals mean less reprocessing on recovery but more steady-state overhead. Start at 1–3 minutes for most pipelines. Sub-minute intervals are justified only when recovery-time objectives demand it, because barrier alignment itself starts to cost throughput.
  2. Minimum pause between checkpoints. Prevents a slow checkpoint from triggering the next one immediately, which causes checkpoint pile-up and ever-growing alignment times. Set it to roughly half the interval.
  3. Checkpoint timeout and tolerable failures. Transient checkpoint failures happen — a slow HDFS NameNode, a network blip. Allowing a small number of consecutive failures before failing the job avoids cascading restarts from infrastructure hiccups.
  4. Unaligned checkpoints. When backpressure is high, barrier alignment can stall checkpoints for minutes. Unaligned checkpoints snapshot in-flight data too, trading larger checkpoint size for bounded checkpoint duration under backpressure. Enable them for pipelines that regularly run hot: env.getCheckpointConfig().enableUnalignedCheckpoints();

End-to-End Exactly-Once: The Sink Problem

Checkpointing gives you exactly-once state. Exactly-once output requires a sink that can commit atomically. Flink's answer is two-phase-commit sinks. The canonical example is Kafka:

Java
 
FlinkKafkaProducer<String, String> sink = new FlinkKafkaProducer<>("output-topic", new SimpleStringSchema(), producerProps, FlinkKafkaProducer.Semantic.EXACTLY_ONCE);


Under the hood, Flink opens a Kafka transaction per checkpoint interval, writes records into it, and commits the transaction only when the checkpoint completes. If the job fails mid-checkpoint, the transaction aborts and no partial output is visible. This works, but it has real operational costs: it requires Kafka 0.11+, it increases end-to-end latency by at least one checkpoint interval, and transactional producers need transaction.timeout.ms tuned above your maximum checkpoint duration or transactions expire mid-flight — a classic production footgun.

For file sinks (HDFS/S3), Flink uses the StreamingFileSink / FileSink with a pending-file mechanism: files are written to a temporary location and moved to their final location only on checkpoint completion. Same principle, different mechanics.

Recovery: Restart Strategies and Savepoints

Checkpoints handle automatic recovery; savepoints handle planned operations (code upgrades, rescaling, migration). The distinction matters operationally: checkpoints are owned by the runtime and can be discarded; savepoints are user-triggered and portable.

One subtlety that bites teams during upgrades: savepoints are not always forward-compatible across Flink versions or across changes to operator state schemas. Before any upgrade, verify in staging that the new job can restore from a savepoint taken by the old version. Flink's state schema evolution handles many cases (adding fields, widening types), but renaming operators or changing key serializers breaks restore. The UID you assign to each operator (uid("my-operator")) is what ties state to operators across restarts — always set explicit UIDs on stateful operators, or a topology change will silently orphan state.

Pair checkpointing with an explicit restart strategy. The fixed-delay strategy with a bounded number of attempts prevents a poisoned record from restarting a job forever:

Java
 
env.setRestartStrategy(RestartStrategies.fixedDelayRestart(5, Time.of(30, TimeUnit.SECONDS)));


Common Pitfalls in Production

  • Non-deterministic functions in operators. Anything depending on wall-clock time, random numbers, or external calls breaks the assumption that replay produces identical results. Keep operators deterministic; push non-determinism to sources or sinks.
  • Checkpoint storage on the same cluster as compute. If the HDFS cluster hosting checkpoints has a bad day, you lose both the job and its recovery points. Separate failure domains where possible.
  • Ignoring checkpoint metrics. Flink exposes checkpoint duration, size, and alignment time per operator. A steadily growing checkpoint duration is an early warning of state growth problems — treat it like a latency SLO, not a curiosity.
  • Exactly-once claimed but not verified. Test failure injection (kill TaskManagers mid-checkpoint) in staging and verify output idempotency. The guarantee is only as real as your last chaos test.

A Production Checklist

  1. Durable checkpoint storage on a distributed filesystem.
  2. State backend matched to state size (RocksDB + incremental for large state).
  3. Interval, pause, timeout, and tolerable failures tuned — not defaulted.
  4. Sink participates in two-phase commit (or accept at-least-once explicitly).
  5. Restart strategy bounded; savepoints for planned changes.
  6. Checkpoint metrics monitored and alerted on.
  7. Failure injection tested in a staging environment.

Exactly-once in Flink is not magic — it is a well-engineered combination of distributed snapshots and transactional sinks, and it holds up in production only when every layer is configured deliberately.

Apache Flink Big data

Opinions expressed by DZone contributors are their own.

Related

  • Stream Processing on the Mainframe With Apache Flink: Genius or a Glitch in the Matrix?
  • Dead Letter Queue Patterns in Apache Flink: Handling Poison Messages Without Stopping Your Stream
  • Superior Stream Processing: Apache Flink's Impact on Data Lakehouse Architecture
  • Should Developers Switch From SQLite to DuckDB?

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook