Shelves / Data Engineering for Analytics
DE·06
Stream Processing
Computing on data as it arrives: event time versus processing time, tumbling, sliding and session windows, watermarks and the latency–completeness trade-off, late data (drop, side outputs, allowed lateness with updates), state and checkpoints, exactly-once results with transactional sinks, stream joins, and the engines (Flink, Kafka Streams, Spark Structured Streaming, streaming databases); with TiffinBox's live kitchen dashboard and a lab in which a three-minute mobile network outage shows why counting by arrival time is wrong and how watermark settings trade waiting for accuracy.
Start here: when "last night" is too late
Batch pipelines (chapters 03–05) answer questions about yesterday. Some questions need answers within seconds: how many orders is each kitchen behind on right now?, is this rider's ETA slipping?, are refunds spiking in the last five minutes? Stream processing computes continuously over events as they arrive, typically from Kafka.
The hard part isn't speed; it's time. Each event has two times:
- Event time: when it happened (the rider's phone recorded "picked up" at 12:41:07).
- Processing time: when your system sees it (12:41:09 normally, or 12:44:00 if the phone was offline).
If you group by processing time, a network outage moves events into the wrong minute. If you group by event time, you must decide how long to wait for stragglers before publishing a minute's result. That decision is the watermark.
A mobile network outage, measured
The lab streamed 30 minutes of rider events (~40 per second; most arrive within 2 s, a few minutes late) with a three-minute outage during which 30% of phones were offline, then reconnected and sent their backlog:
| Counting per minute by… | Minutes 10–12 (outage) | Minute 13 (reconnect) | Worst error |
|---|---|---|---|
| truth (event time) | 2,362 / 2,499 / 2,341 | 2,392 | — |
| processing time | 1,692 / 1,752 / 1,630 | 4,540 | 90% |
| Event time with a watermark lag of… | Result published after window end | Mean error of first result | Events dropped as too late |
|---|---|---|---|
| 0 s | 0.4 s | 6.2% | 6.2% |
| 5 s | 5.3 s | 3.8% | 3.7% |
| 30 s | 30 s | 3.0% | 2.9% |
| 120 s | 120 s | 1.6% | 1.5% |
| 5 s, plus updates for late events up to 10 min | 5.3 s, then corrections | 3.8% first, 0.0% final | 0 |
Processing time invented a dip and a spike that never happened. Event time with a watermark was correct for most minutes, and waiting longer bought accuracy at the cost of latency. Allowing late updates gave both: a fast first answer and an exact final one.
How deep to go
Volume 17 defines six mastery levels. For stream processing:
| Level | What you can do |
|---|---|
| L1 | Explain event time, processing time and windows |
| L2 | Build a windowed aggregation with a streaming engine |
| L3 | Explain watermarks, late data, state, checkpoints and exactly-once |
| L4 | Debug wrong counts, growing state, lag and backpressure |
| L5 | Design streaming pipelines with explicit latency and completeness targets |
| L6 | Operate them: upgrades with state, rescaling, incidents, cost |
Time
| Time | Source | Use |
|---|---|---|
| event time | timestamp set where the event happened | correctness: "orders placed in 12:41" |
| ingestion time | when Kafka (or the gateway) received it | a fallback when devices' clocks can't be trusted |
| processing time | the processing machine's clock | operational metrics about the pipeline itself |
Device clocks drift and can be wrong; record both the device's event time and the server's receipt time, and decide which is authoritative per use (server receipt for fraud, device time for delivery analytics, with sanity bounds).
Windows
| Window | Shape | TiffinBox example |
|---|---|---|
| tumbling | fixed, non-overlapping (every minute) | orders per kitchen per minute |
| sliding / hopping | fixed size, overlapping (5 minutes, every minute) | refund rate over the last 5 minutes |
| session | activity separated by a gap (30 minutes idle) | a customer's browsing session |
| global with triggers | one window, emitted on custom conditions | running totals for today |
Watermarks and late data
A watermark is typically "the maximum event time seen, minus an allowed delay". When it passes a window's end, the window fires. The lab shows the trade-off: a longer lag means later results and fewer dropped events. Real systems combine:
- a watermark lag covering normal delays (seconds);
- allowed lateness: keep window state longer (minutes to hours) and emit updated results for late events; sinks upsert by window key;
- a side output for events later than that, written somewhere (a table, a DLQ) so batch jobs can reconcile;
- idle-source handling: a partition with no events would otherwise hold back the watermark for everyone.
And a lambda-style safety net: the nightly batch (chapters 03–05) recomputes the authoritative daily figures from all events, so streaming can optimise for freshness while batch guarantees completeness.
State, checkpoints and exactly-once
Windowed counts, joins, deduplication and session tracking all keep state per key. Engines store it locally (Flink: in memory or RocksDB on disk) and checkpoint it periodically, with input offsets, to durable storage. After a failure, the job restores the last checkpoint and replays input from those offsets, so state is as if nothing failed.
Exactly-once results also need the output side: either a transactional sink that commits writes together with the checkpoint (Flink's two-phase commit to Kafka; Kafka Streams' transactions) or an idempotent sink (upserts keyed by window and key). Otherwise replays after a failure produce duplicates downstream: at-least-once again.
Watch state size: unbounded keys (every user ever), long windows or forgotten TTLs grow state until checkpoints slow and recovery takes hours. Set state TTLs and size windows deliberately.
Joins in streams
- Stream–table: enrich each order event with the kitchen's current details (the table is itself fed by a compacted topic or CDC).
- Stream–stream, windowed: match "order placed" with "rider assigned" within 10 minutes; unmatched after the window → an alert.
- Temporal (versioned) joins: enrich with the value valid at the event's time (the streaming version of chapter 02's point-in-time join).
Engines
| Engine | Model | Notes |
|---|---|---|
| Apache Flink | distributed dataflow, event time first, strong state and checkpoints | the most complete streaming engine; SQL and DataStream APIs |
| Kafka Streams | a Java library inside your service, state in local stores backed by Kafka | no separate cluster; great for per-service streaming logic |
| Spark Structured Streaming | micro-batches (and a continuous mode) over DataFrames | reuse Spark skills and code; latency of seconds |
| streaming databases (RisingWave, Materialize) | SQL materialised views kept up to date incrementally | very approachable for SQL teams |
| real-time OLAP stores (ClickHouse, Druid, Pinot) | ingest streams, query fresh data fast | the serving layer for live dashboards |
TiffinBox's live kitchen dashboard
orders and status events (Kafka, keyed by kitchen_id)
→ Flink job: event-time tumbling 1-minute windows per kitchen; watermark 5 s; allowed lateness 15 min with upserts
· orders placed, cooked, packed, picked up per minute; backlog = placed − picked up
· stream–table join with kitchen details (compacted topic)
→ upsert into ClickHouse (or PostgreSQL for small scale) keyed by (kitchen_id, minute)
→ dashboard refreshes every 5 s; nightly batch recomputes the day for finance
Common traps
- Processing-time windows for business metrics.
- A fixed watermark assumed to cover outages.
- Unbounded state without TTLs.
- Non-idempotent sinks behind "exactly-once" engines.
- Streaming everything when an hourly batch would do.
Lab: event time, watermarks and an outage
Setup. A small event-time windowing engine written in Python on the lab machine (no external streaming system: the logic is the point, and it's the same logic Flink or Kafka Streams apply). The input is generated, then processed in arrival order:
- 30 minutes of rider events at ~40 per second (71,526 events), each with an event time;
- arrival delays: 95% within 0.05–2 s, 4% within 5–30 s, 1% within 1–5 minutes (phones briefly offline);
- an outage: from minute 10 to minute 13, 30% of phones are offline and deliver their backlog when they reconnect at 13:00.
Counts per 1-minute tumbling window are compared with the truth (counting every event by its event time). The watermark is "maximum event time seen − lag"; a window is published when the watermark passes its end; events for already-published windows are dropped, or, with allowed lateness, applied as updates.
Results
| Method | First result after window end | Mean error of first result | Worst window | Late events dropped |
|---|---|---|---|---|
| processing-time windows | immediately | 6.7% | 90% (minute 13) | — |
| event time, watermark lag 0 s | 0.4 s | 6.24% | 32.5% | 4,400 (6.15%) |
| lag 2 s | 2.3 s | 4.58% | 31.2% | 3,186 (4.45%) |
| lag 5 s | 5.3 s | 3.84% | 31.1% | 2,678 (3.74%) |
| lag 30 s | 30.3 s | 2.99% | 30.6% | 2,091 (2.92%) |
| lag 120 s | 120.4 s | 1.61% | 29.0% | 1,069 (1.49%) |
| lag 5 s + allowed lateness 10 min (updates) | 5.3 s | 3.84%, final 0.00% | — | 0 (2,678 updates emitted) |
Processing-time counts around the outage:
| Minute | 9 | 10 | 11 | 12 | 13 | 14 |
|---|---|---|---|---|---|---|
| true (event time) | 2,410 | 2,362 | 2,499 | 2,341 | 2,392 | 2,353 |
| by arrival (processing time) | 2,416 | 1,692 | 1,752 | 1,630 | 4,540 | 2,357 |
What it shows
- Processing time fabricates patterns whenever delivery is disrupted: a dip of ~30% for three minutes, then a spike of ~90%. A dashboard would have shown a crisis and a recovery that never happened in kitchens.
- Event time with watermarks is correct for normal delays, and each extra second of waiting buys a little accuracy. But no fixed watermark covers an outage (the worst window stayed ~30% off even at 120 s).
- Allowed lateness with updates resolves the trade-off: first results in ~5 s, exact results once stragglers arrive, nothing dropped. The cost is keeping window state longer and sinks that accept corrections.
- Design the dashboard to show it: mark minutes as "provisional" until their lateness period passes.
Try it yourself
- Add a side output for events later than the allowed lateness and count them per window.
- Implement 5-minute sliding windows every minute and compare the cost (state per key) with tumbling windows.
- Run the same logic in Flink SQL or Kafka Streams with the same synthetic events (published to Kafka in arrival order) and compare results.
- Use the server's receipt time instead of the device time and see which errors appear and disappear.
Revision sheet: stream processing
Key ideas
- Event time for correctness; processing time only for pipeline metrics; record both.
- Windows: tumbling, sliding, session, global with triggers.
- Watermarks trade latency for completeness; allowed lateness with upserts gets both; side outputs for the very late; batch as the safety net.
- State per key, checkpointed with offsets; exactly-once needs transactional or idempotent sinks; bound state with TTLs.
- Joins: stream–table, windowed stream–stream, temporal.
- Engines: Flink, Kafka Streams, Spark Structured Streaming, streaming databases; real-time OLAP for serving.
Numbers to remember
- Lab: processing-time worst window error 90%; watermark lag 0 s → 6.2% first-result error, 120 s → 1.6%; lateness with updates → 0.0% final.
Glossary
- Watermark: the event-time point before which no more events are expected.
- Allowed lateness: how long window state is kept to apply late events.
- Side output: a separate stream for events too late to apply.
- Checkpoint: a consistent snapshot of state and input positions.
- Backpressure: slowing producers when consumers fall behind.