Ask "how many payments did we see between 10:00 and 10:01?" and a streaming system has to decide what "between 10:00 and 10:01" means. The time each payment happened? Or the time it reached the processor? Those differ, sometimes by milliseconds, sometimes by hours when a mobile app was offline or a partition was lagging. Flink makes the difference explicit, and getting it right is the first step to results you can trust.
Two clocks
- Processing time is the clock of the machine running the operator. It is simple and fast, but results depend on when events happened to arrive: replay yesterday's data and you get different answers.
- Event time is the timestamp carried in each event: when the payment was made, when the sensor took its reading. Results depend only on the data, so they are the same in real time and in a replay.
Most business questions are event-time questions. The catch is that events don't arrive in event-time order, so Flink needs a way to decide when it has seen "enough" of a time period to produce a result.
Watermarks: "nothing older than this is coming"
A watermark is a marker that flows through the stream carrying a timestamp t. It is Flink's assertion that no more events with a timestamp earlier than t are expected. When the watermark passes the end of a window, the window fires and its result is emitted.
The most common way to generate watermarks is to assume events are out of order by at most a fixed bound:
WatermarkStrategy
.<Reading>forBoundedOutOfOrderness(Duration.ofSeconds(10))
.withTimestampAssigner((r, ts) -> r.eventTimeMillis())
.withIdleness(Duration.ofMinutes(1)); // a silent partition must not hold everything backThe watermark trails the largest timestamp seen by ten seconds. withIdleness stops an idle input from holding the watermark back.
The bound is a direct trade-off: a larger bound waits longer before emitting results (more latency) and drops fewer late events (more completeness). Choose it from data: measure how late events actually arrive, per source, and pick a bound that covers the bulk of them.
Watermarks across parallel inputs
An operator with several inputs (several Kafka partitions, or several upstream subtasks) uses the minimum of their
watermarks. That is correct, because the slowest input decides what is complete, and it has a famous side effect: one partition that receives
no data holds back the watermark for the whole job, and windows never fire. withIdleness tells Flink to ignore an input that
has been silent for a while. Kafka sources given the watermark strategy directly (in env.fromSource) generate watermarks per partition, which keeps out-of-order data across partitions
from being treated as late.
Late events: three choices
Whatever the bound, some events will arrive after the watermark has passed their window. Flink offers three ways to handle them, and they combine:
- Drop them (the default for windows). Fine when a small loss doesn't matter, such as dashboards.
- Allowed lateness: keep the window's state for a while after it fires, and emit an updated result when a straggler arrives. Downstream must accept updates (an upsert sink, or a consumer that handles corrections).
- A side output: route anything later still to a separate stream, to be stored, counted or reconciled in batch.
stream
.keyBy(Reading::sensorId)
.window(TumblingEventTimeWindows.of(Duration.ofMinutes(1)))
.allowedLateness(Duration.ofMinutes(2)) // update the result for stragglers
.sideOutputLateData(lateTag) // and keep anything later still
.aggregate(new AverageReading());
Event time beyond windows
The same machinery drives more than windows. Event-time timers in a KeyedProcessFunction fire when the watermark
passes them, which is how you implement "alert if no heartbeat for five minutes" or "close the session after thirty minutes of inactivity"
correctly in a replay. Interval joins and temporal joins in Flink SQL rely on watermarks to know when state can be cleaned up, which keeps the
job's state from growing without bound.
A worked example: choosing the bound from data
Before choosing a bound, measure lateness. For a sample of real traffic, record for each event the difference between the time it reached the job and its own timestamp, and look at the distribution per source. Suppose, as an illustration, that almost all events from a web source arrive within a few seconds, but a mobile source has a long tail of events that arrive minutes or hours later from phones that were offline. One bound cannot serve both well: a few seconds drops much of the mobile tail; an hour delays every web result by an hour. The usual answer is a bound that covers the bulk of events, with the long tail handled by allowed lateness or a side output, or separate pipelines per source.
Watermark alignment
When one source is far ahead of another, for example during a catch-up after an outage, the fast source keeps producing events that must be buffered in state until the slow source's watermark catches up. State and checkpoints grow. Flink's watermark alignment can pause sources that are too far ahead of the group's slowest watermark, which keeps state bounded during replays and backfills.
In Flink SQL
The same ideas appear in table definitions: a WATERMARK FOR clause names the event-time column and the bound, for example
WATERMARK FOR ts AS ts - INTERVAL '10' SECOND. Window functions, interval joins and the clean-up of state in SQL jobs all depend on
it, so a missing or wrong watermark is one of the first things to check when a SQL job's state grows.
Choosing settings: a short checklist
- Use event time for anything a business person will read; keep processing time for operational metrics.
- Measure lateness per source before choosing the bound.
- Set idleness for any source with partitions that can go quiet.
- Decide, per output, whether late data is dropped, corrected or side-lined, and count it either way.
- Test with a replay of real, out-of-order data, not only with a generator that produces events in order.
The worked examples show these choices in context: sensor anomaly detection, where devices go offline and send data late, and card fraud signals, where latency matters most.
Questions we are often asked
What if our events have no timestamp?
Then the best available is the time the event was written to Kafka, which the Kafka source can use. It is still more stable than processing time in a replay, but it reflects when the producer sent the event, not when it happened. Adding a real event timestamp at the producer is worth the effort.
Why does my window never fire?
Almost always a watermark that doesn't advance: an idle partition without idleness configured, timestamps in the wrong unit (seconds read as milliseconds), or a source that never received a watermark strategy. The Flink web UI shows each operator's current watermark, which is the quickest place to look.