KStream, KTable, Windowing and Joins in Kafka Streams
KStream, KTable, windowing and joins are the tools that turn Kafka Streams from a simple record-by-record processor into a real stream-processing engine. They let you count events per minute, detect sessions of user activity, enrich orders with customer data and match payments to orders, all inside a normal Java application.
This tutorial builds on the Kafka Streams introduction. It explains the stream–table duality, how event time drives windows, the four window types, how late records and grace periods work, and how each join type behaves, with Java and Spring Boot examples.
1. Streams and Tables: Two Views of the Same Data
A KStream is an unbounded sequence of independent facts: every record is a new event, such as “customer 7 viewed product 42”. A KTable is the latest value per key: every record is an update (an upsert) of that key, and a record with a null value deletes the key. This is the stream–table duality:
- Replaying a stream of changes from the beginning rebuilds the table (that is how a KTable is restored from its changelog topic).
- Capturing every change of a table produces a stream (
KTable.toStream()).
Records for key alice | Read as a KStream | Read as a KTable |
|---|---|---|
(alice, 3), then (alice, 5) | Two events; a sum is 8 | One row whose current value is 5 |
(alice, null) | Ignored by most operations | Deletes the row (tombstone) |
Aggregations connect the two: stream.groupByKey().count() returns a KTable, and table.toStream() turns its updates back into a stream. A third abstraction, GlobalKTable, holds a full copy of a (usually small) table on every application instance.
2. Event Time and Stream Time
Windows and stream–stream joins are based on record timestamps, not on the clock of the machine. By default the timestamp is the one stored in the Kafka record, which the producer sets to the event’s creation time unless the topic uses message.timestamp.type=LogAppendTime. A custom TimestampExtractor can read the time from the payload instead.
Each task tracks stream time: the highest record timestamp it has seen so far. Stream time only moves forward when new records arrive, and it is what closes windows. That has an important consequence: if no new records arrive on a partition, its windows are not closed and final results are not emitted, even if hours of wall-clock time pass.
3. The Four Window Types
| Window | Defined by | Overlap | DSL | Typical use |
|---|---|---|---|---|
| Tumbling | Size | No; each record in exactly one window | TimeWindows.ofSizeWithNoGrace(size) | Orders per minute, errors per hour |
| Hopping | Size and advance (hop) | Yes, when advance < size | TimeWindows.ofSizeAndGrace(size, grace).advanceBy(hop) | “Last 10 minutes, updated every minute” dashboards |
| Sliding | Maximum time difference between records | Yes; windows are created by the records themselves | SlidingWindows.ofTimeDifferenceAndGrace(diff, grace) | “More than 5 failed logins within 2 minutes” |
| Session | Inactivity gap | No; sessions of one key can merge | SessionWindows.ofInactivityGapWithNoGrace(gap) | User visits, device activity periods |
A windowed aggregation returns a KTable<Windowed<K>, V>: the key carries both the original key and the window’s start and end.
4. Late Records, Grace Periods and Final Results
Records do not always arrive in timestamp order: a phone may buffer events while offline, or a producer may retry. A record is late when its timestamp falls into a window whose end has already been passed by stream time. The grace period decides how long a window stays open for late records:
- Within the grace period, the late record is added and an updated result is emitted.
- After window end plus grace, the window is closed and late records for it are dropped (and counted in the
dropped-recordsmetric).
The ...WithNoGrace factory methods use a grace period of zero; ...AndGrace lets you choose one. A longer grace period tolerates more disorder but keeps more state and delays final results.
By default a windowed aggregation emits an updated result for every input record (reduced somewhat by the record cache). If downstream systems need exactly one final result per window, for example to send one alert, use suppress:
views.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(5), Duration.ofMinutes(1)))
.count()
.suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
.toStream(); // one record per key and window, emitted after end + grace
5. Join Types and How They Behave
All joins except KStream–GlobalKTable are based on the record key, and the inputs must be co-partitioned: the same number of partitions and the same partitioning of keys. If the keys differ, re-key first with selectKey() or map(); Kafka Streams then repartitions automatically.
| Join | Windowed? | What triggers output | Variants | Typical use |
|---|---|---|---|---|
| KStream–KStream | Yes, JoinWindows | A new record on either side that finds a match within the time difference | inner, left, outer | Match a payment to an order that happened within 10 minutes |
| KStream–KTable | No | Only new stream records; table updates just change the lookup state | inner, left | Enrich each order with the current customer data |
| KStream–GlobalKTable | No | Only new stream records | inner, left | Enrich with small reference data without co-partitioning; a key mapper picks the table key |
| KTable–KTable | No | An update on either side | inner, left, outer | Combine two current views, such as account and balance |
| KTable–KTable foreign-key | No | An update on either side | inner, left | Join order rows to the customer row they reference, when keys differ |
null (left join) or dropped (inner join); the later customer record does not re-trigger it. Make sure reference data is loaded first, or use a versioned table store so the join looks up the table version valid at the record’s timestamp.6. Example: Windowed Counts and an Enrichment Join
The topology below counts page views per product in 5-minute tumbling windows with 1 minute of grace, and enriches each order with the customer’s current loyalty tier from a customers table:
package com.javabytechie.streams;
import java.time.Duration;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.*;
public class ShopTopology {
public static StreamsBuilder build() {
StreamsBuilder builder = new StreamsBuilder();
// 1. Windowed count: key = productId, value = viewing user
KStream<String, String> views = builder.stream("product-views",
Consumed.with(Serdes.String(), Serdes.String()));
views.groupByKey()
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(5), Duration.ofMinutes(1)))
.count(Materialized.as("views-per-5min"))
.toStream()
.map((windowed, count) -> KeyValue.pair(
windowed.key() + "@" + windowed.window().startTime(), count))
.to("product-view-counts", Produced.with(Serdes.String(), Serdes.Long()));
// 2. Enrichment: orders keyed by customerId, customers table keyed by customerId
KTable<String, String> customerTier = builder.table("customer-tiers",
Consumed.with(Serdes.String(), Serdes.String()));
KStream<String, String> orders = builder.stream("orders-by-customer",
Consumed.with(Serdes.String(), Serdes.String()));
orders.leftJoin(customerTier,
(order, tier) -> order + ",tier=" + (tier == null ? "STANDARD" : tier))
.to("orders-enriched", Produced.with(Serdes.String(), Serdes.String()));
return builder;
}
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "shop-analytics");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
KafkaStreams streams = new KafkaStreams(build().build(), props);
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
streams.start();
}
}
With these input records on customer-tiers and orders-by-customer:
customer-tiers c7 -> GOLD
orders-by-customer c7 -> order=o-501,amount=120
orders-by-customer c9 -> order=o-502,amount=40
orders-enriched c7 -> order=o-501,amount=120,tier=GOLD
orders-enriched c9 -> order=o-502,amount=40,tier=STANDARD
Customer c9 has no row in the table, so the left join supplies null and the joiner falls back to STANDARD. An inner join would have dropped that order.
7. Example: Matching Payments to Orders
A KStream–KStream join pairs records from two streams whose timestamps are close. Here, a payment counts only if it arrives within 10 minutes after or before the order (both streams keyed by order ID):
KStream<String, String> orders = builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String()));
KStream<String, String> payments = builder.stream("payments", Consumed.with(Serdes.String(), Serdes.String()));
orders.join(payments,
(order, payment) -> "PAID " + order + " / " + payment,
JoinWindows.ofTimeDifferenceAndGrace(Duration.ofMinutes(10), Duration.ofMinutes(2)),
StreamJoined.with(Serdes.String(), Serdes.String(), Serdes.String()))
.to("orders-paid");
Both sides are buffered in window stores for the length of the join window plus grace, so a long join window means a lot of state. To find orders that were not paid in time, use a left join and look for results whose right side is null after the window closes.
8. Running the Topology in Spring Boot
Spring for Apache Kafka manages the KafkaStreams lifecycle for you. Add kafka-streams to the classpath, annotate a configuration class with @EnableKafkaStreams, and define the topology on the injected StreamsBuilder; Spring Boot creates the streams configuration from properties:
spring:
kafka:
bootstrap-servers: localhost:9092
streams:
application-id: shop-analytics
properties:
processing.guarantee: exactly_once_v2
default.key.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
default.value.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
@Configuration
@EnableKafkaStreams
public class ShopStreamsConfig {
@Bean
public KStream<String, String> enrichedOrders(StreamsBuilder builder) {
KTable<String, String> tiers = builder.table("customer-tiers");
KStream<String, String> orders = builder.stream("orders-by-customer");
KStream<String, String> enriched = orders.leftJoin(tiers,
(order, tier) -> order + ",tier=" + (tier == null ? "STANDARD" : tier));
enriched.to("orders-enriched");
return enriched;
}
}
9. Important Configuration
| Setting | Default | Why it matters here |
|---|---|---|
processing.guarantee | at_least_once | Use exactly_once_v2 when duplicate window counts or join results are not acceptable |
commit.interval.ms | 30000 (100 with exactly-once) | Together with the cache, controls how often updated results are flushed downstream |
statestore.cache.max.bytes | 10485760 (10 MiB) | Record cache that combines several updates of the same key before emitting; 0 shows every update |
Materialized.withRetention(...) | Window size plus grace period | How long windowed results stay queryable in the window store; set it longer if interactive queries must read older windows |
| Grace period | Zero with ...WithNoGrace | How much out-of-order data is accepted before a window closes |
10. Common Mistakes
- Using no grace period with out-of-order data. Late records are silently dropped; watch the
dropped-recordsmetric. - Expecting final results without
suppress. A windowed count emits intermediate updates; a downstream alerting service then fires several times per window. - Waiting for a window to close on an idle partition. Stream time advances only with new records, so final results never come if traffic stops.
- Joining topics that are not co-partitioned. Different partition counts make Kafka Streams fail at startup; different partitioners produce wrong or missing matches.
- Loading reference data after the stream. In a KStream–KTable join, stream records that arrive before their table row are not joined later.
- Very long KStream–KStream join windows. Both sides are kept in state for the whole window, which can grow the state stores and restore times dramatically.
11. Best Practices
- Make timestamps meaningful: set event time at the producer, or extract it from the payload.
- Choose the grace period from data: measure how late records really arrive, then add a margin.
- Name your stores and operators (
Materialized.as,Named.as) so changelog topics stay stable when the topology changes. - Use GlobalKTable only for small, slowly changing data; every instance stores all of it.
- Test topologies with
TopologyTestDriver, which lets you control record timestamps and assert window results without a broker.
12. Summary
A KStream is a sequence of facts and a KTable is the latest value per key; aggregations turn streams into tables and toStream() turns them back. Windows group records by event time: tumbling and hopping by fixed intervals, sliding by distance between records, and sessions by gaps in activity. Grace periods decide how late data is handled, and suppress emits one final result per window. Joins are key-based and need co-partitioned inputs, except with a GlobalKTable; only KStream–KStream joins are windowed, and in KStream–KTable joins only the stream side triggers output.
13. Related Reading
- Kafka Streams: topologies, tasks and the basics of the DSL
- Kafka Streams state stores: where window and join state is kept
- Event sourcing and CQRS: building read models with KTables
- Kafka partitions: why co-partitioning depends on keys and partition counts
14. References
Kafka Streams Windowing and Joins Interview Questions and Answers
Common interview questions on Kafka Streams Windowing and Joins, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is the stream–table duality in Kafka Streams?
Answer: A stream of changes and a table are two views of the same data. Replaying every change of a key from the beginning rebuilds the table’s current value, and capturing every update of a table produces a stream. In Kafka Streams, aggregating a KStream produces a KTable, a KTable is restored from its changelog stream after a failure, and toStream() turns table updates back into a stream.
Q. What is the difference between tumbling, hopping, sliding and session windows?
Answer: Tumbling windows have a fixed size and never overlap, so each record lands in exactly one window. Hopping windows have a fixed size and advance by a smaller hop, so they overlap. Sliding windows are defined by the maximum time difference between records and are created by the records themselves. Session windows have no fixed size: a session for a key continues while records arrive within the inactivity gap and ends after a longer pause.
Intermediate questions
Q. What is the grace period of a window, and what happens to records that arrive after it?
Answer: The grace period is how long a window still accepts out-of-order records after its end, measured in stream time (the highest record timestamp seen). Late records inside the grace period update the window’s result. Once stream time passes window end plus grace, the window is closed and further records for it are dropped and counted in the dropped-records metric. A larger grace tolerates more disorder but holds more state and delays final results.
Q. In a KStream–KTable join, does an update to the table produce output?
Answer: No. Only records arriving on the stream side trigger the join; table updates only change the state used for lookups. So a stream record that arrives before its matching table row is joined with null in a left join, or dropped in an inner join, and is not re-joined when the row arrives later. KTable–KTable joins, by contrast, emit on updates from either side.
Q. Why does a KStream–KStream join require a join window?
Answer: Both inputs are unbounded, so Kafka Streams cannot keep every record forever to find matches. The JoinWindows limits matches to records whose timestamps are within a given difference, and both sides are buffered in window stores only for that time plus grace. The window size therefore directly determines the amount of state and the restore time after failures.
Tricky and scenario questions
Q. An alerting service receives several alerts for the same 5-minute window from a windowed count. Why, and how do you fix it?
Answer: Windowed aggregations emit an updated result whenever new records change the count, so downstream sees intermediate values for the same window. Use suppress(Suppressed.untilWindowCloses(...)) to emit only the final result after window end plus grace, or make the consumer idempotent per window key. Remember that final results appear only when stream time advances, so an idle partition delays them.
Q. You need to enrich orders with product data, but orders are keyed by order ID and products by product ID. What are your options?
Answer: Re-key the order stream by product ID with selectKey() and join with a products KTable; Kafka Streams adds a repartition topic so both sides are co-partitioned. If the product catalogue is small, use a GlobalKTable instead: every instance has the full table and a key mapper extracts the product ID, so no repartitioning is needed. If both sides are tables, a KTable–KTable foreign-key join handles the different keys directly.