# Stream Processing

**Also known as:** Event streaming · Continuous queries  
**Category:** Data & Storage (Where the data lives)  
**Complexity:** 4/5  
**Guide:** https://layra4.dev/architectures/data-storage/stream-processing

*A job that never ends, updating its results as each event arrives.*

Stream processing runs a job that never finishes. It reads an unbounded sequence of events, such as clicks, payments or sensor readings, usually from a durable log like Kafka or Kinesis. It updates its results as each event arrives. Apache Flink, Kafka Streams and Spark Structured Streaming are common engines. The output is a running count, an alert, an enriched event, or a table kept current.

The hard parts are time and failure. Events arrive late and out of order, so the job must decide when a window of time is complete. And the job runs for months, so it must save its state and resume after a crash without losing or double-counting events.

> **In one sentence.** A stream job keeps state per key and updates it with every event; event time, watermarks and checkpoints decide when a result is final and how it survives a crash.

## Origin (2015)

Early engines such as Apache Storm (2011) were fast but could lose or repeat events. Google's MillWheel (2013) and the Dataflow Model paper (2015) made event time, watermarks and consistent state the standard. Apache Beam and Apache Flink follow that model.

## How it works

### Event time vs processing time

Event time is when the thing happened, stamped by the device or service that produced the event. Processing time is when your job sees it. Network delays, retries and offline devices put a gap between the two.

- Group by event time for results that are correct
- Processing time is simpler, but replays give different answers
- The gap (skew) is not constant: it jumps during outages

> event_time 09:59:58 · processing_time 10:03:12  (the phone was in a tunnel)

### Windows

A window cuts the endless stream into finite groups you can count or sum. The window is chosen by event time and, usually, per key.

- Tumbling: fixed size, no overlap, such as each minute
- Sliding (hopping): fixed size, overlapping, such as 10 minutes every minute
- Session: per key, closed after a gap with no events, such as 30 minutes

### Watermarks and late data

A watermark is the job's claim that no more events older than time T are expected. When the watermark passes the end of a window, the window fires its result. An event that arrives after that is late.

- A watermark is an estimate, not a guarantee
- Too eager means more late events; too patient means slower results
- Late events can be dropped, sent to a side output, or used to update the result

> watermark = highest event time seen − 30 s

### Keyed state and checkpoints

Events are partitioned by a key, such as user id, so every event for one key reaches the same worker and its local state. The engine takes regular snapshots of all state together with the input offsets. After a crash it restores the last snapshot and rereads the log from those offsets.

- State lives with the worker, not in a remote database
- A checkpoint is state plus input positions, taken together
- Recovery replays every event since the last checkpoint

### Delivery guarantees (At-least-once · Exactly-once)

At-most-once can lose events. At-least-once never loses one but replays some after a crash. Exactly-once in an engine means its state ends up as if each event were applied once. Writes to outside systems are only exactly-once if the sink is idempotent or commits with the checkpoint.

- At-least-once plus an idempotent sink is the practical default
- A transactional sink commits its output together with the checkpoint
- No checkpoint can take back an email that was sent twice

### Backpressure

When a sink or a later step is slower than the input, the engine slows the readers instead of buffering without limit. Because the input is a durable log, the backlog waits there safely and shows up as consumer lag.

## Design rules

### Stamp events at the source and window by event time

Put a timestamp in every event when it is created. Windows built on arrival time give a different answer on every replay, and an outage moves its traffic into the minute the job came back.

### Decide what happens to late events

Set the allowed lateness from the skew you measure, not a guess. Send anything later to a side output and count it. Late events that are dropped silently look like a dip in the chart.

### Make every sink idempotent

Recovery replays events, so outputs are written more than once. Upsert by a key derived from the data, such as (page, window start), or use a sink that commits with the checkpoint. Keep calls with side effects, like payments, behind an idempotency key.

### Alert on lag and checkpoint time, not only on uptime

A job can be running and an hour behind. Watch consumer lag on the input and how long checkpoints take. Both rise before the results go stale.

## Examples

### A per-minute count by event time, with a watermark and an idempotent sink

```typescript
// Count page views per page per minute, by when they happened, not when they arrived.
type View = { pageId: string; eventTime: number };   // ms since epoch, stamped at the source

const WINDOW_MS = 60_000;
const MAX_SKEW_MS = 30_000;              // measured from real data, not guessed

const counts = new Map<string, number>(); // keyed state: "pageId|windowStart" -> views
let maxEventTime = 0;

// The watermark: "no event older than this is still expected".
const watermark = () => maxEventTime - MAX_SKEW_MS;

export async function onEvent(v: View): Promise<void> {
  const windowStart = v.eventTime - (v.eventTime % WINDOW_MS);   // tumbling window
  if (windowStart + WINDOW_MS <= watermark()) {
    await lateEvents.write(v);           // the window already fired: keep it, count it
    return;
  }
  const key = v.pageId + "|" + windowStart;
  counts.set(key, (counts.get(key) ?? 0) + 1);
  maxEventTime = Math.max(maxEventTime, v.eventTime);
  await fireClosedWindows();
}

async function fireClosedWindows(): Promise<void> {
  for (const [key, views] of counts) {
    const [pageId, start] = key.split("|");
    if (Number(start) + WINDOW_MS > watermark()) continue;     // still open
    // Upsert by (page, window): a replay after a crash rewrites the same row.
    await sink.query(
      `insert into page_views_per_minute (page_id, window_start, views) values ($1, $2, $3)
       on conflict (page_id, window_start) do update set views = excluded.views`,
      [pageId, new Date(Number(start)), views],
    );
    counts.delete(key);
  }
}
```

This is what an engine does inside one keyed step. Real engines also track the watermark per input partition, take the lowest, and checkpoint `counts` together with the input offsets.

## When to use

- Results must be seconds or minutes old: fraud checks, alerts, live dashboards
- Events already flow through a durable log that you can read and replay
- You need state per key over time: sessions, running totals, limits per user

## When not to use

- A daily answer is fine: a batch job is simpler to build, test and rerun
- Each event needs one action and no state: a plain queue consumer is enough
- No one can run a stateful job around the clock, with checkpoints and lag alerts

## Benefits

- Results are seconds old, not hours
- Work is spread evenly over the day instead of one nightly spike
- One job can both react (alert, block) and aggregate

## Costs

- Time is hard: late and out-of-order events, and watermarks to tune
- A stateful job that never stops: checkpoints, upgrades and rebalances
- Fixing a bug means replaying the log, which needs long retention

## Pitfalls

- Windowing by processing time, so a one-hour outage moves an hour of sales into one minute.
- Trusting "exactly-once" and calling a payment API from inside the job, which charges twice after a restart.
- One input partition with no traffic that holds the watermark back, so no window ever fires.
- Session or join state that never expires, so checkpoints grow until they take minutes and the job falls behind.
- One hot key, such as a bot, that sends most events to one worker while the others sit idle.

## Related patterns

- [Batch Processing](https://layra4.dev/architectures/data-storage/batch-processing) — the same computation over a bounded dataset, when hours are fine
- [Message Queue](https://layra4.dev/architectures/core-building-blocks/message-queue) — the durable log a stream job reads from and replays
- [Publish–Subscribe & Event Streams](https://layra4.dev/architectures/core-building-blocks/pub-sub) — how several jobs read the same stream independently
- [Backpressure](https://layra4.dev/architectures/key-design-principles/backpressure) — how a slow sink slows the readers instead of crashing the job
- [Change Data Capture](https://layra4.dev/architectures/data-storage/change-data-capture) — turns database changes into a stream you can process
- [Idempotent Consumer](https://layra4.dev/architectures/infrastructure/idempotent-consumer) — why a replayed event must be safe to apply twice

## Further reading

- *Streaming Systems* — Tyler Akidau, Slava Chernyak & Reuven Lax (2018) — Event time, windows, watermarks and triggers, explained by the team behind Google Dataflow.
- *Designing Data-Intensive Applications, ch. 11* — Martin Kleppmann (2017) — Logs, stream joins, fault tolerance and what exactly-once really means.
- *The Dataflow Model* — Tyler Akidau et al. (VLDB 2015) — The paper behind the windowing and watermark model most engines now use.
