Stream processing: windows, watermarks, state

In one sentence

Compute continuously over unbounded event streams: group events into windows by event time, use watermarks to decide when a window is complete, and checkpoint state so results survive failures exactly once.

Analogy: Counting mailed ballots: you tally by postmark date, not arrival date, and declare a day closed only when you're confident no more ballots from that day are coming.

Events get event-time stamps at the source, are grouped per key and window, and are emitted when the watermark passes the window's end; checkpoints make the state recoverable.

How it works

  • Aggregate by event time, not processing time: events arrive late and out of order.
  • Windows bound the infinite stream: tumbling (fixed), hopping (overlapping), session (ends after inactivity).
  • A watermark says older events are no longer expected; its delay trades result latency against dropped late data.
  • Checkpoints snapshot state with source offsets, so a crashed job rewinds and replays without loss or double counts.
  • Exactly-once covers state and transactional sinks, not side effects like emails or API calls.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your Flink job counts orders per minute by event time with a 10 s watermark delay. The dashboard shows fewer orders than the database, and the missing ones come from mobile clients that sync after being offline. What do you do?

Go deeper

Full explanation

A stream processor (Flink, Kafka Streams, Spark Structured Streaming) runs a long-lived job that reads events, usually from Kafka (Queues vs streams (Kafka)), keeps state and emits results continuously.

Event time vs processing time. Event time is when something happened on the device; processing time is when your job sees it. Phones go offline and partitions lag, so events arrive out of order. Aggregate by event time, or results change with every backlog and replay.

Windows cut the infinite stream into groups: tumbling (fixed, no overlap), hopping (fixed, overlapping) and session (closed by a gap of inactivity).

Watermarks decide when a window is complete: Watermark(t) declares no more events at or before t. A common one is the max event time seen minus an allowed delay; Kafka Streams calls that delay a grace period. Events behind it are late: drop them, side-output them or update the result.

State and exactly-once. Per-key state (counts, joins) lives locally, often in RocksDB. Flink snapshots state plus source offsets in periodic checkpoints and rewinds to the last one after a crash. Exactly-once covers state and transactional sinks such as Kafka, not side effects like emails.

Code Flink SQL: clicks per URL per minute, by event time
sqlFlink SQL: clicks per URL per minute, by event time
-- Event time = ts; tolerate up to 30 s of out-of-order arrival
CREATE TABLE clicks (
  user_id STRING,
  url     STRING,
  ts      TIMESTAMP(3),
  WATERMARK FOR ts AS ts - INTERVAL '30' SECOND
) WITH (
  'connector' = 'kafka',
  'topic' = 'clicks',
  'properties.bootstrap.servers' = 'kafka:9092',
  'properties.group.id' = 'click-counts',
  'format' = 'json'
);

-- Each 1-minute window emits once the watermark passes its end,
-- i.e. ~30 s after the minute closes. Later events are dropped.
SELECT window_start, window_end, url, COUNT(*) AS clicks
FROM TUMBLE(TABLE clicks, DESCRIPTOR(ts), INTERVAL '1' MINUTE)
GROUP BY window_start, window_end, url;
Real example

A ride app counts trip requests per city per minute for surge pricing. Phones buffer events in tunnels, so some arrive 10–60 s late (assumption). With processing time, a tunnel exit spikes the wrong minute. With event time and a 30 s watermark delay, each minute emits ~30 s after it ends, and only events later than that go to a side output for correction. When a task crashes, Flink restores the last checkpoint and replays Kafka from the saved offsets: counts are neither lost nor doubled.

Trade-offs +3 · −3

+ You gain

  • Results in seconds instead of at the next batch run.
  • Event time plus watermarks give the same answer on live data and on replay.
  • Local state makes joins and aggregations fast, without a database round trip per event.

− You pay

  • Hard to operate: state size, checkpoint duration, backpressure and rescaling.
  • A watermark is a guess: too tight drops late data, too loose delays every result.
  • Exactly-once output only becomes visible when each checkpoint commits, and it stops at your sinks.

Use it when

Continuous aggregates, fraud and anomaly detection, real-time ML features, CDC pipelines and alerting: anywhere a result is worth more in seconds than in hours.

Avoid it when

When hourly or daily freshness is fine, a batch job is simpler to run, debug and backfill. For stateless per-event work, a plain consumer is enough.

Numbers to know 4
  • Bounded-out-of-orderness watermark ≈ max event time seen − allowed delay (e.g. 30 s).
  • Flink exactly-once sinks use two-phase commit since Flink 1.4 (Dec 2017), committing on each checkpoint.
  • Kafka Streams: processing.guarantee=exactly_once_v2 (Kafka 3.0+, brokers 2.5+).
  • With transactional output, readers using read_committed see results only after the commit: latency ≥ checkpoint interval.
Common pitfalls 4
  • Using processing time for business metrics: a backlog or replay shifts events into the wrong windows.
  • An idle partition holds the watermark back, so windows never fire. Configure idleness.
  • Unbounded state: joins or distinct counts on keys that never expire grow until the job dies. Set a state TTL.
  • Assuming exactly-once covers your webhook or email call: make side effects idempotent.
Interview questions 2

Answer out loud first, then reveal.

How do you handle late events in a windowed aggregation?Show answer

First I measure lateness, event time versus arrival, per source. I set the watermark delay to cover most of it, say p99, accepting that each window emits that much later. For the stragglers I choose per use case: drop and count them, route them to a side output for a correction job, or allow lateness so the window re-emits an updated result, which downstream must treat as an upsert.

What does exactly-once really mean in Flink or Kafka Streams?Show answer

Exactly-once state, not exactly-once execution. After a failure records are processed again, but state and source offsets rewind to the same checkpoint, so each event affects state once. Output needs the sink's help: Kafka transactions or a two-phase-commit sink that commits when the checkpoint completes, or idempotent upserts. A call to an external API can still run twice, so I give it an idempotency key.