Event-driven systems become particularly useful when we stop thinking of Kafka as simply a message broker and start treating streams of events as continuously changing datasets.
In this project, I built a small real-time analytics application using Spring Boot and Kafka Streams. The application consumes payment events, groups them by product, calculates daily sales statistics using event-time windows, stores the resulting state locally through Kafka Streams, and makes that state queryable through a REST API.
The interesting part is that there is no traditional database sitting between the stream processor and the API.
Kafka Streams maintains the aggregation as a materialized state store, and the Spring Boot application queries that state directly.
The processing flow looks conceptually like this: kafka-stream-topology.png This provides a good example of how Kafka Streams can serve both as a stream-processing engine and as the stateful computation layer behind an API.
The Event Model
The input to the application is a CartEvent. A simplified version looks like this:
public class CartEvent {
private String productId;
private String productName;
private BigDecimal amount;
private TransactionType transactionType;
private String paymentTransactionId;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
To make things simple, the transactions can currently have one of two types:
public enum TransactionType {
PURCHASE,
REFUND
}
For example, the stream might receive events conceptually equivalent to:
Laptop | PURCHASE | 1200
Laptop | PURCHASE | 1000
Phone | PURCHASE | 700
Laptop | REFUND | 1200
Phone | PURCHASE | 650
Instead of storing these events in a database and periodically running a query such as SUM(amount) GROUP BY product, the goal is to maintain those calculations continuously as events arrive.
Consuming the Event Stream
The Kafka Streams topology starts by consuming the configured payment analytics topic:
KStream<String, CartEvent> input = builder.stream(
paymentAnalyticsTopic,
Consumed.with(Serdes.String(), paymentEventSerde)
.withTimestampExtractor(new PaymentTimestampExtractor())
);
JSON SerDes are used to convert Kafka records into the Java domain objects.
.withTimestampExtractor(new PaymentTimestampExtractor())
This tells Kafka Streams which timestamp should determine when an event occurred.
Processing Time vs Event Time
For stream-processing systems, the distinction between processing time and event time matters. Processing time answers: when did my Kafka Streams application process this record/event? Event time answers: when did the business event actually happen?
The custom timestamp extractor uses createdAt from the event:
public class PaymentTimestampExtractor implements TimestampExtractor {
@Override
public long extract(
ConsumerRecord<Object, Object> record,
long partitionTime
) {
CartEvent evt = (CartEvent) record.value();
return evt != null
? Timestamp.valueOf(evt.getCreatedAt()).getTime()
: partitionTime;
}
}
This means that window assignment is based on when the payment was created rather than simply when Kafka Streams happened to process it. This becomes important when events are delayed or arrive out of order.
Re-Keying the Stream
To go deeper into this, we want the aggregation per product, Kafka Streams needs records belonging to the same aggregation key to reach the same logical processing partition. Changing the key is therefore not merely cosmetic. When followed by a key-based operation such as groupByKey(), Kafka Streams may need to repartition the records.
The next operation changes the Kafka record key:
KStream<String, CartEvent> byProduct = input
.selectKey((origKey, evt) -> evt.getProductName());
Conceptually:
Before selectKey():
payment-123 -> Laptop
payment-456 -> Phone
payment-789 -> Laptop
After selectKey():
Laptop -> payment-123
Phone -> payment-456
Laptop -> payment-789
Now all events for Laptop can participate in the same aggregation. Choosing the correct key is one of the most important design decisions in Kafka-based systems because it affects partitioning, ordering and stateful operations.
Creating Tumbling Windows
The application calculates statistics using a daily time window:
TimeWindows dailyWindow =
TimeWindows.ofSizeAndGrace(
Duration.ofDays(1),
Duration.ofMinutes(5)
);
This creates 24-hour tumbling windows with a five-minute grace period. A tumbling window is fixed-size and non-overlapping. Conceptually:
Day 1
|-------------------|
Day 2
|-------------------|
Day 3
|-------------------|
Each event belongs to one window according to its event timestamp. The grace period is also significant. We also have bear in mind, distributed systems do not guarantee that every event will arrive exactly when expected. Network delays, retries, consumer interruptions or upstream processing can cause records to arrive late. The grace period gives Kafka Streams additional time to accept late-arriving records for a window.
Stateful Aggregation
After re-keying, the stream is grouped and windowed:
KTable<Windowed<String>, StatsAccumulator> aggregated =
byProduct
.groupByKey(Grouped.with(Serdes.String(),paymentEventSerde))
.windowedBy(dailyWindow)
.aggregate(
StatsAccumulator::new,
this::aggregateEventIntoAccumulator,
Materialized.<String, StatsAccumulator,
WindowStore<Bytes, byte[]>>as(STORE_NAME)
.withKeySerde(Serdes.String())
.withValueSerde(accumulatorSerde)
);
There are several things happening here.
- First, events are grouped by product.
- Second, those groups are divided into daily windows.
- Third, Kafka Streams continuously maintains an aggregate for each combination of
product + time windowThe accumulator contains:
public class StatsAccumulator {
String productName;
long count = 0;
BigDecimal sum = BigDecimal.ZERO;
}
So Kafka Streams might internally maintain state conceptually like:
Laptop | 2026-09-01 | count=15 | sum=18500
Phone | 2026-09-01 | count=32 | sum=22400
Laptop | 2026-09-02 | count=4 | sum=5200
This is fundamentally different from repeatedly querying all historical events. The computation happens incrementally as the stream changes.
Handling Purchases and Refunds
The aggregation function treats purchases as positive transactions and refunds as negative transactions:
private StatsAccumulator aggregateEventIntoAccumulator(
String productId, CartEvent evt, StatsAccumulator acc) {
boolean isPurchase = TransactionType.PURCHASE.name()
.equalsIgnoreCase(evt.getTransactionType().name());
BigDecimal amount = isPurchase
? evt.getAmount()
: evt.getAmount().negate();
acc.setCount(isPurchase ? acc.getCount() + 1 : acc.getCount() - 1);
acc.setSum(acc.getSum().add(amount));
acc.setProductName(productId);
return acc;
}
For example:
PURCHASE €100
PURCHASE €200
REFUND €100
produces:
count = 1
sum = €200
The aggregate therefore represents the current net sales state for that product and window.
Materializing the Aggregation
One of the most useful parts of the topology is:
Materialized.<String, StatsAccumulator,
WindowStore<Bytes, byte[]>>as(STORE_NAME)
The aggregation is explicitly materialized as product-stats-store. This means the aggregation is not just an intermediate value flowing through the topology. It becomes queryable application state. Conceptually:
Kafka events
|
v
Stream processor
|
v
product-stats-store
+-------------------------+
Laptop -> daily stats
Phone -> daily stats
Tablet -> daily stats
+-------------------------+
Kafka Streams manages this state as part of the stream-processing application. This leads to another powerful Kafka Streams feature: Interactive Queries.
Querying Stream State from Spring Boot
The ProductStatsController retrieves the Kafka Streams instance managed by Spring: private final StreamsBuilderFactoryBean factoryBean;
It then obtains the materialized window store:
ReadOnlyWindowStore<String, StatsAccumulator> store = streams.store(
StoreQueryParameters.fromNameAndType(
PaymentStreamProcessorConfig.STORE_NAME,
QueryableStoreTypes.windowStore()
)
);
The REST layer can now query the results of the stream processor directly. For example: GET /api/stats/Laptop?from=<timestamp>&to=<timestamp> The controller executes:
store.fetch(
productName,
Instant.ofEpochMilli(from),
Instant.ofEpochMilli(to)
);
The result is therefore coming from the materialized Kafka Streams state rather than from a separate database query.
The application also supports retrieving aggregates across products for a time range: GET /api/stats/{from}/{to} using:
store.fetchAll(Instant.ofEpochMilli(from),Instant.ofEpochMilli(to));
This creates an interesting architecture:

The same computation can therefore feed downstream event-driven systems while also serving synchronous API queries.
Producing the Analytics Stream
The accumulated state is converted into DailyStats:
DailyStats ds = new DailyStats();
ds.setProductName(acc.getProductName());
ds.setWindowStart(windowedKey.window().start());
ds.setSum(acc.getSum().doubleValue());
ds.setAverage(acc.getSum()
.divide(
BigDecimal.valueOf(acc.getCount()),
RoundingMode.HALF_UP
).doubleValue()
);
The results are then written/published to: daily-product-sales-stats. This allows another service to consume the calculated statistics without having to know how they were produced. That separation is useful in event-driven architectures. One service can own the calculation while downstream consumers react only to the resulting events.
A Note About Suppression
Windowed aggregations introduce an important question:
Question:
Should downstream consumers receive every update, or only the final result when the window closes?
Kafka Streams provides the suppression API for this. The project defines a bounded strict buffer:
Suppressed.StrictBufferConfig strictBuffer = Suppressed.BufferConfig
.maxBytes(50 * 1024 * 1024L)
.shutDownWhenFull();
A topology requiring only final window results could apply:
aggregated.suppress(Suppressed.untilWindowCloses(strictBuffer));
There is an important operational trade-off here. shutDownWhenFull() preserves the strict final-results guarantee but stops the application if the suppression buffer exceeds its configured bound.
An eager strategy such as emitEarlyWhenFull() improves availability under memory pressure but may emit intermediate results. In the current version of this project, suppression is intentionally not enabled:
// .suppress(Suppressed.untilWindowCloses(strictBuffer))
Therefore the output stream receives updates as the aggregate changes. Therefore the output stream receives updates as the aggregate changes.
What This Project Demonstrates
Although this is a relatively small application, it demonstrates several important concepts that appear in larger event-streaming systems:
- Event-time processing — business timestamps determine when events belong.
- Partitioning and re-keying — events are reorganized according to the entity being aggregated.
- Windowing — an unbounded event stream is divided into finite periods.
- Late-event handling — grace periods account for events arriving after their expected time.
- Stateful processing — calculations are maintained incrementally rather than recomputed from scratch.
- Materialized state — stream-processing results become locally queryable state.
- Interactive Queries — synchronous APIs can expose the state maintained by an asynchronous stream processor.
- Derived event streams — calculated results can be published back to Kafka for other systems such as ClickHouse. Together, these concepts illustrate why Kafka Streams is more than an API for consuming and producing Kafka records. It allows us to model continuously evolving business state directly from event streams.
For a production-oriented version, there are several areas I would explore further.
- The first is exactly-once processing semantics, particularly when correctness of financial aggregates is important.
- The second is idempotency and duplicate transaction handling. A payment transaction ID is already part of the event model, and a production implementation should define what happens if the same transaction is received more than once.
- Another area is interactive queries across multiple application instances. A local Kafka Streams state store contains only the state assigned to that instance. Once the application is horizontally scaled, the API needs a strategy for locating the instance that owns a particular key.
- Other useful extensions include schema management with Avro or Protobuf and Schema Registry, better invalid-event handling, observability, integration tests using Kafka Streams’ testing facilities, and additional window types such as hopping or sliding windows.
Final Thoughts
In a traditional analytics workflow, we might:
Store events -> Query database -> Calculate result
With Kafka Streams, we can instead think in terms of:
Events -> Continuously update state -> Query the current result
The stream itself becomes the source of the computation, while Kafka Streams maintains the derived state required by the application. That model is useful far beyond product sales.
The same principles can be applied to fraud detection, transaction monitoring, IoT telemetry, user activity analytics, campaign metrics, logistics, operational monitoring and many other systems where information needs to be derived continuously from events. And that is where event streaming becomes much more interesting than simply sending messages between services.