liveBook · Manning

TimeWindows

As explained in Kafka Streams in Action, Second Edition

TimeWindows is a Kafka Streams class that defines fixed-size time-based windows with a configurable advance interval.

TimeWindows defines fixed-size, time-aligned windows for Kafka Streams aggregations. Apply it after groupByKey with windowedBy, then configure the window size and advance interval. section 9.1.1

Build a hopping-window aggregation by:

  • Creating a one-minute window with TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(1)). section 9.1.1
  • Chaining advanceBy(Duration.ofSeconds(10)) so results update every ten seconds. section 9.1.1
  • Handling the resulting Windowed key by unwrapping its underlying key or producing it with a windowed Serde. section 9.1.1

IoT temperature monitoring

An aggregation can report average and highest sensor temperatures for the previous minute every ten seconds. Because the advance is shorter than the window, successive results overlap. section 9.1.1

Listing 9.3 Adding windowing to the aggregation for the Iot temperature readings
KStream<String,Double> iotHeatSensorStream =
  builder.stream("heat-sensor-input",
    Consumed.with(stringSerde, doubleSerde));
iotHeatSensorStream.groupByKey()                   #1
      .windowedBy(TimeWindows.ofSizeWithNoGrace(
                       Duration.ofMinutes(1))        #2
        .advanceBy(Duration.ofSeconds(10)))
        .aggregate(
 () -> new IotSensorAggregation(tempThreshold),     #3
         aggregator,
         Materialized.with(stringSerde, aggregationSerde))
         .toStream().to("sensor-agg-output",
           Produced.with(serdeString,
                        sensorAggregationSerde))     #4

Inspect the complete Kafka Streams topology for adding TimeWindows to IoT temperature aggregation. section 9.1.1

Figure 9.19 TimeWindows are aligned to the epoch.
figure

Use the diagram to see how TimeWindows align their boundaries to the Unix epoch. section 9.1.5

How Kafka Streams in Action, Second Edition covers it

How deep it goes
Explains construction, advance configuration, output-key handling, and epoch alignment, while deferring grace-period semantics.
Examples
Uses IoT temperature readings aggregated over one-minute windows with ten-second advances and overlapping results.
What it assumes
Assumes familiarity with Kafka Streams groupByKey, aggregation, streams, topics, and Serdes.
What you can do after
Apply it via Kafka Streams Java APIs to build fixed-size hopping-window aggregations and route windowed results to a topic.
How it connects
Connects Kafka Streams aggregation, groupByKey, hopping windows, Windowed keys, Serdes, and Unix epoch alignment.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kafka Streams in Action, Second Edition. The section links point to the parts of the book it draws on.