Stream Processing
Event time versus processing time, watermarks, windowing, and what "exactly-once" actually means — the machinery for computing over data that never stops arriving.
#The shift from batch to stream
A batch job has a luxury it never acknowledges: the data is complete. When you run yesterday's report, yesterday is over. Every record that will ever belong to that window has arrived. You can sort, join, aggregate, and know the answer is final.
Streaming removes that. Data arrives continuously, out of order, sometimes hours late, and you have to produce answers before you know whether more input is coming.
Every hard problem in stream processing follows from that one difference.
#The two clocks
A mobile app buffers events offline. The user goes into a tunnel
at 09:58 and reconnects at 10:47.
Event time of the click: 09:58
Processing time at your job: 10:47
"Clicks in the 09:55-10:00 window" is a question about event time.
Answering it in processing time puts the click in the 10:45 bucket
and the answer is simply wrong.Almost every business question is an event-time question. Revenue per hour, sessions per user, fraud within a 5-minute window — all of these mean when it happened, not when we found out. Processing time is only acceptable for questions genuinely about your own system, like throughput monitoring.
The cost of event time is that you must decide how long to wait for late data. That decision is a watermark.
#Watermarks
A watermark is an assertion the system makes to itself:
"I believe I have now seen all events with timestamp ≤ T."
It is a guess, not a fact — nothing can prove no more events are coming. But a stream never ends, so without some rule for declaring "enough", you could never publish a result at all. The watermark is that rule: the point at which a time window is considered complete enough to report on.
Records arriving (event times, out of order):
10:03 10:01 10:04 10:02 10:07 10:05 [10:02 ← LATE] 10:09
Watermark strategy: "max event time seen minus 5 minutes"
after 10:07 → watermark = 10:02
after 10:09 → watermark = 10:04
When watermark passes 10:05, the 10:00-10:05 window fires.
The late 10:02 record arrives AFTER that. Now what?That last question has exactly three answers, and choosing among them is a product decision, not a technical one:
| Strategy | Behaviour | Right for |
|---|---|---|
| Drop | Discard records past the watermark | Monitoring, approximate dashboards |
| Side output | Route late records to a separate stream for inspection or manual handling | Anything where you need to know how much you're losing |
| Allowed lateness + retract | Keep window state open longer; re-emit a corrected result that supersedes the earlier one | Billing, analytics that must eventually be exact |
"Retract" means withdrawing a result you already published. If the 10:00–10:05 window first reported 41 clicks and the late record arrives, you send "ignore 41, the answer is 42" — so anything downstream must be able to overwrite a number it has already received.
#Windows
Unbounded streams have to be cut into finite chunks before you can aggregate. Four shapes cover nearly everything:
TUMBLING (fixed, non-overlapping)
[00-05][05-10][10-15] "revenue per 5 minutes"
each event in exactly one window
SLIDING / HOPPING (fixed size, overlapping)
[00────05]
[01────06]
[02────07] "5-minute average, updated each minute"
each event in size/slide windows → 5× the state
SESSION (dynamic, gap-based)
[ev ev ev]......[ev ev] "user session = activity with
gap > 30 min closes it no 30-minute gap"
windows have data-dependent boundaries
GLOBAL (one window, custom trigger)
[everything] "every 1,000 events" or a custom ruleSliding windows are a state multiplier people miss. A 1-hour window sliding every minute means each event belongs to 60 windows, so you hold 60× the state. At scale this is the difference between a job that fits in memory and one that doesn't. If you need per-minute updates over an hour, it's usually far cheaper to keep one-minute tumbling totals and add up the latest 60 of them each minute. Each event then touches one small counter instead of 60 windows.
Session windows are the expensive ones because boundaries are data-dependent — you cannot know a session has ended until the gap elapses. Worse, a late event can merge two previously separate sessions. Say a user was active 09:00–09:20 and 09:45–10:00, so you reported two sessions; then a late event stamped 09:35 arrives and closes the gap. Now you must retract both results and emit one combined session.
#State, and why it dominates operations
A stateless step — one that transforms each event on its own, like converting a currency field or dropping bot traffic — is easy. Everything interesting in streaming is stateful, meaning it must remember something between events: aggregations, joins, deduplication, session tracking. That state can be enormous — a job tracking 100 million users' sessions holds 100 million entries — and it must survive failure.
The critical property is that the state snapshot and the input offset must be consistent with each other. The input offset is your position in the input stream — "I've processed up to message 5,000,000 in partition 3". After a crash you restore the saved state and resume reading from the saved offset, so the two must describe the same moment. Restoring state from 10:00 while resuming input from 10:05 silently loses five minutes of updates; resuming from 09:55 double-counts five minutes. The snapshot must record exactly which offsets it includes.
Flink does this with the Chandy–Lamport distributed snapshot algorithm. It injects a special marker record, a barrier, into the input streams. Each operator saves its state at the moment the barrier reaches it, then passes the barrier on. Because every operator saves "everything before the barrier, nothing after it", the saved pieces together form a consistent cut — a snapshot of the whole distributed job at one logical point in the stream — without stopping it. This is the same idea as a consistent snapshot in a database, applied to a dataflow graph.
#"Exactly-once" — what it actually means
The most misunderstood phrase in streaming. Let's be precise, because the imprecision causes real bugs.
**You cannot have exactly-once delivery.** It's impossible in an asynchronous network with failures — the sender can never know whether a lost acknowledgement means the message arrived or didn't, so it must either risk losing it or risk duplicating it. This is a theorem, not a limitation of current tools.
**You can have exactly-once effects:** a record may physically arrive and be processed several times, but the job's stored results look exactly as though it happened once. The delivery is messy; the outcome isn't. That distinction — between how many times something ran and how many times it counted — is the whole of what the machinery below buys you.
What the machinery gives you:
input offsets + operator state + output commit
all move together, atomically, at each checkpoint
On failure: roll back to the last checkpoint,
replay from those offsets, recompute.
Internal state ends up identical.
What it does NOT give you:
Any guarantee about side effects your code performs
directly — an HTTP POST, an email, a payment.
Those happen on every replay.#Stream joins
Joining two unbounded streams raises a question a batch join never has to answer: how long do you keep a record around waiting for its partner?
| Join type | Mechanism | Cost |
|---|---|---|
| Stream–stream (windowed) | Buffer both sides for a bounded interval; emit matches within it | State proportional to window × rate on both sides |
| Stream–table | Enrich each event from a materialised lookup table | Table must be copied to every parallel task; watch for skew (a few very hot keys overloading one task) |
| Temporal / versioned join | Join against the version of the table as of the event's timestamp | Requires versioned state; the correct choice for prices, rates, and config |
The temporal join is the one that's usually needed and rarely used. If you join an order stream against a currency_rates table, joining against the current rate is wrong — you want the rate that was in effect when the order was placed. Replaying the job a month later with a plain lookup gives different (and incorrect) results; a temporal join gives the same answer forever. Reproducibility on replay is the test for whether your join is correct.
#Choosing an engine
| System | Model | Where it fits |
|---|---|---|
| Kafka Streams | Library, no cluster; state in RocksDB + changelog topics | Kafka-native services; deploy as a normal app |
| Flink | True streaming, event time, sophisticated state and snapshots | The most complete engine; complex jobs, large state |
| Spark Structured Streaming | Micro-batch (continuous mode exists but is limited) | Teams already on Spark; batch/stream code sharing |
| Materialize / RisingWave | Incremental view maintenance over SQL | "Keep this SQL query's result always up to date" |
| A consumer loop you wrote | Whatever you build | Genuinely fine for stateless or small-state transforms — don't reach for a cluster to filter a topic |
#Exercise
#Check yourself
Event time versus processing time — which do business questions need?Show answer
What is a watermark?Show answer
Name the three ways to handle data that arrives after the watermark.Show answer
What trade-off does the watermark delay control?Show answer
Why are sliding windows expensive?Show answer
What must a checkpoint keep consistent?Show answer
What does "exactly-once" actually mean in stream processing?Show answer
Why use a temporal join for currency rates?Show answer
#What to carry forward
- Event time versus processing time is the root distinction. Business questions are almost always event time.
- Watermarks are heuristics that trade completeness for latency. Decide the late-data policy explicitly.
- Sliding windows multiply state; session windows can retroactively merge.
- State + input offset + output commit must move atomically — that's what checkpointing buys.
- "Exactly-once" means state semantics, not delivery. External side effects need transactional sinks or idempotency.
- Temporal joins, not current-value lookups, are what make a job reproducible on replay.
- A five-minute batch job is often the correct answer. Make streaming justify itself.