Learn Labs
Connect & Stream Processing

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.

WindowShapeExample
TumblingFixed, non-overlappingOrders per minute
HoppingFixed size, overlapping5-minute totals every minute
SlidingDefined by the gap between eventsLogins within 60 s of each other
SessionActivity separated by inactivityA 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:

state storelocal RocksDB per partition, for fast reads and writeschangelog topicevery state change is also written to a compacted Kafka topicrestorea new instance rebuilds the store by replaying the changelogprocessing.guarantee=exactly_once_v2uses transactions: output, state changelog, and offsets commit together

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

ToolModelWhen
Kafka StreamsLibrary in your JVM appJVM shops; per-service processing
Apache FlinkSeparate cluster, very capableLarge stateful jobs, complex event time, SQL
ksqlDBSQL over Kafka topicsSimple transformations without code
Plain consumersYour codeStateless work, or simple state kept in Redis or Postgres
ClickHouseMaterialized views on a Kafka engine tableAnalytics aggregations straight into OLAP

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:

  1. Use each record's timestamp (msg.timestamp()[1]) as event time and bucket by ts // 60000.
  2. Keep counts in a dict keyed by (user, window); emit a window's counts to a clicks-per-minute topic once a record arrives that's more than 30 seconds past the window's end (your grace period).
  3. Commit offsets only after emitting.
  4. Kill it mid-window and restart. Which counts are now wrong, and what would Kafka Streams' changelog have done differently?

On this page