Fault Tolerance and Checkpointing in Flink on AWS
Flink fault tolerance is a recovery protocol, not a backup checkbox. A completed checkpoint identifies a consistent input position and a copy of operator state. After a task manager or job manager fails, Flink restores that boundary and replays source records. The result is correct only when every stateful operator, source, and externally visible sink participates in the protocol.
This article uses an Amazon MSK source, an S3 object as durable checkpoint storage, and a transactional Kafka sink. The same principles apply to filesystem, database, and Kinesis connectors, but connector guarantees must be checked individually.
Checkpoint modes and timing
Choose exactly once when failed in-flight work must not become visible twice. Choose at least once when the checkpoint protocol may release output before a barrier commits and downstream consumers can deduplicate. Exactly-once alignment can add latency and buffer pressure; unaligned checkpoints avoid barrier alignment through in-flight channels but write more data and require connector support.
A practical first configuration is:
execution.checkpointing.mode: EXACTLY_ONCE
execution.checkpointing.interval: 60 s
execution.checkpointing.min-pause: 30 s
execution.checkpointing.timeout: 5 min
execution.checkpointing.unaligned.enabled: true
execution.checkpointing.max-concurrent-checkpoints: 1
execution.checkpointing.tolerable-failed-checkpoints: 3
execution.checkpointing.externalized-checkpoint-retention: RETAIN_ON_CANCELLATION
The interval is a recovery-lag decision. A 60-second interval bounds typical source replay to roughly 60 seconds, but a large backpressured job can have a longer effective replay if checkpoints fail or take too long. Shorter intervals reduce replay but increase object storage, serialization, and network cost.
min-pause measures from the completion of one checkpoint to the start of the next. This prevents a checkpoint-heavy job from spending every cycle taking snapshots. Keep maximum concurrent checkpoints at one unless testing proves that overlap helps.
For consistent low-latency recovery, a good initial target is:
- p99 completed checkpoint duration below 20 seconds;
- alignment or in-flight time below 5 seconds in a normal window;
- no more than one failed checkpoint in any rolling 15-minute period;
- state growth below 10% per day unless driven by measured key cardinality.
Durable state on S3
Use a configured state backend and a bucket owned by the same operational environment. With a RocksDB state backend, active state can spill to local disk and snapshots upload to S3. With the heap backend, state is in task-manager memory and each snapshot copies that state. RocksDB supports larger state but adds serialization and compaction work.
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(60_000L, CheckpointingMode.EXACTLY_ONCE);
env.setStateBackend(new EmbeddedRocksDBStateBackend(true));
env.getCheckpointConfig().setCheckpointStorage(
"s3://company-flink-state/orders-app/checkpoints");
env.getCheckpointConfig().enableExternalizedCheckpoints(
ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
The Flink deployment needs s3:GetObject, s3:PutObject, s3:DeleteObject, and list access to the narrow prefix. The S3 bucket should:
- enable default encryption and block public access;
- have versioning or a retention policy appropriate to recovery audits;
- expire abandoned incremental state only after its checkpoint files are no longer referenced;
- live in the same AWS Region as the Flink job to reduce latency and transfer cost;
- have CloudTrail data-event logging when an audit trail is required.
Incremental RocksDB checkpoints in S3 avoid copying unchanged files, but that does not make object lifetime simple. Never delete shared incremental files based on a listing age alone. Let Flink remove state through managed lifecycle operations, then expire only known abandoned prefixes.
Restart policy
A restart policy determines whether the job survives infrastructure disruption:
restart-strategy: exponential-delay
restart-strategy.exponential-delay.initial-backoff: 5 s
restart-strategy.exponential-delay.max-backoff: 2 min
restart-strategy.exponential-delay.backoff-multiplier: 1.5
restart-strategy.exponential-delay.reset-backoff-threshold: 10 min
Fixed-delay retries are predictable but can retry too aggressively during a regional dependency outage. Exponential delay reduces load, while the reset threshold restores fast recovery after a healthy period. Alert on repeated restarts; unlimited retries can hide a bad deployment and continuously consume source records and cloud capacity.
Choose availability versus fail-fast behavior explicitly:
region failover: restore job and checkpoint in the replacement Region
local task failure: retry with restore from latest complete checkpoint
configuration or schema crash: cap attempts, alert, do not loop forever
A regional design also needs checkpoint-state access in the recovery Region, replicated connector endpoints, and enough headroom to catch up. Copying an S3 checkpoint with replication_time_control is not itself proof that a Flink restore is safe; run restore drills.
Savepoints are operational recovery points
A checkpoint is managed for automatic recovery. A savepoint is an intentionally triggered state image used for upgrades, rescaling, migration, or a known rollback point.
Trigger a savepoint with a job stop:
flink stop --savepointPath s3://company-flink-state/orders-app/savepoints \
"$JOB_ID"
Restore the new version explicitly:
flink run -s \
s3://company-flink-state/orders-app/savepoints/savepoint-123 \
target/orders-v2.jar
Before changing operator UIDs, verify compatibility. Stable UIDs connect new code to restored operator state:
DataStream<Order> orders = env
.fromSource(source, watermarkStrategy, "orders-source")
.uid("orders-kafka-source");
orders
.keyBy(Order::customerId)
.process(new CustomerOrderProcessor())
.uid("customer-order-state-v1")
.name("Customer order state");
Adding a stateless map is usually straightforward. Renaming a UID, changing a keyed state type, or reordering key identity is not. Use Flink state migration mechanisms where supported, and create a full savepoint before deployment.
Exactly-once sinks
A source and state checkpoint alone does not guarantee exactly once at an external sink. Flink can commit a Kafka transaction only after the checkpoint completes. Configure transactional IDs uniquely across jobs and verify that output consumers use isolation level read_committed:
transaction.timeout.ms=900000
isolation.level=read_committed
enable.idempotence=true
Other sinks must support transactions, idempotent writes, or an atomic commit protocol. With an object store, for example, the common safe design writes part files temporarily and publishes or commits only with a checkpoint. With a normal JDBC insert, retry after restore may create duplicates unless the database enforces a unique key.
Exactly-once is end-to-end only across the complete set of participating boundaries. For an HTTP API that acknowledges an action and later loses the response, Flink cannot retroactively know whether the side effect happened.
Failure and restore behavior
Suppose checkpoint 407 completes with Kafka offset 90,000 and checkpoint 408 is in flight. A task dies:
- Flink cancels or fails the affected execution attempt.
- The current graph restores state and task keys from checkpoint 407.
- Kafka seeks to offset 90,001, not the latest consumed position.
- Records consumed in the incomplete attempt are processed again.
- Operators reconstruct deterministic state.
- Sink transactions that checkpoint 407 did not commit remain invisible or are aborted.
That replay is why nondeterministic clocks, random values, and remote lookups need care. Use event timestamps, deterministic IDs, and an explicit side-input snapshot where the result must be reproducible.
Failure injection exercise
Run failure injection in a non-production environment first, then as a scheduled game day:
# Example controls; use the orchestration API for the selected runtime.
kill -TERM "$TASK_MANAGER_PID"
aws s3api get-object \
--bucket company-flink-state \
--key orders-app/checkpoints/latest/_metadata \
checkpoint-metadata
# Deploy a bad serializer once to verify fail-fast and capped restarts.
flink list --running
flink list --scheduled
Measure these values during the exercise:
| Metric | Practical target |
|---|---|
| Time to detect failure | below 30 seconds |
| Time to restore state | below 3 minutes |
| Source replay volume | no more than one checkpoint interval plus expected lag |
| Visible duplicate results | zero for transactional sink consumers |
| Checkpoint success after recovery | two consecutive successes |
| Keyed output count | same as baseline after full replay reconciliation |
Also inject S3 permission denial and DNS failure. The first should fail checkpoints with a specific authorization signal; the second tests retry policy and catches. A restore that only works when every dependency is healthy is not a credible recovery design.
Debugging failures
Use the checkpoint UI or metrics to distinguish:
- stuck tasks: one operator never acknowledges the barrier;
- backpressure: buffers consume the checkpoint budget;
- state backend pressure: RocksDB IO or compaction is saturated;
- S3 throttling: request errors or long PUT latency;
- external commit delay: the sink cannot complete the two-phase commit;
- source skew: a late partition holds the watermark or barrier.
Correlate Flink job attempt IDs, checkpoint IDs, S3 request IDs, and deploy version IDs. Do not treat a restart count alone as root cause.
Production acceptance checklist
Before release:
- Trigger, find, and restore a savepoint in the target environment.
- Terminate a task manager during checkpoint and replay.
- Validate output deduplication at the consumer.
- Prove the S3 IAM boundary using a denied test.
- Load test 2x peak for one checkpoint-retention period.
- Alert on failed checkpoints, restore duration, state size, restart loops, and source lag.
- Document the latest usable checkpoint and deployment rollback command.
Fault tolerance is successful when the service produces a defined result after a defined failure, within a measured recovery objective. Checkpoints provide the mechanism; runbooks and failure drills make that mechanism operational.