00:00

KStream, KTable, Windowing and Joins in Kafka Streams

Last updated:

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 aliceRead as a KStreamRead as a KTable
(alice, 3), then (alice, 5)Two events; a sum is 8One row whose current value is 5
(alice, null)Ignored by most operationsDeletes 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

Kafka Streams window typesOn a time axis from 0 to 20 minutes, tumbling windows of 5 minutes are consecutive and do not overlap. Hopping windows of 10 minutes that advance every 5 minutes overlap, so one record belongs to two windows. Session windows group records of one key that are separated by less than the inactivity gap; a gap longer than the inactivity gap starts a new session. Sliding windows are defined by the maximum time difference between records. Tumbling 0–55–1010–1515–20 Hopping 0–10 5–15 10–20 Session session 1 session 2 gap > inactivity gap Sliding records within the time difference 0 min10 min20 min
Tumbling windows never overlap, hopping windows can, session windows depend on gaps in activity, and sliding windows depend on the distance between records.
WindowDefined byOverlapDSLTypical use
TumblingSizeNo; each record in exactly one windowTimeWindows.ofSizeWithNoGrace(size)Orders per minute, errors per hour
HoppingSize and advance (hop)Yes, when advance < sizeTimeWindows.ofSizeAndGrace(size, grace).advanceBy(hop)“Last 10 minutes, updated every minute” dashboards
SlidingMaximum time difference between recordsYes; windows are created by the records themselvesSlidingWindows.ofTimeDifferenceAndGrace(diff, grace)“More than 5 failed logins within 2 minutes”
SessionInactivity gapNo; sessions of one key can mergeSessionWindows.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-records metric).

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:

Final results only
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.

JoinWindowed?What triggers outputVariantsTypical use
KStream–KStreamYes, JoinWindowsA new record on either side that finds a match within the time differenceinner, left, outerMatch a payment to an order that happened within 10 minutes
KStream–KTableNoOnly new stream records; table updates just change the lookup stateinner, leftEnrich each order with the current customer data
KStream–GlobalKTableNoOnly new stream recordsinner, leftEnrich with small reference data without co-partitioning; a key mapper picks the table key
KTable–KTableNoAn update on either sideinner, left, outerCombine two current views, such as account and balance
KTable–KTable foreign-keyNoAn update on either sideinner, leftJoin order rows to the customer row they reference, when keys differ
KStream–KTable timing: because only stream records trigger the join, an order arriving before the matching customer record is joined with 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:

ShopTopology.java
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:

Input and output
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):

PaymentMatching.java (excerpt)
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:

application.yml
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
ShopStreamsConfig.java
@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

SettingDefaultWhy it matters here
processing.guaranteeat_least_onceUse exactly_once_v2 when duplicate window counts or join results are not acceptable
commit.interval.ms30000 (100 with exactly-once)Together with the cache, controls how often updated results are flushed downstream
statestore.cache.max.bytes10485760 (10 MiB)Record cache that combines several updates of the same key before emitting; 0 shows every update
Materialized.withRetention(...)Window size plus grace periodHow long windowed results stay queryable in the window store; set it longer if interactive queries must read older windows
Grace periodZero with ...WithNoGraceHow 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-records metric.
  • 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.

14. References