Stream Processing: Windows, Watermarks, State and Exactly-Once
Product wants a “trending now” rail: the top 10 hashtags in the last minute, refreshed every minute. The first version is a cron job that runs GROUP BY hashtag over the last 60 seconds of the posts table. At 500 posts per second it works. At 6,000 posts per second, with a 3x evening peak, the query takes 40 seconds to scan a minute of data, the primary’s CPU sits at 85%, and the rail is always a minute and a half stale.
Worse, the numbers are wrong. Phones on the subway upload posts in bursts when they reconnect, so a post written at 18:00:50 arrives at 18:02:10 and lands in the wrong minute.
You need a system that processes each event as it arrives, keeps running counts, assigns events to the minute they happened in, decides when a minute is complete, and survives a machine dying without double counting. That is stream processing.
What it is
Stream processing is continuous computation over an unbounded sequence of events. Instead of running a query over data at rest (batch), you install the query once and every new event flows through it, updating results incrementally.
Batch and streaming are not opposites. A batch job is a stream processor run over a bounded slice of history. The real differences are:
| Batch | Stream | |
|---|---|---|
| Input | Bounded (a day, a table) | Unbounded (events keep arriving) |
| Latency | Minutes to hours | Milliseconds to seconds |
| Completeness | Known: the input is all there | Must be decided: when is a minute done? |
| Failure recovery | Rerun the job | Restore state and resume from a checkpoint |
| Typical uses | Reports, model training, backfills | Alerting, fraud, live dashboards, feature pipelines |
The completeness row is the heart of it: a stream processor has to guess when the input is complete, and recover when the guess was wrong. Batch analytics and warehouses are covered in OLTP vs OLAP. The streams themselves usually come from a log such as Kafka, often fed by CDC and outboxes.
How it works
The dataflow graph
A streaming job is a graph of operators. Sources read from partitions, operators transform or aggregate, sinks write results. Each operator runs as many parallel instances, and records are routed between them by key, the same way a Kafka topic partitions by key.
flowchart LR
S["Source<br/>posts topic, 48 partitions"] --> M["Stateless<br/>extract hashtags"]
M -->|"keyBy hashtag"| A["Stateful<br/>count per hashtag<br/>per 1 min window"]
A -->|"keyBy window"| T["Stateful<br/>top 10 per window"]
T --> K["Sink<br/>trending topic"]
A -.->|"state"| ST[("State store<br/>RocksDB / ForSt")]
ST -.->|"checkpoint"| OS[("Object storage")]
style A fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style T fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style ST fill:#FAEEDA,stroke:#854F0B,color:#633806
style OS fill:#F1EFE8,stroke:#888780,color:#444441
Stateless operators (map, filter, flatMap, parsing, routing) look at one record at a time. They scale trivially and recover trivially: restart and keep going.
Stateful operators (counts, sums, distinct, joins, deduplication, pattern detection) remember something across records. That memory is the hard part: it has to be partitioned by key, kept somewhere fast, survive failures, and be redistributed when you scale.
Event time vs processing time
Every event has two timestamps that matter:
- Event time: when it happened, stamped by the producer (the phone, the sensor, the database commit).
- Processing time: when the stream processor sees it.
The gap between them, called skew, is never zero and is not constant. A healthy pipeline may run 200 ms behind; a phone that was offline for 20 minutes produces events 20 minutes late; a consumer restart makes everything a few minutes late at once. Windowing by processing time is simple but gives answers that change if you replay the same data, which breaks backfills and makes results depend on how busy the cluster was. Windowing by event time gives reproducible answers but forces you to deal with out-of-order arrival. Client clocks can also be wrong; the general problem of ordering by timestamps is covered in time, clocks and ordering.
Windows
Aggregating an infinite stream needs boundaries. Windows assign each event to one or more finite buckets.
| Window | Definition | Events per window | Example |
|---|---|---|---|
| Tumbling | Fixed size, no overlap | Each event in exactly 1 | Hashtag counts per minute |
| Sliding (hopping) | Fixed size, advances by a smaller step | Each event in size / step windows | Last 5 minutes, updated every minute |
| Session | Per key, closes after a gap of inactivity | Variable | User sessions with a 30 minute gap |
| Global | One window per key, custom trigger | All | Running totals, dedup |
Naming varies: Flink calls the overlapping kind “sliding”, Kafka Streams calls it “hopping” and reserves “sliding” for windows defined by the distance between two records. The cost is the same idea: a 5 minute window sliding every 1 minute puts each event into 5 windows, so state and work are 5x a tumbling window. Session windows merge as events arrive: two sessions for the same user that come within the gap of each other become one.
Watermarks and late data
If you window by event time, when do you emit the result for 18:00 to 18:01? Wait too short and late events are missed; wait forever and you never emit.
A watermark is the processor’s declaration “I believe I have now seen all events with event time up to T”. When the watermark passes the end of a window, the window fires. The most common strategy is bounded out-of-orderness: watermark = highest event time seen minus a fixed delay, say 10 seconds. Sources emit watermarks per partition and an operator’s watermark is the minimum across its inputs, so one slow or idle partition holds back the whole job (Flink lets you mark idle sources so they stop doing that).
Events that arrive after the watermark has passed their window are late. You have three choices, and good systems let you combine them:
- Drop them (and count how many you dropped, so you know the watermark delay is wrong).
- Allowed lateness: keep the window’s state for an extra period and emit an updated result when a late event arrives. Downstream must handle updates, for example by upserting by window key.
- Side output: send late events to a separate stream for a correction job or a batch reconciliation.
Kafka Streams does not use watermarks. It tracks stream time (the highest timestamp seen per task) and a per-window grace period: records later than window end plus grace are dropped. The idea is the same, the vocabulary differs.
State stores and checkpoints
Stateful operators keep state locally, partitioned by key, so a lookup is a memory or local SSD read rather than a network call. Flink offers a heap state backend and an embedded RocksDB backend; Flink 2.0 (released in 2025) added disaggregated state through the ForSt backend, which keeps the primary copy in remote object storage and uses local disk as a cache, so large state no longer has to fit on task manager disks and rescaling moves less data. Kafka Streams keeps state in local RocksDB stores, each backed by a compacted changelog topic in Kafka; a restarted instance rebuilds the store by replaying the changelog, and standby replicas keep warm copies to shorten that.
Local state is only useful if it survives failure consistently with the input position. Flink does this with checkpoints based on the Chandy-Lamport snapshot algorithm. The intuition: you want a photograph of the whole distributed job as if it stopped at one instant, without stopping it.
sequenceDiagram participant JM as Coordinator participant Src as Source participant Op as Count operator participant Snk as Sink JM->>Src: start checkpoint 42 Src->>Src: record Kafka offsets Src->>Op: records ... barrier 42 ... records Op->>Op: barrier from all inputs, snapshot state Op->>Snk: barrier 42 Snk->>Snk: pre-commit transaction Snk-->>JM: ack 42 JM->>Snk: checkpoint 42 complete, commit
The coordinator injects a barrier into each source. A source records its offsets and forwards the barrier inline with the data. Every record before the barrier belongs to “before checkpoint 42”, every record after belongs to “after”. When an operator has received the barrier on all its inputs (alignment), it snapshots its state asynchronously and forwards the barrier. When every sink has acknowledged, the checkpoint is complete: a set of source offsets plus every operator’s state at exactly the cut those offsets define. On failure Flink restores all state from the last complete checkpoint and rewinds the sources to its offsets. Alignment can stall under backpressure, so Flink also offers unaligned checkpoints, which store in-flight buffers in the snapshot instead of waiting.
Exactly-once, precisely
Restoring a checkpoint and replaying input means operators reprocess some records. Internal state is still exactly-once, because the replayed records are applied to state from before they were first seen. Results leaving the job are another matter: a sink that already wrote them will write them again. This is the general rule from delivery semantics: exactly-once is about effects, and it needs cooperation from the sink.
- Flink gets end-to-end exactly-once with two-phase commit sinks. The Kafka sink opens a Kafka transaction per checkpoint, writes into it, pre-commits on the barrier and commits only when the checkpoint completes. Downstream consumers must read with
isolation.level=read_committed, and output becomes visible once per checkpoint interval, so a 30 second checkpoint interval means up to 30 seconds of extra latency. Idempotent sinks (upsert by key into a database) are the other route. - Kafka Streams with
processing.guarantee=exactly_once_v2writes output records, changelog updates and the consumed offsets in a single Kafka transaction. Because input, state and output all live in Kafka, the whole read-process-write step is atomic. It covers Kafka to Kafka only; a side effect such as calling an HTTP API is outside the transaction. - Spark Structured Streaming tracks offsets and state per micro-batch in a checkpoint directory and gives exactly-once with replayable sources and idempotent or transactional sinks.
Joins
Stream-stream joins match events from two streams, such as ad impressions and clicks. Because both sides are unbounded, the join must be bounded in time: “a click within 30 minutes of its impression”. The operator buffers both sides for the window, so state equals the event rate times the window length on each side.
Stream-table joins enrich each event with the current value of a table, such as adding the user’s country to each post. The table is itself a stream of changes (a compacted topic or a CDC feed) materialised into local state; Kafka Streams calls this a KStream-KTable join. Only the table side is stored. The subtle choice is whether to join against the table as it is now or as it was at the event’s time; Flink SQL’s temporal join (FOR SYSTEM_TIME AS OF) gives the latter, which backfills need.
Backpressure
When a sink or operator is slower than its input, something has to give. In Flink, operators exchange data through bounded network buffers with credit-based flow control: a slow operator stops granting credit, upstream buffers fill, and the slowdown propagates back to the sources, which simply read Kafka more slowly. Nothing is dropped and memory stays bounded. Because the source is a durable log, “reading more slowly” shows up as consumer lag, which is the number to alert on.
Lag behaves like any queue: as an operator’s utilisation approaches 100%, the time an event waits grows non-linearly. Push the slider toward 90% and 99% to see why a job that runs “fine” at 85% CPU falls minutes behind after a 15% traffic bump.
Fixes, in order: remove the hot spot (skewed keys are the usual cause), scale the slow operator, make the sink batch or write asynchronously, and only then shed load. General patterns live in bulkheads, load shedding and backpressure, covered later in the course.
Worked example: per-minute trending hashtags
If exact counts are not required, a Count-Min sketch per window bounds memory regardless of the number of distinct hashtags; see Bloom filters, HyperLogLog and friends.
Where it breaks
Idle partitions stall the watermark. One Kafka partition with no traffic holds the job’s watermark at the last event it saw, and no window ever fires. Configure idleness detection.
Watermark delay set by guesswork. Too short drops real data; too long adds latency to every result. Measure the skew distribution (event time vs arrival time) and pick a delay around its p99, then route the rest to a side output.
Unbounded state. A dedup operator or a join without a time bound grows forever. Set state TTLs and window every stateful join.
Changing the job breaks the snapshot. Renaming an operator or changing a state type can make the old checkpoint unreadable. Give operators stable ids.
Too few source partitions. The first stage cannot run more parallel instances than the topic has partitions, as discussed in Kafka internals.
Real-world systems
- Apache Flink 2.x: the general-purpose stateful engine. DataStream API and Flink SQL, event-time windows and watermarks, aligned and unaligned checkpoints, RocksDB and the disaggregated ForSt state backend. Flink 2.2 shipped in December 2025. Managed offerings include Amazon Managed Service for Apache Flink and Confluent Cloud for Apache Flink.
- Kafka Streams: a library, not a cluster, so it runs inside your service. Kafka in, Kafka out, RocksDB state with changelog topics,
exactly_once_v2. Kafka 4.2 made the new broker-side Streams rebalance protocol (KIP-1071) generally available. - Spark Structured Streaming: micro-batch on the Spark engine, strong for teams already on Spark and lakehouse tables. Spark 4.1 added a real-time mode for low-latency stateless queries.
- Streaming databases: RisingWave and Materialize let you define incrementally maintained materialised views in Postgres-compatible SQL over Kafka or CDC sources, and query them like tables. They trade the flexibility of a DataStream API for far less code.
How to apply it
Pick the engine from the shape of the problem:
| Need | Good default |
|---|---|
| Kafka in and out, logic lives in a service, moderate state | Kafka Streams |
| Large state, event-time correctness, many sources and sinks | Flink |
| Already on Spark and a lakehouse, seconds of latency is fine | Spark Structured Streaming |
| Mostly SQL aggregations and joins served as live tables | RisingWave or Materialize |
| Simple per-event transforms | A plain consumer, no framework |
Checklist for any streaming job:
- Decide event time or processing time explicitly, and where the event timestamp comes from.
- Choose a watermark delay from measured skew; decide what happens to late data and count it.
- Bound every piece of state with a window or TTL.
- Key by something with even distribution; plan for hot keys.
- Use a transactional or idempotent sink if results must not duplicate.
- Alert on consumer lag, checkpoint duration and failures, and late-record counts.
Interview questions
Q1: What is a watermark, and what happens to an event that arrives after it?
A watermark is a monotonically increasing assertion that the processor has seen all events up to some event time T, typically the maximum event time seen minus a fixed out-of-orderness bound. When it passes a window’s end, the window fires. An event with event time below the watermark is late. Depending on configuration it is dropped (and counted), applied within an allowed lateness period that re-emits an updated result, or routed to a side output for separate handling. Kafka Streams expresses the same idea as stream time plus a per-window grace period.
Q2: How does Flink recover from a task failure without double counting?
Flink periodically takes a consistent checkpoint using barriers (Chandy-Lamport style). Each source records its offsets and sends a barrier downstream; each operator snapshots its state once barriers from all inputs arrive. A completed checkpoint is a consistent cut of offsets plus state. On failure Flink restores every operator’s state from the last checkpoint and rewinds sources to the recorded offsets, so replayed records are applied to state that has not seen them. Output is exactly-once only if sinks are transactional (two-phase commit tied to checkpoints) or idempotent.
Q3: You join a stream of orders with a table of currency rates. A backfill of last month’s orders gives different totals than the live run did. Why?
The join probably used the current rate rather than the rate valid at each order’s event time. Live, “current” was close to event time; in the backfill, every order picks up today’s rate. Use a temporal (versioned) join that looks up the table version as of the event’s timestamp, such as Flink SQL’s FOR SYSTEM_TIME AS OF, and keep the rate history rather than only the latest value.
✅ Key takeaways
- Streaming is incremental computation over unbounded input; the core problem is deciding when results are complete.
- Window by event time for reproducible results, use watermarks to decide when to fire, and have an explicit policy for late data.
- Stateful operators keep partitioned local state, and checkpoints (a barrier-based consistent cut) let the job restore state and rewind sources together.
- Exactly-once covers internal state; end-to-end needs transactional or idempotent sinks. Kafka Streams achieves it for Kafka-to-Kafka with one transaction per step.
- Backpressure shows up as consumer lag; hot keys are the usual cause, and two-phase aggregation is the usual fix.
🧠 Check your understanding
0 / 4-
1A 10 minute window slides every 1 minute. Compared with a 10 minute tumbling window, roughly how much window state and update work does it need?
Each event falls in size / slide = 10 overlapping windows. Engines can share some work with panes, but the naive cost is 10x. Option A is tempting because the window length is the same, but overlap multiplies membership.
-
2Your Flink job's windows stopped firing, yet most partitions are receiving traffic. What is the most likely cause?
An operator's watermark is the minimum across its inputs, so one silent partition freezes it. Mark sources idle after a timeout. High allowed lateness delays cleanup, not firing.
-
3What does Kafka Streams exactly_once_v2 make atomic?
It uses a Kafka transaction covering output, changelog and offsets, which is why it applies to Kafka-to-Kafka processing. External side effects such as HTTP calls or a Postgres write are outside the transaction.
-
4One hashtag is 20% of all events and the count operator for it is saturated. Which fix addresses the cause?
All events for one key go to one operator instance, so adding partitions or parallelism does not spread that key. Salting splits it across instances and a small second stage merges the partial counts.
Where to go next
- Event sourcing and CQRS: projections are stream processors over an event store, with the same checkpoint and idempotency concerns.
- Bulkheads, load shedding and backpressure: what to do when the stream really is faster than you can process.
- Time-series databases: a common destination for windowed aggregates.
- Design a news feed: a capstone where stream processing powers ranking and counters.
Finished this lesson?
Mark it complete to track your progress across the roadmap.