Stream Processing
Processing unbounded event streams — batch vs stream, event time vs processing time, windows and watermarks, stateful operators, exactly-once semantics, joins, change data capture, and the Kafka/Flink ecosystem.
Batch processing runs a job over a bounded dataset (yesterday's logs) and produces output when done. Stream processing handles unbounded data continuously, producing results within milliseconds to seconds of events arriving: fraud detection, live dashboards, alerting, real-time recommendations, keeping search indexes and caches up to date.
The building blocks
- A durable, partitioned, replayable log (Message queues) is the backbone: it decouples producers from processors and lets you reprocess history.
- A stream processor runs operators (filter, map, aggregate, join) continuously, keeping state fault-tolerantly.
Event time vs processing time
| Event time | Processing time | |
|---|---|---|
| Meaning | When the event happened (timestamp in the event) | When the processor sees it |
| Deterministic on replay? | Yes | No |
| Affected by delays? | Correct even if events arrive late or out of order | Results shift with lag, backlogs, outages |
A phone that was offline for an hour uploads its events late. Counting "clicks per minute" by processing time would attribute them to the wrong minute. Use event time for correctness.
Windows
Aggregations over infinite streams need windows:
| Window | Definition | Example |
|---|---|---|
| Tumbling | Fixed size, non-overlapping | Requests per minute |
| Hopping / sliding | Fixed size, overlapping, advancing by a step | 5-minute average updated every minute |
| Session | Activity separated by gaps of inactivity | User sessions ending after 30 min idle |
| Global + triggers | Custom | "Every 100 events" |
Watermarks: when is a window complete?
With out-of-order data, when can you emit the count for 10:00–10:01? A watermark is the processor's estimate that "no more events with event time ≤ T are expected". When the watermark passes the end of a window, the window fires.
- Watermarks are usually derived from observed timestamps minus an allowed lateness (e.g. "max seen − 5 seconds").
- Late events (arriving after the watermark) can be dropped, sent to a side output, or trigger an updated result if allowed lateness is configured.
- The trade-off: waiting longer gives more complete results but higher latency.
Stateful processing and fault tolerance
Aggregations, joins and deduplication need state (counts per key, recent events). Processors keep it locally (in memory or RocksDB), partitioned by key, and make it fault-tolerant:
- Flink: periodic distributed snapshots (the Chandy-Lamport-style barrier algorithm): barriers flow through the dataflow; each operator snapshots its state when barriers arrive; on failure, restore the last snapshot and rewind the sources to the matching offsets.
- Kafka Streams: state stores backed by compacted changelog topics in Kafka; recovery replays the changelog.
Exactly-once semantics
Messages can be redelivered after failures (at-least-once). "Exactly-once" in stream processing means each event's effect on state and output happens once, even if it's physically processed more than once:
- Internal state: snapshot/restore consistent with source offsets (Flink checkpoints, Kafka transactions that commit offsets and output atomically).
- External sinks: either transactional (two-phase commit with the checkpoint — Flink's TwoPhaseCommitSinkFunction, Kafka transactional producer) or idempotent (upserts keyed by a deterministic ID).
End-to-end exactly-once is only as strong as the weakest link — a sink that sends emails can't be un-sent.
Joins
| Join | Example | State needed |
|---|---|---|
| Stream–stream (windowed) | Match ad impressions with clicks within 1 hour | Both streams' events within the window |
| Stream–table (enrichment) | Add user profile data to each click | The table (kept current from a CDC stream) |
| Table–table | Maintain a materialised join of two changing tables | Both tables |
Change data capture (CDC)
Instead of having applications dual-write to a database and a queue, stream the database's own change log (PostgreSQL WAL, MySQL binlog) into Kafka with a tool like Debezium. Every insert, update and delete becomes an event, in commit order. Downstream processors keep derived data in sync: search indexes, caches, analytics warehouses, materialised views.
This leads to a powerful architectural idea: treat the log as the source of truth, with databases, indexes and caches as materialised views of it (event sourcing at the system level, sometimes called "turning the database inside out").
Architectures
- Lambda architecture: a batch layer (accurate, slow) plus a speed layer (approximate, fast), merged at query time. Two codebases for the same logic — now largely out of favour.
- Kappa architecture: only stream processing; reprocess history by replaying the log through a new version of the job. Simpler, enabled by durable logs and exactly-once processors.
Tools
| Tool | Notes |
|---|---|
| Apache Flink | True streaming, event time, rich state, exactly-once; the most powerful general-purpose engine |
| Kafka Streams / ksqlDB | A library (not a cluster) for Kafka-to-Kafka processing; simple deployment |
| Spark Structured Streaming | Micro-batches (or continuous mode); unified with Spark batch |
| Apache Beam | One programming model, runs on Flink/Spark/Google Dataflow |
| Materialize, RisingWave | Streaming SQL databases maintaining incremental materialised views |
-- Flink SQL: clicks per page per minute in event time, tolerating 5 s of lateness
CREATE TABLE clicks (
page STRING,
ts TIMESTAMP(3),
WATERMARK FOR ts AS ts - INTERVAL '5' SECOND
) WITH ('connector' = 'kafka', 'topic' = 'clicks', 'format' = 'json');
SELECT page, window_start, COUNT(*) AS clicks
FROM TABLE(TUMBLE(TABLE clicks, DESCRIPTOR(ts), INTERVAL '1' MINUTE))
GROUP BY page, window_start, window_end;- Stream processing computes continuously over unbounded data, usually from a durable log like Kafka.
- Use event time for correct results; watermarks decide when windows are complete; late data needs a policy.
- Windows: tumbling, hopping, session.
- State is partitioned by key and made fault-tolerant with snapshots or changelogs.
- Exactly-once = consistent state + transactional or idempotent sinks.
- CDC streams database changes to keep derived systems in sync; Kappa replaces Lambda by replaying logs.