What you'll learn: By the end of this lesson you will be able to explain what a stream processor does that a batch job does not, tell stateless operations from stateful ones and say where the state lives, describe how a tumbling window with a grace period decides which records it accepts, predict what happens to a late event, choose between emitting every update and emitting only a final result, and read all of it off a deterministic trace produced by a Kafka Streams lab.
Picture two ways to know how many parcels each postcode received today. In the first, you wait until the evening, take the whole day's paperwork and count. In the second, a board by the conveyor belt shows a tally for each postcode that ticks up as every parcel passes. The board is always current, but it has problems the evening count never had: a parcel scanned late at the depot appears after the board has moved on, and you must decide what "today" means when the clock on the wall and the time on the label disagree.
Stream processing is the second way. This lesson takes the smallest useful set of ideas, a topology, state, windows and time, and runs them on a lab you can read. It builds on event streaming and message queues; the lesson on Kafka internals (partitions, offsets and consumer groups) and the lesson on delivery guarantees are named here in plain text only.
Verified with Java 25, Apache Kafka Streams 4.2.2 (and kafka-streams-test-utils 4.2.2) and the Apache Kafka 4.2 documentation, on 2026-12-01.
The core idea
A stream processor is a program that reads an unbounded sequence of records, applies a graph of processing steps to each one as it arrives, and writes results back out. Steps that look only at the current record are stateless. Steps that need to remember earlier records keep state in a store. Windows cut the endless stream into finite buckets of time, and because records can arrive out of order, a window needs a rule for how long to wait: the grace period.
Three illustrations run through the lesson:
- Minimal example: order events through a filter and a map, then a running count, from the Java lab.
- Realistic example: ShopStream counts paid orders per store per five minutes, in "In practice".
- Failure example: a late event that arrives after its window has closed and is dropped.
Batch and stream, side by side
| Batch job | Stream processor | |
|---|---|---|
| Input | A bounded set, known in advance | An unbounded sequence that never ends |
| When it answers | After all the input is read | Continuously, as records arrive |
| State | Rebuilt on each run | Kept between records |
| Late data | Part of the input, or the next run | Must be handled by a rule |
| Result | One final answer | A stream of updates, possibly refined later |
The Kafka documentation describes a stream as "an unbounded, continuously updating data set" and a stream processor as "a processing step to transform data in streams". A topology is "a graph of stream processors (nodes) that are connected by streams (edges)".
A topology, tasks and state
Kafka Streams is, in the documentation's words, "a client library for processing and analyzing data stored in Kafka", and it "is not a resource manager, but a library": it runs inside your own application and builds on the Kafka producer and consumer. The pieces to know are few.
- Topology. The graph of steps: a source reads a topic, processors transform, a sink writes a topic.
- Tasks. "Kafka Streams creates a fixed number of tasks based on the input stream partitions for the application", and the assignment of partitions to tasks never changes, so each task is a fixed unit of parallelism.
- State stores. "Every task in Kafka Streams embeds one or more state stores that can be accessed via APIs to store and query data required for processing."
- Changelog topics. For each state store, the library "maintains a replicated changelog Kafka topic in which it tracks any state updates", which is how state is restored after a failure.
Figure 1. The lab's counting topology. How to read this: records flow left to right through two stateless steps, then go through a repartition topic because the key changed, then into a stateful count that reads and updates its state store and emits every new total. The repartition step is explained in the next section and appears in the lab's own topology printout.
Stateless operations
A stateless step decides about a record using only that record. The two workhorses are filter and map. The Kafka DSL guide describes filter as one that "evaluates a boolean function for each element and retains those for which the function returns true". Nothing is remembered: delete the process and restart it, and the next record is handled identically.
Both operations are in the lab. The input is an order event with the order ID as its key and store|status|cents as its value. The first chain keeps PAID events and re-keys each one by store, keeping only the amount. The documentation gives one warning about map: because it can change the key, a grouping or join after it triggers re-partitioning, and "mapValues is preferable to map because it will not cause data re-partitioning". Re-keying is sometimes the whole point, as here, but it costs an extra topic.
Expected output, captured from a real run (Kafka Streams 4.2.2, Java 25, 2026-12-01):
Part 1. Stateless: filter (status = PAID) then map (re-key by store, keep the amount).
Input key = order id, value = store|status|cents. Output topic: paid-by-store
in 10:00:10 o1 s1 PAID 500 out s1 -> 500
in 10:00:20 o2 s2 PAID 800 out s2 -> 800
in 10:00:30 o3 s1 CREATED 500 out (nothing)
in 10:00:40 o4 s1 PAID 700 out s1 -> 700
in 10:00:50 o5 s2 PAID 100 out s2 -> 100
The CREATED event produces nothing; the other four come out with the store as the key.
Stateful operations and the table view
A stateful step has to remember. groupByKey().count() is the classic: for each store it keeps a number, and each paid order raises it by one. The DSL guide describes it as one that "counts the number of records by the grouped key". The number lives in a named state store, so it survives between records, and in the changelog topic, so it survives a restart.
The output of a count is not one number per key. It is a table that changes over time, and the stream of its changes is what leaves the topology. That is the stream-table duality the documentation names: "a stream can be viewed as a table, and a table can be viewed as a stream". Every paid order produces one update for its key, and the latest update per key is the table.
The printout below is the topology the DSL built for the counting chain, from Topology.describe(). The map changed the key, so before grouping the DSL inserted a repartition sink and source, which is why there are two sub-topologies.
Expected output, captured from a real run (Kafka Streams 4.2.2, Java 25, 2026-12-01):
Topologies:
Sub-topology: 0
Source: KSTREAM-SOURCE-0000000000 (topics: [orders])
--> KSTREAM-FILTER-0000000001
Processor: KSTREAM-FILTER-0000000001 (stores: [])
--> KSTREAM-MAP-0000000002
<-- KSTREAM-SOURCE-0000000000
Processor: KSTREAM-MAP-0000000002 (stores: [])
--> paid-count-store-repartition-filter
<-- KSTREAM-FILTER-0000000001
Processor: paid-count-store-repartition-filter (stores: [])
--> paid-count-store-repartition-sink
<-- KSTREAM-MAP-0000000002
Sink: paid-count-store-repartition-sink (topic: paid-count-store-repartition)
<-- paid-count-store-repartition-filter
Sub-topology: 1
Source: paid-count-store-repartition-source (topics: [paid-count-store-repartition])
--> KSTREAM-AGGREGATE-0000000003
Processor: KSTREAM-AGGREGATE-0000000003 (stores: [paid-count-store])
--> KTABLE-TOSTREAM-0000000007
<-- paid-count-store-repartition-source
Processor: KTABLE-TOSTREAM-0000000007 (stores: [])
--> KSTREAM-SINK-0000000008
<-- KSTREAM-AGGREGATE-0000000003
Sink: KSTREAM-SINK-0000000008 (topic: paid-count-by-store)
<-- KTABLE-TOSTREAM-0000000007
Then the same five events through that topology, with the state store read at the end:
Expected output, captured from a real run (Kafka Streams 4.2.2, Java 25, 2026-12-01):
in 10:00:10 o1 s1 PAID 500 out s1 = 1
in 10:00:20 o2 s2 PAID 800 out s2 = 1
in 10:00:30 o3 s1 CREATED 500 out (nothing)
in 10:00:40 o4 s1 PAID 700 out s1 = 2
in 10:00:50 o5 s2 PAID 100 out s2 = 2
state store paid-count-store now holds:
s1 = 2
s2 = 2
Every input produced at most one update. The third event is filtered out and so changes nothing. The store holds s1 = 2 and s2 = 2, the table the updates describe.
One setting hides this in real deployments. Kafka Streams has record caches, "enabled by default", and with caching on, intermediate updates for the same key can be merged, so a consumer may see a key jump from one value to a later one. The DSL guide says to disable the caches only "for testing or debugging purposes", and the lab does exactly that, with statestore.cache.max.bytes set to 0, so every update shows. The setting's default is 10485760 bytes.
Time: three clocks and stream time
Windows need a clock, and there are three to choose from. The documentation defines event time as the point "when an event or data record occurred, i.e. was originally created at the source", processing time as when the record "happens to be processed by the stream processing application", and ingestion time as when it "is stored in a topic partition by a Kafka broker". Event time is the one that gives the same answer when you replay the same data, which is why the lab uses it: each input carries its own timestamp.
Kafka Streams also keeps stream time: "We call this data-driven time the stream time of the application." The page adds that "this time will only advance when a new record arrives at the processor." That sentence explains most surprises. Stream time is the clock the windows use, and it moves only when a record arrives, so a quiet topic freezes it.
Windows and the grace period
A window groups records by time. The simplest is a tumbling window, "a hopping window whose window size is equal to its advance interval": fixed-size, no overlap, no gaps. The lab uses five-minute windows, so an order at 10:03 belongs to the window from 10:00 to 10:05, and one at 10:05:30 to the window from 10:05 to 10:10.
Records arrive out of order in the real world, so a window cannot close at its end time; a late record would have nowhere to go. The grace period is how long the window keeps accepting them. The documentation's own example is a window from 09:00 to 10:00 with a 10-minute grace period: it "will accept out-of-order records until 10:10, at which point, the window is closed". The rule for the late record is explicit: a record is discarded when its timestamp belongs to a window and "the current stream time is greater than the end of the window plus the grace period", and then "the record is discarded and will not be processed in that window."
Figure 2. The window lifecycle. How to read this: time on this diagram is stream time, not the wall clock, so each transition is triggered by a record that moves stream time forward. The two self-loops on the right are the difference the lab shows: a late record is counted while the window is still accepting, and dropped once it is closed.
Late events, three ways
For every record, the processor asks one question, shown below, and the three variants of the lab differ only in the answer.
Figure 3. The decision for each record. How to read this: the diamond is the late test from the documentation. The drop path ends in a counter and nothing else, which is why a closed window loses data silently unless the counter is watched.
The lab feeds six paid orders for one store through the same windowed count three times. The arrivals are out of order on purpose: the record stamped 10:04:00 arrives after one stamped 10:05:30, which makes it 90 seconds late, and the record stamped 10:02:00 arrives last, after stream time has reached 10:07.
| Arrival | Event time | Window | What it tests |
|---|---|---|---|
| 1 | 10:01:00 | 10:00 to 10:05 | normal |
| 2 | 10:03:00 | 10:00 to 10:05 | normal |
| 3 | 10:05:30 | 10:05 to 10:10 | moves stream time to 10:05:30 |
| 4 | 10:04:00 | 10:00 to 10:05 | late by 90 seconds |
| 5 | 10:07:00 | 10:05 to 10:10 | moves stream time to 10:07 |
| 6 | 10:02:00 | 10:00 to 10:05 | very late |
Expected output, captured from a real run (Kafka Streams 4.2.2, Java 25, 2026-12-01):
Variant A: grace period 0, every update emitted
in 10:01:00 o1 s1 PAID 500 out s1 [10:00-10:05) = 1 [records dropped so far: 0]
in 10:03:00 o2 s1 PAID 700 out s1 [10:00-10:05) = 2 [records dropped so far: 0]
in 10:05:30 o3 s1 PAID 300 out s1 [10:05-10:10) = 1 [records dropped so far: 0]
in 10:04:00 o4 s1 PAID 900 out (nothing) [records dropped so far: 1]
in 10:07:00 o5 s1 PAID 400 out s1 [10:05-10:10) = 2 [records dropped so far: 1]
in 10:02:00 o6 s1 PAID 600 out (nothing) [records dropped so far: 2]
With no grace period, window 10:00 to 10:05 is closed as soon as stream time passes 10:05, so arrival 4 is dropped: the window stays at 2 although three orders belong to it. The dropped counter reads 1, then 2 after arrival 6. The counter is the task metric dropped-records-total, "the total number of records dropped within this task", and it is the first thing to graph.
Expected output, captured from a real run (Kafka Streams 4.2.2, Java 25, 2026-12-01):
Variant B: grace period 1 minute, every update emitted
in 10:01:00 o1 s1 PAID 500 out s1 [10:00-10:05) = 1 [records dropped so far: 0]
in 10:03:00 o2 s1 PAID 700 out s1 [10:00-10:05) = 2 [records dropped so far: 0]
in 10:05:30 o3 s1 PAID 300 out s1 [10:05-10:10) = 1 [records dropped so far: 0]
in 10:04:00 o4 s1 PAID 900 out s1 [10:00-10:05) = 3 [records dropped so far: 0]
in 10:07:00 o5 s1 PAID 400 out s1 [10:05-10:10) = 2 [records dropped so far: 0]
in 10:02:00 o6 s1 PAID 600 out (nothing) [records dropped so far: 1]
With a one-minute grace period the window stays open until stream time passes 10:06. Arrival 4 is counted and the window is revised from 2 to 3: the output is a correction of an earlier answer. Arrival 6 comes when stream time is 10:07, past 10:06, and is dropped. One minute of grace bought one extra order and cost a revision downstream.
The third variant answers a different question: what if consumers cannot cope with revisions? The DSL guide notes that "windowed computations update their results continuously", and that suppress(Suppressed.untilWindowCloses(...)) makes the operator "emit nothing for a window until it closes, and then emit the final result".
Expected output, captured from a real run (Kafka Streams 4.2.2, Java 25, 2026-12-01):
Variant C: grace period 1 minute, suppress(untilWindowCloses): only final results
in 10:01:00 o1 s1 PAID 500 out (nothing) [records dropped so far: 0]
in 10:03:00 o2 s1 PAID 700 out (nothing) [records dropped so far: 0]
in 10:05:30 o3 s1 PAID 300 out (nothing) [records dropped so far: 0]
in 10:04:00 o4 s1 PAID 900 out (nothing) [records dropped so far: 0]
in 10:07:00 o5 s1 PAID 400 out s1 [10:00-10:05) = 3 [records dropped so far: 0]
in 10:02:00 o6 s1 PAID 600 out (nothing) [records dropped so far: 1]
Nothing is emitted for four arrivals, then window 10:00 to 10:05 appears once with its final value 3, at the moment arrival 5 pushes stream time past 10:06. The window from 10:05 to 10:10 is never emitted in this run, because stream time never reached 10:11. That is the cost of finality: the answer waits for the next record, and a topic that goes quiet holds its last window forever.
Build it: a traced Kafka Streams lab
This is the minimal example, a model you can run. It uses TopologyTestDriver, not a broker. The Kafka documentation says the test-utils package "provides a TopologyTestDriver that can be used pipe data through a Topology", and that it "simulates the library runtime that continuously fetches records from input topics". It runs the real DSL topology, state store and windowing code in-process, so there is no cluster, no consumer group, no rebalance and no network. A lab on a real broker would need Docker, which this course's labs avoid.
Goal. Watch each operation turn input records into output records, and see grace periods and suppress change the result for the same events.
Setup. From the repository's examples/spring-labs folder:
cd examples/spring-labs && ./gradlew :labs:stream-processing-basics:test
The run executes 7 tests and compares a trace with examples/spring-labs/golden/stream-processing-basics.txt. The topologies are in examples/spring-labs/labs/stream-processing-basics/src/main/java/buildingai/labs/streams/OrderTopologies.java; the trace is rendered by StreamsReport in the test sources, because kafka-streams-test-utils is a test dependency.
How the model works. Each input is one pipeInput call with an explicit timestamp, and the trace prints what that single input made the topology emit. The windowed topology differs in one argument:
.windowedBy(TimeWindows.ofSizeAndGrace(WINDOW, grace))
.count();
The suppressed variant adds suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded())) before toStream().
Steps. Run the tests, read the five outputs above in order, then change the grace period in OrderTopologies and predict the trace before you run it. The tests assert the same behaviour the trace shows: the stateless output, the running counts and the store contents, the three windowed variants, and that the very late order is counted as dropped.
Break it. In OrderTopologies.windowedCount, replace TimeWindows.ofSizeAndGrace(WINDOW, grace) with TimeWindows.ofSizeWithNoGrace(WINDOW). The tests zeroGraceDropsTheLateOrderAndAMinuteOfGraceAcceptsIt and suppressEmitsOnlyTheFinalCountOfAClosedWindow and the golden comparison fail, because the one-minute variants no longer accept arrival 4. Restore the line and run the tests again.
Stretch. Feed events for two stores and see whether one store's late event is judged against the other store's records. Add a second input partition. Replace count with a sum of amounts.
What the model leaves out. A real broker and consumer group, partitions and their assignment to tasks, rebalances, the changelog topic's actual content, restoring state after a crash, exactly-once processing, joins, session and sliding windows, wall-clock punctuation, and throughput of any kind.
Choosing the knobs: the trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| Grace period 0 | Lowest delay, smallest state | Any out-of-order record for a closed window is dropped | Producers or networks reorder by more than the window |
| Longer grace | Fewer drops | Revisions arrive later, windows stay open longer, more state is held | Consumers cannot handle a corrected number |
| Emit every update | Freshest answer, simple | Downstream sees revisions, more traffic | The sink cannot upsert |
suppress(untilWindowCloses) |
One final result per window | Delay of window plus grace; needs a later record to close; buffers in memory | You need live numbers or the topic may go quiet |
| Smaller windows | Finer answers | More windows and more state | The business question is hourly |
Re-key with map |
Lets you group by another key | A repartition topic and extra traffic | A mapValues would do |
In practice: ShopStream counts paid orders per store per five minutes
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Every number is illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's stage 7 adds an operations screen: for each store, how many paid orders arrived in each five-minute slot, so the support team can see a store going quiet. The order events already flow through a topic. The numbers do not need to be perfect to the second, but a store showing zero orders when it is busy will trigger a wrong phone call.
Starting architecture
Figure 4. The path from an order to the screen. How to read this: the processor reads the topic, keeps a count per store and window, and writes counts to another topic that the screen reads. The metrics box is not decoration: the drop counter is how the team learns that a window closed before an order arrived.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
| A. Grace 0, emit every update | Fastest | Mobile clients that reconnect after a dead zone send orders minutes late, and those are dropped |
| B. Grace a few minutes, emit every update | Late orders are counted and the screen corrects itself | Numbers revise; the screen must replace, not add |
| C. Grace a few minutes plus suppress | One final number per window | Screen delay of window plus grace; an idle store's last window may not appear until another record arrives |
| D. Streaming for the live view, batch for the truth | Fast approximation plus a corrected nightly count | Two code paths to keep consistent |
The decision
Option B with option D behind it. The screen replaces the number for a (store, window) pair, so a revision is harmless, and the grace period is set from what the team can measure: the observed lateness of events, which Kafka Streams reports as the task metric record-lateness-avg, "the average observed lateness in ms of records (stream time - record timestamp)". The nightly batch count is the record of truth, and the streaming number is documented as "may be corrected for a few minutes".
Rollout and verification
Rollout starts in shadow: the processor runs beside the existing report for a week, and the team compares counts per store and window. Verification checks the three things the lab trace exposes: the drop counter should stay near zero, windows should emit revisions only inside the grace period, and the sum of window counts should match the batch count within a small tolerance the team writes down in advance.
The 2 a.m. failure
The page reads: the operations screen shows zero orders for a group of stores for the last hour, but the stores are calling in orders. The stores' devices lost connectivity during a regional network issue and queued their orders; when the network returned they sent an hour of orders at once, with their original timestamps. Stream time had moved on, every window for that hour was already closed, and the processor dropped the records, exactly as in variant A of the lab. The drop counter is the signal.
The checks: look at dropped-records-total for the task, compare the timestamps of the dropped orders with stream time, and confirm that the batch count shows the orders. The mitigation is to reprocess the affected period from the topic with a larger grace period, or simply publish the corrected figure from the batch job. The lasting fix is an alert on the drop counter, a grace period derived from measured lateness, and a note on the screen that live numbers can be revised.
Architect's notes
- Ask what time means first. Event time makes replays reproducible; processing time is easier and wrong as soon as anything is delayed.
- Write down the lateness you accept. The grace period is a business decision about how late is too late, not a tuning number.
- Alert on dropped records. A closed window drops late records without an error; the metric is the only trace.
- Choose updates or finality deliberately. Updates are fresh and revised;
suppressis final and waits for the next record. - Prefer
mapValuesunless the key must change. Every key change is a repartition topic. - Remember the default guarantee.
processing.guaranteedefaults toat_least_once; the delivery guarantees lesson covers what that means for a count. - Check the version. Defaults such as the cache size and the available window types are documented per release.
Common mistakes
- Using processing time and calling the result reproducible. A replay produces different windows.
- Assuming a window closes at its end time. It closes when stream time passes the end plus the grace period.
- Expecting stream time to follow the wall clock. It advances only when a record arrives, so an idle partition freezes it.
- Reading the output as one number per key. It is a stream of updates; the table is the latest per key.
- Forgetting that
suppressneeds a later record. The last window of a quiet topic does not emit. - Never looking at the drop counter. A zero on a dashboard can be a window that closed early.
- Testing with the record cache on and being surprised. Intermediate updates can be merged, and the DSL guide advises disabling caches only for tests and debugging.
Key takeaways
- A stream processor is a topology of steps over an unbounded input; the result is a continuously updated output.
- Stateless steps (
filter,map) look at one record; stateful steps (count) keep state in a store backed by a changelog topic. - A count's output is a changelog of a table: one update per input, the latest per key is the answer.
- Windows are driven by stream time, which moves only when records arrive.
- A window accepts records until stream time passes its end plus the grace period; after that, late records are dropped and counted.
- Grace buys completeness and costs delay and revisions;
suppresstrades freshness for a single final value.
Practice exercises
Exercise 1 (20 min). For the six arrivals in the table, work out by hand which window each belongs to and whether it is dropped under a 2-minute grace period. Then check by changing grace in the lab.
Exercise 2 (45 min). Run the lab. Add a second store with its own late event and predict the trace. Say whether one store's records can close the other's windows, and confirm it with the trace.
Exercise 3 (1 hour). Run "Break it". Then switch the count to a sum of cents and compare the three variants.
Exercise 4 (2 hours). For ShopStream's courier locations, stock changes and checkout events, decide the window type, size, grace period and whether to suppress, and say what a dropped record costs in each.
Related reading
- Event Streaming: topics, partitions and consumer groups.
- Message Queues: queues compared with logs.
- Idempotent and Commutative Operations: why updates that can be applied twice matter for at-least-once.
- Backpressure: what a slow processor does to a fast producer.
- Data Warehouses and Lakes: where the batch count of truth usually lives.
Official documentation
- Apache Kafka 4.2, Streams core concepts: streams, topologies, time, windows, grace period and state.
- Apache Kafka 4.2, Streams DSL:
filter,map,count, windowing and final results withsuppress. - Apache Kafka 4.2, Streams architecture: tasks, threads, state stores and changelog topics.
- Apache Kafka 4.2, Testing a Streams application:
TopologyTestDriver. - Apache Kafka 4.2, Streams configuration and monitoring: the cache setting and the task metrics.