Core Concepts
Flink (Stream Processing)
Count events as they arrive, handle late records, and recover after a crash.
Flink runs calculations as events arrive and keeps the intermediate results those calculations need. It reads events from a source such as Kafka, applies steps called operators, and sends results to a sink, such as a result table. The counts an operator remembers between events are its state.
Use Flink when a calculation needs to stay current as events arrive and depends on state from earlier events, such as a rolling count or a join between streams. The walkthrough follows four clicks through processing, windowing, and recovery.
From a click to a count
Take a job that reads clicks from Kafka and writes one count per user for each five-minute interval, or window. These fixed intervals are called tumbling windows. The job groups clicks by user_id using keyBy. Each operator can run as several parallel copies called subtasks. Routing the clicks for one user to the same subtask lets it keep that user's counts together.
A click carries the time it happened. Flink calls that event time and uses it to assign the click to a window. Processing time is when the job handles the record. The Kafka offset is the record's position in a partition. It stays the same regardless of when the click happened or when the job handles it.
Decoded Kafka record for the 12:03 click
{
"offset": 151,
"value": {
"user_id": "u17",
"event_time": "2026-04-17T12:03:00Z"
}
}The job reads four clicks for user u17 in offset order. All times are UTC on the same day.
| Kafka offset | Event time | What the job does |
|---|---|---|
| 149 | 12:01 | Starts the 12:00 to 12:05 count at 1. |
| 150 | 12:04 | Increases that count to 2. |
| 151 | 12:03 | Processes the click at 12:06 on the wall clock. Increases the same count to 3. |
| 152 | 12:10 | Starts the 12:10 to 12:15 count at 1. |
A watermark tells operators how far event time has progressed. This job lets the source watermark trail the newest event time seen by about two minutes. When offset 151 arrives, the newest time seen is still 12:04, so the watermark is at most about 12:02 and the earlier window is open. After offset 152 arrives and the watermark reaches about 12:08, the earlier window emits its result.
user_id window_start window_end count
u17 12:00 12:05 3Handle late or invalid clicks
Say a click for 12:02 arrives after its window has emitted. The job's allowed lateness is zero, so it has already discarded that window's working count. This job sends the click to late-clicks, a side output configured for those records.
Flink drops those records by default. With positive allowed lateness, it can keep the window after its first emission and produce an updated count when a late click arrives within the configured grace period. Flink windows, triggers, and allowed lateness
A malformed timestamp needs a separate route. The job can validate it before assigning event time and send the record to invalid-clicks for inspection. That route is application logic.
Follow offset 151 through the processing path below. It raises the count from 2 to 3 before the window's event-time timer fires. The timer waits until the watermark advances far enough to emit the count. The two side paths show where malformed and late clicks go.
Choose a window
Change the window rule and the same clicks answer different questions. The start of each fixed window is inclusive and the end is exclusive.
| Window rule | How the same clicks are counted |
|---|---|
| Tumbling, five minutes | The 12:03 click counts once, in 12:00 to 12:05. That window emits 3. |
| Sliding, five minutes with a new window every two minutes | The 12:03 click counts in both 12:00 to 12:05 and 12:02 to 12:07. Those windows emit 3 and 2, respectively. |
| Session, five-minute inactivity gap | The 12:01, 12:03, and 12:04 clicks belong to one active period. The 12:10 click starts another. The first session stays open at watermark 12:08 and can emit once it reaches the end of the gap around 12:09. |
Each panel plots the same four clicks by event time. Follow the highlighted 12:03 click to see which windows include it. In the session panel, look at the gap between the last two clicks to see why they land in separate sessions.
Choose the clock and when to emit
If the same five-minute windows used processing time, the 12:03 click would count in the 12:05 to 12:10 window because the job handled it at 12:06.
The window rule decides which counts a click can change. A trigger decides when to emit those counts. The default event-time trigger fires when the watermark reaches the last timestamp in the window, just before its exclusive end. A custom trigger can emit after three clicks in this user's window and fire again when the watermark closes the window. Flink window assigners and triggers
Recover after a crash
What the checkpoint saves
The job configuration supplies the grouping key, window rule and its size, slide or gap, the watermark policy, and allowed lateness. The values the job accumulates while it runs are its working state. After offset 150, that includes the count of 2 for u17 and an event-time timer that will fire when the watermark reaches the end of the window.
For recovery, the saved count and the next Kafka offset must describe the same point in the stream. With checkpointing enabled, Flink sends a marker called a checkpoint barrier into each source stream. The barriers coordinate what the job saves across subtasks, using a method inspired by the Chandy-Lamport algorithm for distributed snapshots. The snapshot is a checkpoint. Flink state and checkpoints
Saved values in checkpoint C1
Next Kafka offset: 151
Window: u17, 12:00 to 12:05
Count: 2
Event-time timer: pendingRestoring count 2 and starting at offset 152 would skip the 12:03 click. Timer recovery
What replay does to the result
The job processes offsets 151 and 152. It emits the count of 3, an append sink commits the row, and the worker crashes before the next checkpoint completes.
On restart, Flink restores count 2, the pending timer, and the Kafka read position from C1. Follow offsets 151 and 152 down the timeline to see why the job emits count 3 again.
Rows in the append table after replay
user_id window_start window_end count
u17 12:00 12:05 3
u17 12:00 12:05 3| Sink behavior | What the reader sees |
|---|---|
| Append a new row | The first committed row survives the crash. Replay appends an identical row, so the reader sees two rows. |
Upsert by (user_id, window_start) | Replay writes the same count to the same row. For readers of that table, this is an idempotent write. |
| Stage output in a checkpoint-coordinated transaction | The failed attempt's output stays uncommitted. The sink commits the replayed result after a successful checkpoint, when readers of committed data can see it. |
Flink can process a record more than once and still recover its own state as if the record affected it once. An end-to-end exactly-once effect also needs a replayable source and a sink that handles replay. A table upsert covers the state of that row. Check separately whether the write triggers another effect, such as sending a notification. Flink exactly-once guarantees · Kafka sink delivery guarantees
Running Flink in production
Quiet inputs and slow consumers
With several inputs, the lowest active input watermark controls progress. A quiet input can hold back windows even when the other inputs are busy. Configure Flink to mark that input idle after a period without records so it drops out of the minimum. Flink watermark strategies
When an operator reads more slowly than the previous step sends records, the buffers in front of it fill. Eventually the sender has to slow down too. Flink calls that slowdown backpressure. A slow sink can cause it to spread upstream all the way to Kafka.
Checkpoints under backpressure
Suppose a checkpoint barrier arrives first on the faster input of a two-input operator. In an aligned checkpoint, the operator pauses that input until the matching barrier arrives on the slow input. It then takes the snapshot. Records before either barrier have contributed to the state, and records after the barriers wait for processing to resume.
In an unaligned checkpoint, the barriers can pass buffered records. The checkpoint saves those in-flight records along with the operator state so they are available on recovery. This can shorten the checkpoint under backpressure. It can also make the snapshot larger and add work at restore time.
Check start delay, the time until the first barrier reaches a subtask, and alignment time, the time between the first and last barrier there. If the first barrier reaches it quickly and alignment takes much longer, look at the slower inputs. If the first barrier is also late, trace the delay upstream. Checkpoint metrics
If checkpoints time out, the latest completed one may be older and recovery may have more data to replay. Unaligned checkpoints can help the checkpoint finish while that backlog exists. The slow operator may still need more capacity or a faster dependency. Checkpointing under backpressure
Where Flink stores state
Flink keeps a subtask's working state in a state backend. HashMapStateBackend keeps Java objects in the worker's heap, the part of memory used for those objects.
EmbeddedRocksDBStateBackend stores encoded state in a local disk-backed database. It can handle state larger than the available heap and supports incremental checkpoints, which save changes since the last completed checkpoint. Access has encoding and storage overhead. Flink state backends
Checkpoint storage holds durable snapshots. It can be a distributed filesystem or an object store such as S3. During a checkpoint, each subtask saves a snapshot of its portion of state. To change the number of subtasks, Flink moves key groups, bundles of keys assigned together. The subtask that receives a group takes over the state for the users in it. Flink keyed state
How to use in a system design
A plain Kafka consumer can validate and forward each click independently. If counts can wait for a scheduled query over stored clicks, a batch job may suffice. For live five-minute results, a consumer implementation would need to define when windows emit, keep counts across records, and pair saved counts with saved offsets.
Flink provides those mechanics and runs them on a separate processing runtime. Kafka Streams is another option for a Kafka-centered application that can run the processing library inside its own deployment. Kafka Streams introduction
In an interview, explain what happens to the 12:03 click as the watermark advances and to its result when the job restarts. Name the state kept per user, where checkpoints live, and which output effects the sink can safely repeat. If the sink is slow, use the checkpoint metrics and operator throughput to decide whether the job needs more sink capacity or a change to how it checkpoints.
See also
- Backpressure and Load Shedding - limits work when a downstream consumer falls behind.
- Batch vs Stream Processing - introduces event time, watermarks, and stream-processing guarantees.
- Idempotency - prevents replayed output from creating a second result.
- Kafka - provides a replayable source for many Flink jobs.
- Object Storage (S3) - can hold checkpoints outside the worker that created them.
- B-Trees vs LSM-Trees - explains the storage structure used by RocksDB.
- Change Data Capture - a CDC pipeline into Flink is a common shape.
Used in
- No current backend design article uses Flink directly.
Done reading? Mark it so it sticks in your dashboard.