Apache Flink Event-Time Tutorial: State and Recovery
Follow one Apache Flink 2.3.0 event-time job through watermarks, late orders, checkpoint recovery, and a file sink, with delivery guarantees stated clearly.
This tutorial counts orders by customer in event-time windows and follows one late record through watermarking, allowed lateness, checkpoint recovery, and a file sink. It also compares Flink’s operating model with Kafka Streams and Spark Structured Streaming, including the source and sink conditions behind exactly-once delivery.
Apache Flink Event-Time Tutorial: State and Recovery
Flink 2.3.0 was the latest stable Apache Flink release when checked on 2026-11-04; Apache lists its release date as 2026-06-25 on the official downloads page. This tutorial follows one job that counts orders per customer in 10-minute event-time windows.
Choose a stream-processing model
Start with the workload and the operating model you want to own. These systems can all process event streams, but their programming model and runtime responsibilities differ.
| Option | A good fit when | What to check before choosing |
|---|---|---|
| Apache Flink | A long-running job needs keyed state, event-time windows, and checkpointed recovery. | You can operate a Flink cluster, configure durable checkpoint storage, and validate connectors. Verify both source and sink guarantees. |
| Kafka Streams | The application is Kafka-centered and you want stream processing embedded with the application. | Kafka Streams runs as an application library and scales through Kafka partitions; plan application lifecycle, partitioning, and local state accordingly. See the Kafka Streams architecture guide. |
| Spark Structured Streaming | The pipeline fits Spark’s SQL/DataFrame model and the surrounding Spark data platform. | Micro-batch is the default mode. Spark also documents Real-time Mode with a narrower supported query set, so verify support for the operators you need in the Structured Streaming guide and Real-time Mode reference. |
If portable pipeline code across execution engines matters more than a single runtime’s APIs, also compare the Apache Beam guide. Runner support and behavior still need to be checked for the features the job uses.
Follow one event-time job
Assume an order service sends records with a customer ID and the time the order was placed. The job counts orders for each customer in tumbling 10-minute windows. Event time is the timestamp attached to the order; processing time is when Flink handles the record. A queue delay can make those times differ.
Here is the input sequence. All times are UTC. The arrival time is when the job receives the record, not the order’s event timestamp.
| Order | Event time | Arrival time | Explanation |
|---|---|---|---|
o-101 |
10:02 | 10:02 | First record in the 10:00–10:10 window |
o-102 |
10:09 | 10:10 | Second record in the window |
o-103 |
10:15 | 10:15 | Advances the highest event timestamp seen |
o-104 |
10:08 | 10:20 | Deliberately late: it arrives after the watermark has passed the window end |
The job assigns event timestamps and uses bounded out-of-orderness of two minutes. Once it has seen the 10:15 event, the generated watermark is approximately 10:13, subject to when the periodic watermark is emitted. That watermark says Flink is making progress through event time; it is an estimate based on the configured assumption, not proof that no older record can arrive.
The two-minute bound is an input assumption, not a universal setting. Bounded-out-of-orderness watermarking tracks the greatest event timestamp observed and emits progress behind it by the configured delay. If the data often arrives further out of order, a window may fire before some records arrive. If the delay is made larger, windows wait longer before firing and retain state longer. Choose the bound from observed source disorder and the business tolerance for corrections.
With multiple source partitions or inputs, downstream event-time progress is held by the slowest watermark. A stalled or idle input can therefore keep windows open even when other inputs have moved ahead. Flink’s event-time docs cover idleness and watermark generation; use an idleness signal only when silence from that input really means it has no earlier events pending.
The first three records place o-101 and o-102 in the event-time window [10:00, 10:10). When the watermark passes the window end, Flink fires a count of two. o-104 has event time 10:08, but it arrives while the watermark is around 10:13. It is late because event time is behind the watermark and its window has already fired. Processing time 10:20 does not change which event-time window contains it.
In this example, the window allows five minutes of lateness. Flink retains the window state until the watermark advances past the window end plus that allowance, around 10:15. Time passing on the wall clock does not advance the watermark; later event-time progress must do that. Since the watermark is only around 10:13 when o-104 arrives, Flink accepts it and the event-time trigger can fire an updated count of three. The updated result is a second output for the same customer and window. A downstream consumer must treat it as an update, for example by upserting on (customer_id, window_start).
The job sends records that arrive after the allowed-lateness cutoff to a side output. Those records do not change the main count; the side-output stream can be inspected, stored, or handled by a correction process. Without the side output, Flink drops records that are too late for the window. Flink’s event-time guide and window documentation describe timestamp assignment, watermarks, allowed lateness, and side outputs.
Code fragment: checkpointed DataStream job
The Java fragment below uses the same two-minute watermark lag, ten-minute window, and five-minute allowed-lateness period as the timeline. The source and CountOrdersPerWindow helper are omitted. replayableOrdersSource must be a source that snapshots its position with Flink and can replay from that position after recovery; merely reading from an external system is not enough.
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
// Example interval only; choose it from the recovery objective and state size.
env.enableCheckpointing(60_000L, CheckpointingMode.EXACTLY_ONCE);
// Local path for a one-machine example. Use durable shared storage in a cluster.
env.getCheckpointConfig().setCheckpointStorage("file:///tmp/flink-checkpoints");
WatermarkStrategy<OrderEvent> watermarks = WatermarkStrategy
.<OrderEvent>forBoundedOutOfOrderness(Duration.ofMinutes(2))
.withTimestampAssigner((event, previousTimestamp) -> event.eventTimeMillis());
OutputTag<OrderEvent> tooLateTag = new OutputTag<OrderEvent>("too-late") {};
SingleOutputStreamOperator<WindowCount> counts = env
.fromSource(replayableOrdersSource, watermarks, "orders")
.keyBy(OrderEvent::customerId)
.window(TumblingEventTimeWindows.of(Duration.ofMinutes(10)))
.allowedLateness(Duration.ofMinutes(5))
.sideOutputLateData(tooLateTag)
.process(new CountOrdersPerWindow());
DataStream<String> countRows = counts.map(WindowCount::toJson);
DataStream<String> tooLateRows = counts.getSideOutput(tooLateTag)
.map(OrderEvent::toJson);
FileSink<String> countSink = FileSink
.forRowFormat(new Path("file:///tmp/flink-counts"),
new SimpleStringEncoder<String>("UTF-8"))
.build();
FileSink<String> lateSink = FileSink
.forRowFormat(new Path("file:///tmp/flink-too-late"),
new SimpleStringEncoder<String>("UTF-8"))
.build();
countRows.sinkTo(countSink);
tooLateRows.sinkTo(lateSink);
env.execute("customer-order-window-counts");
The fragment omits the event classes, source construction, and window function. Its local filesystem paths are for a local run; a cluster needs checkpoint and sink storage available to the relevant workers and operators.
The side output contains only events that exceed the window’s allowed-lateness cutoff. The o-104 record in the timeline does not go there because it arrives before the cutoff; it updates the main window result instead. If late records after the cutoff matter to the business, keep the side-output sink and define a separate correction workflow. If they do not matter, the operator can omit that side output and accept that Flink drops those records.
What a checkpoint recovers
A completed checkpoint ties Flink-managed operator state to positions in the input streams. If a TaskManager fails, Flink restores the last completed checkpoint and replays input after the stored positions. For this job, that means the window’s count and the source position move together: replayed records rebuild the same state rather than being added twice to the restored state. The checkpointing documentation explains checkpoint storage and recovery.
For a concrete failure point, let checkpoint C1 complete after the watermark has fired the count of two and before o-104. C1 contains the input position and the window state after the first firing. o-104 then updates the count to three. If a task fails before the next checkpoint completes, Flink restores C1 and replays o-104; the managed count reaches three again from the restored value of two. The FileSink restores its checkpointed file state too, so the uncommitted output from the failed attempt is not published as a second committed result.
When validating this job, inject a task failure between C1 and the next completed checkpoint. Confirm that the restored window reaches three and the finished output files contain one committed copy of each emitted result. This checks both the replayable source and the sink’s checkpoint behavior.
Checkpoints do not make arbitrary external writes transactional. Exactly-once state updates require the source to participate in snapshotting and support replay. End-to-end exactly-once also requires a sink that participates in checkpoints, usually through transactions or idempotent writes. A database call or HTTP request inside a user function is outside Flink’s checkpoint transaction; recovery can repeat that side effect unless the destination handles retries safely.
This example uses Flink’s built-in FileSink. The 2.3.0 filesystem connector documents exactly-once behavior for streaming when checkpointing is enabled: pending output files become finished on successful checkpoints. The result stream can still contain both the first count and its late update, because those are two valid window results. Exactly-once delivery means the sink commits each emitted result once; it does not collapse updates into one final row. See the Flink 2.3.0 FileSystem connector documentation and source and sink guarantees for the conditions.
The file sink keeps output in progress until it can commit it. Downstream readers should consume finished files, which the connector marks after successful checkpoints in streaming mode. That makes this sink a reasonable fit for immutable output files. It is not an upsert store: the first count and the late update are separate records, so any consumer that needs one current value per window must apply the update key itself.
If you replace FileSink with a database or webhook, verify that connector’s documented behavior. Use a transactional sink that commits with checkpoints, or make writes idempotent with a stable key such as customer ID plus window start. Do not infer external delivery guarantees from Flink’s checkpointed state alone.
Summary
Flink fits this example when event-time windows and keyed state are worth operating as a long-running job. Check whether the input can replay from a checkpoint, how late records should change or leave the result stream, and whether the sink can commit safely with checkpoints. Resolve those questions before comparing throughput claims or choosing a framework.
Quick recap checklist
- Assign the timestamp from the order event and choose a watermark delay from observed disorder.
- Decide how long a fired window accepts late updates and where later records go.
- Confirm the source can restore its position and replay records from a completed checkpoint.
- Verify that the sink participates in checkpoints or handles retries idempotently.
Interview checks
Compare its event timestamp with the watermark and its window’s end. The five-minute allowed-lateness period keeps the window available for an update; records arriving after that cutoff go to the side output.
No. The source must snapshot and replay its position, and the sink must participate in checkpointing transactionally or make repeated writes idempotent. A direct external call from a user function is outside the checkpoint transaction.
Watermarks track event-time progress, not elapsed wall-clock time. A stalled or idle input can hold back the downstream watermark, so the allowed-lateness cleanup threshold may not be reached until later event-time progress arrives.
Further reading
- Kafka Streams for Kafka-centered stream processing embedded in an application
- Spark Structured Streaming for Spark’s SQL and DataFrame model
- Apache Beam for a portable pipeline model with runner-specific capability checks
- Flink 2.3.0 stateful stream processing
Category
Related Posts
Apache Spark Structured Streaming: Kafka Pipeline Guide
Build a PySpark 4.3.0 Kafka pipeline, set up checkpoint recovery, and learn why the built-in Kafka sink can still write duplicate records.
Consistent Hashing for Load Balancing
Learn how consistent-hash rings, virtual nodes, and bounded-load policies reduce reassignment, and when sticky sessions still make sense.
Load Balancing Algorithms: Workloads and Benchmarks
Compare round robin, least-connections, and two-choice routing under mixed request durations with a reproducible workload and operational trade-offs.