Create session windows


If you have time series events in a Kafka topic, how can you group them into variable-size, non-overlapping time intervals based on a configurable inactivity period?

Edit this page

Example use case:

Given a topic of click events on a website, there are various ways that we can process it. As well as simply counting the number of clicks in a regular time frame (using hopping or tumbling windows), we can also perform sessionization on the data. Here the length of the time window is based on the concept of a session, which is defined based on a period of inactivity. A given user might visit a website multiple times a day, but in distinct visits. Using session windows, we can analyze the number of clicks and the duration of each visit.

Hands-on code example:

New to Confluent Cloud? Get started here.

Short Answer

To use SessionWindows use the SessionWindows.with method inside a windowedBy call.<INPUT TOPIC>, Consumed.with(<KEY SERDE>, <VALUE SERDE>))
                .<Aggregation Operation>....

The SessionsWindows.with call determines the length inactivity before you consider the session closed. The grace method determines is how much time elapses after the window closes before out-of-order are rejected.

Session windows aggregate events (by key) into sessions. A session represents a period of activity followed by inactivity period. Once the defined time for inactivity elapses, the session is considered closed. Session windows are a bit different from other window types (hopping, tumbling) because they don’t have a fixed window size. As long as new records arrive for a key within the inactivity gap, the window continues to grow in size, meaning the amount of time the window spans, not the total number of records in the window. Another way to view session windows is that they are driven by behavior while other window types are solely time based.

Run it

Initialize the project


To get started, make a new directory anywhere you’d like for this project:

mkdir session-windows && cd session-windows

Next, create a directory for configuration data:

mkdir configuration

Provision your Kafka cluster


This tutorial requires access to an Apache Kafka cluster, and the quickest way to get started free is on Confluent Cloud, which provides Kafka as a fully managed service.

Take me to Confluent Cloud
  1. After you log in to Confluent Cloud, click Environments in the lefthand navigation, click on Add cloud environment, and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.

  2. From the Billing & payment section in the menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.

  3. Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.

Confluent Cloud

Write the cluster information into a local file


From the Confluent Cloud Console, navigate to your Kafka cluster and then select Clients in the lefthand navigation. From the Clients view, create a new client and click Java to get the connection information customized to your cluster.

Create new credentials for your Kafka cluster and Schema Registry, writing in appropriate descriptions so that the keys are easy to find and delete later. The Confluent Cloud Console will show a configuration similar to below with your new credentials automatically populated (make sure Show API keys is checked). Copy and paste it into a configuration/ file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
security.protocol=SASL_SSL required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
# Required for correctness in Apache Kafka clients prior to 2.6

# Best practice for Kafka producer to prevent data loss

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url={{ SR_URL }}
basic.auth.credentials.source=USER_INFO{{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the Confluent Cloud Console so that it includes your Confluent Cloud information and credentials.

Download and set up the Confluent CLI


This tutorial has some steps for Kafka topic management and producing and consuming events, for which you can use the Confluent Cloud Console or the Confluent CLI. Follow the instructions here to install the Confluent CLI, and then follow these steps connect the CLI to your Confluent Cloud cluster.

Configure the project


Create the following Gradle build file, named build.gradle for the project:

buildscript {
    repositories {
    dependencies {
        classpath ""

plugins {
    id "java"
    id "idea"
    id "eclipse"
    id "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
version = "0.0.1"

repositories {
    maven {
        url ""

apply plugin: "com.github.johnrengelman.shadow"

dependencies {
    implementation "org.apache.avro:avro:1.11.1"
    implementation "org.slf4j:slf4j-simple:2.0.7"
    implementation 'org.apache.kafka:kafka-streams:3.4.0'
    implementation ('org.apache.kafka:kafka-clients') {
       version {
           strictly '3.4.0'
    implementation "io.confluent:kafka-streams-avro-serde:7.3.0"
    implementation "org.apache.kafka:kafka-clients:3.1.0"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:3.4.0"
    testImplementation "junit:junit:4.13.2"
    testImplementation 'org.hamcrest:hamcrest:2.2'

test {
    testLogging {
        outputs.upToDateWhen { false }
        showStandardStreams = true
        exceptionFormat = "full"

jar {
  manifest {
      "Class-Path": configurations.compileClasspath.collect { it.getName() }.join(" "),
      "Main-Class": "io.confluent.developer.SessionWindow"

shadowJar {
    archiveBaseName = "session-windows-standalone"
    archiveClassifier = ''

And be sure to run the following command to obtain the Gradle wrapper:

gradle wrapper

Then create a development configuration file at configuration/

Update the properties file with Confluent Cloud information


Using the command below, append the contents of configuration/ (with your Confluent Cloud configuration) to configuration/ (with the application properties).

cat configuration/ >> configuration/

Create a schema for the model object


Create a directory for the schemas that represent the events in the stream:

mkdir -p src/main/avro

Then create the following Avro schema file at src/main/avro/clicks.avsc for our Clicks object:

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Clicks",
  "fields": [
    { "name": "ip", "type": "string" },
    { "name": "timestamp", "type": "long" } ,
    { "name": "url", "type": "string" }

Because we will use an Avro schema in our Java code, we’ll need to compile it. The Gradle Avro plugin is a part of the build, so it will see your new Avro files, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:

./gradlew build

Create a timestamp extractor


First, create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer

Before you create the Kafka Streams application you’ll need to create an instance of a TimestampExtractor. In Kafka Streams, timestamps drive the progress of records in the application. By default, Kafka Streams uses the timestamps contained in the ConsumerRecord. But you can configure your application to use timestamps embedded in the record payload itself. You do this by creating an class implementing the TimestampExtractor interface and provide the class name when configuring your Kafka Streams application like so:

 props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class.getName());

We’re going to create a custom TimestampExtractor so the Kafka Streams application uses the timestamps embedded in our generated click events.

You aren’t required to use a custom TimestampExtractor in all cases. We’re using one here as it helps drive home the point of how sessions work and we can use synthetic timestamps to ensure we get distinct sessions.

Create the following file at src/main/java/io/confluent/developer/

package io.confluent.developer;

import io.confluent.developer.avro.Clicks;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.processor.TimestampExtractor;

public class ClickEventTimestampExtractor implements TimestampExtractor {
    public long extract(ConsumerRecord<Object, Object> record, long previousTimestamp) {
        return ((Clicks)record.value()).getTimestamp();

You’ll take care of the configuration when you create the Kafka Streams topology in the next step.

Create the Kafka Streams topology


In this tutorial you’ll learn about using SessionWindows with Kafka Streams. Session windows are driven by user behavior, as opposed to time., Consumed.with(Serdes.String(), clicksSerde))
                .groupByKey() (1)
                .windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30))) (2)
                .count() (3)
                .map((windowedKey, count) ->  { (4)
                    String start = timeFormatter.format(windowedKey.window().startTime());
                    String end = timeFormatter.format(windowedKey.window().endTime());
                    String sessionInfo = String.format("Session info started: %s ended: %s with count %s", start, end, count);
                    return KeyValue.pair(windowedKey.key(), sessionInfo);
1 Grouping by key, a prerequisite for aggregation operations
2 Specifying a session window for the windowing operation
3 Counting the number of clicks by key per session
4 Formatting the results. You probably won’t do this in practice, but it’s done in this tutorial to make the concept of a session more clear.

For this session window, once there is a period of inactivity of 5 minutes or more for a given key the current session is closed and any new records arriving after that time start a new session.

Session windows aggregate events (by key) into sessions. A session represents a period of activity followed by inactivity period. Once the defined time for inactivity elapses, the session is considered closed. Session windows are a bit different from other window types (hopping, tumbling) because they don’t have a fixed window size. As long as new records arrive for a key within the inactivity gap, the window continues to grow in size, meaning the amount of time the window spans, not the total number of records in the window. Another way to view session windows is that they are driven by behavior while other window types are solely time based.

NOTE: This in this example the incoming records have keys. If your input topic is not keyed, you’ll need to use the KStream.groupBy method and provide a KeyValueMapper instance to select to key to use for grouping.

That wraps up our discussion for the finer points of the code for this tutorial. Now create the following file at src/main/java/io/confluent/developer/

package io.confluent.developer;

import io.confluent.developer.avro.Clicks;
import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.avro.specific.SpecificRecord;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
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.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.SessionWindows;

import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;

public class SessionWindow {

    private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG)

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String inputTopic = allProps.getProperty("");
        final String outputTopic = allProps.getProperty("");
        final SpecificAvroSerde<Clicks> clicksSerde = getSpecificAvroSerde(allProps);, Consumed.with(Serdes.String(), clicksSerde))
                .windowedBy(SessionWindows.ofInactivityGapAndGrace(Duration.ofMinutes(5), Duration.ofSeconds(30)))
                .map((windowedKey, count) ->  {
                    String start = timeFormatter.format(windowedKey.window().startTime());
                    String end = timeFormatter.format(windowedKey.window().endTime());
                    String sessionInfo = String.format("Session info started: %s ended: %s with count %s", start, end, count);
                    return KeyValue.pair(windowedKey.key(), sessionInfo);
                .to(outputTopic, Produced.with(Serdes.String(), Serdes.String()));


    static <T extends SpecificRecord> SpecificAvroSerde<T> getSpecificAvroSerde(final Properties allProps) {
        final SpecificAvroSerde<T> specificAvroSerde = new SpecificAvroSerde<>();
        final Map<String, String> serdeConfig = (Map)allProps;
        specificAvroSerde.configure(serdeConfig, false);
        return specificAvroSerde;
    public void createTopics(Properties allProps) {
        try (AdminClient client = AdminClient.create(allProps)) {
            List<NewTopic> topicList = new ArrayList<>();

            NewTopic sessionInput = new NewTopic(allProps.getProperty(""),

            NewTopic counts = new NewTopic(allProps.getProperty(""),


    public Properties loadEnvProperties(String fileName) throws IOException {
        Properties allProps = new Properties();
        FileInputStream input = new FileInputStream(fileName);

        return allProps;

    public static void main(String[] args) throws Exception {

        if (args.length < 1) {
            throw new IllegalArgumentException("This program takes one argument: the path to an environment configuration file.");

        SessionWindow tw = new SessionWindow();
        Properties allProps = tw.loadEnvProperties(args[0]);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
        allProps.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, ClickEventTimestampExtractor.class);
        Topology topology = tw.buildTopology(allProps);

        ClicksDataGenerator dataGenerator = new ClicksDataGenerator(allProps);

        final KafkaStreams streams = new KafkaStreams(topology, allProps);
        final CountDownLatch latch = new CountDownLatch(1);

        // Attach shutdown handler to catch Control-C.
        Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
            public void run() {

        try {
        } catch (Throwable e) {

    static class ClicksDataGenerator {
        final Properties properties;

        public ClicksDataGenerator(final Properties properties) {
   = properties;

        public void generate() {
            properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
            properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

            try (Producer<String, Clicks> producer = new KafkaProducer<>(properties)) {
                String topic = properties.getProperty("");
                List<Clicks> sessionClicks = new ArrayList<>();
                final String keyOne = "";
                final String keyTwo = "";

                Instant instant =;


                Instant newSessionInstant =, ChronoUnit.HOURS);



                sessionClicks.forEach(click -> {
                    producer.send(new ProducerRecord<>(topic, click.getIp(), click), (metadata, exception) -> {
                            if (exception != null) {
                            } else {
                                System.out.printf("Produced record at offset %d to topic %s \n", metadata.offset(), metadata.topic());

Compile and run the Kafka Streams program


Now that we have data generation working, let’s build your application by running:

./gradlew shadowJar

Now that you have an uberjar for the Kafka Streams application, you can launch it locally.

When you run the following, the prompt won’t return, because the application will run until you exit it. There is always another message to process, so streaming applications don’t exit until you force them.

java -jar build/libs/session-windows-standalone-0.0.1.jar configuration/
This Kafka Streams application includes record generator to populate the topic with "sessionized" data. The first part of running the application will populate data in the input topic for the streams application to process. If you decide to re-run the application the data-generator will run again, giving you slightly different results. In practice, you don’t want to include something like this in a production application.

Consume data from the output topic


Now that your Kafka Streams application is running, open a new terminal window, change directories (cd) into the session-windows directory and start a console-consumer to confirm the output:

confluent kafka topic consume output-topic --from-beginning --print-key

You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ configuration file. Look for the configuration parameter, whereby the ":" is the delimiter between the key and secret.

Enter your Schema Registry API key:
Enter your Schema Registry API secret:

Your results should look something like this: : Session info started: 1:13:45 PM EST ended: 1:14:23 PM EST with count 4 : Session info started: 1:13:55 PM EST ended: 1:14:43 PM EST with count 4 : Session info started: 3:13:45 PM EST ended: 3:13:55 PM EST with count 4 : Session info started: 3:13:56 PM EST ended: 3:14:13 PM EST with count 4
Processed a total of 4 messages

Teardown Confluent Cloud resources


You may try another tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud Console or CLI to destroy all of the resources you created. Verify they are destroyed to avoid unexpected charges.

Test it

Create a test configuration file


First, create a test file at configuration/

Write a test


Create a directory for the tests to live in:

mkdir -p src/test/java/io/confluent/developer

Testing a Kafka streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver class makes this much more pleasant that it would otherwise be.

There is only one method in SessionWindowTest annotated with @Test, and that is sessionWindowTest(). This method actually runs our Streams topology using the TopologyTestDriver and some mocked data that is set up inside the test method.

This test is straightforward, but there is one section we should look into a little more

final int expectedNumberOfSessions = 2;
final String key = "";
final List<Clicks> sessionClicks = new ArrayList<>();
Instant instant =;

sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build()); (1)

Instant newSessionInstant =,ChronoUnit.MINUTES); (2)

1 Creating a record for the first "session"
2 Increasing the time to beyond inactivity period, the test should yield 2 sessions in the results
3 Adding record for second "session"

The TestInputTopic provides useful methods when testing your topology. Here you’re using the pipeKeyValueList to provide the records to the steams application. Here you’re not specifying any timestamp activity as the streams application pulls the timestamps embedded in the TemperatureReading objects you created above.

Now create the following file at src/test/java/io/confluent/developer/

package io.confluent.developer;

import io.confluent.developer.avro.Clicks;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.Test;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static org.junit.Assert.assertEquals;

public class SessionWindowTest {

    private final static String TEST_CONFIG_FILE = "configuration/";

    public void sessionWindowTest() throws IOException {
        final SessionWindow instance = new SessionWindow();
        final Properties allProps = instance.loadEnvProperties(TEST_CONFIG_FILE);

        final String sessionDataInputTopic = allProps.getProperty("");
        final String outputTopicName = allProps.getProperty("");

        final Topology topology = instance.buildTopology(allProps);
        try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, allProps)) {

            final SpecificAvroSerde<Clicks> exampleAvroSerde = SessionWindow.getSpecificAvroSerde(allProps);

            final Serializer<String> keySerializer = Serdes.String().serializer();
            final Serializer<Clicks> exampleSerializer = exampleAvroSerde.serializer();
            final Deserializer<String> valueDeserializer = Serdes.String().deserializer();
            final Deserializer<String> keyDeserializer = Serdes.String().deserializer();

            final TestInputTopic<String, Clicks>  inputTopic = testDriver.createInputTopic(sessionDataInputTopic,

            final TestOutputTopic<String, String> outputTopic = testDriver.createOutputTopic(outputTopicName, keyDeserializer, valueDeserializer);
            final String key = "";
            final List<Clicks> sessionClicks = new ArrayList<>();
            Instant instant =;
            final int expectedNumberOfSessions = 2;
            Instant newSessionInstant =,ChronoUnit.MINUTES);
            List<KeyValue<String, Clicks>> keyValues = -> KeyValue.pair(o.getIp(),o)).collect(Collectors.toList());

            final List<KeyValue<String, String>> actualResults = outputTopic.readKeyValuesToList();
            // Should result in two sessions
            assertEquals(expectedNumberOfSessions, actualResults.size());

Invoke the tests


Now run the test, which is as simple as:

./gradlew test