Stream Processing
Stateless and stateful processing, windows, joins, and Kafka Streams
A consumer that reads a topic, does something, and writes results to another topic is a stream processor. Simple ones are just consumers. The hard parts (state that survives crashes, time windows, joins between streams, reprocessing) are what stream processing frameworks exist for. The book's Stream Processing chapter and DDIA chapter 12 cover the theory in depth.
Stateless vs stateful
Stateless operations look at one record at a time: filter, map, reroute by field, mask a value. Any consumer can do them, and scaling is just more consumers in the group.
Stateful operations need memory of earlier records:
- Aggregations: orders per customer per hour, running revenue totals.
- Joins: enrich each order with the customer's current tier.
- Deduplication: drop events whose id was already seen.
- Pattern detection: three failed logins within a minute.
State must be partitioned the same way as the input (all of one customer's orders reach the same instance, which is why keys matter), and it must survive crashes.
Time and windows
Events carry an event time (when it happened) that differs from processing time (when you see it). Mobile clients go offline; a consumer replays yesterday's data. Correct results use event time.
| Window | Shape | Example |
|---|---|---|
| Tumbling | Fixed, non-overlapping | Orders per minute |
| Hopping | Fixed size, overlapping | 5-minute totals every minute |
| Sliding | Defined by the gap between events | Logins within 60 s of each other |
| Session | Activity separated by inactivity | A user's browsing session |
Late events arrive after their window seemingly closed. A processor keeps windows open for a grace period, then either drops later arrivals or emits a correction.
Kafka Streams
Kafka Streams is a Java library (not a cluster) for stateful stream processing on Kafka. Your app is a normal JVM service; Kafka Streams turns it into a consumer-group member with local state:
StreamsBuilder b = new StreamsBuilder();
KStream<String, Order> orders = b.stream("orders");
KTable<String, Customer> customers = b.table("cdc.public.customers"); // latest row per key
orders
.join(customers, (order, customer) -> order.withTier(customer.tier())) // stream-table join
.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(1), Duration.ofSeconds(30)))
.count()
.toStream()
.to("orders-per-customer-per-minute");How it keeps state safely:
A KTable built from a compacted CDC topic, like cdc.public.customers
from the Connect lesson,
is a live, local copy of a database table that a stream can join against
without querying the database. That pattern (CDC → table → join) is one
of the most useful things in the Kafka ecosystem.
Other options
| Tool | Model | When |
|---|---|---|
| Kafka Streams | Library in your JVM app | JVM shops; per-service processing |
| Apache Flink | Separate cluster, very capable | Large stateful jobs, complex event time, SQL |
| ksqlDB | SQL over Kafka topics | Simple transformations without code |
| Plain consumers | Your code | Stateless work, or simple state kept in Redis or Postgres |
| ClickHouse | Materialized views on a Kafka engine table | Analytics aggregations straight into OLAP |
Before reaching for a framework, ask whether the "state" can live in a
database the consumer writes to with upserts. A consumer that keeps
per-hour counts in Postgres with INSERT ... ON CONFLICT DO UPDATE,
committing offsets after each batch, is simple, debuggable, and
idempotent. Frameworks earn their complexity with joins, large state,
event-time windows, and exactly-once output to Kafka.
Lab
Write a Python consumer in labs/ that computes tumbling one-minute
counts of clicks per user from the clicks topic produced by lag.py:
- Use each record's timestamp (
msg.timestamp()[1]) as event time and bucket byts // 60000. - Keep counts in a dict keyed by
(user, window); emit a window's counts to aclicks-per-minutetopic once a record arrives that's more than 30 seconds past the window's end (your grace period). - Commit offsets only after emitting.
- Kill it mid-window and restart. Which counts are now wrong, and what would Kafka Streams' changelog have done differently?