Create session windows

Question:

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:

Short Answer

To use SessionWindows use the SessionWindows.with method inside a windowedBy call.



builder.stream(<INPUT TOPIC>, Consumed.with(<KEY SERDE>, <VALUE SERDE>))
                .groupByKey()
                .windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30)))
                .<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

Prerequisites

1

This tutorial installs Confluent Platform using Docker. Before proceeding:

  • • Install Docker Desktop (version 4.0.0 or later) or Docker Engine (version 19.03.0 or later) if you don’t already have it

  • • Install the Docker Compose plugin if you don’t already have it. This isn’t necessary if you have Docker Desktop since it includes Docker Compose.

  • • Start Docker if it’s not already running, either by starting Docker Desktop or, if you manage Docker Engine with systemd, via systemctl

  • • Verify that Docker is set up properly by ensuring no errors are output when you run docker info and docker compose version on the command line

Initialize the project

2

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

mkdir session-windows && cd session-windows

Get Confluent Platform

3

Next, create the following docker-compose.yml file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud):

version: '2'
services:
  broker:
    image: confluentinc/cp-kafka:7.4.1
    hostname: broker
    container_name: broker
    ports:
    - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_NODE_ID: 1
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
      KAFKA_LISTENERS: PLAINTEXT://broker:9092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:29092
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
  schema-registry:
    image: confluentinc/cp-schema-registry:7.3.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
    - broker
    ports:
    - 8081:8081
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: broker:9092

And launch it by running:

docker compose up -d

Configure the project

4

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

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "gradle.plugin.com.github.jengelman.gradle.plugins:shadow:7.0.0"
    }
}

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 {
    mavenCentral()
    maven {
        url "https://packages.confluent.io/maven"
    }
}

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 {
    attributes(
      "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

Next, create a directory for configuration data:

mkdir configuration

Then create a development file at configuration/dev.properties:

application.id=session-windows
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081

input.topic.name=page-views
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=output-topic
output.topic.partitions=1
output.topic.replication.factor=1

Create a schema for the model object

5

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

6

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/ClickEventTimestampExtractor.java

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 {
    @Override
    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

7

In this tutorial you’ll learn about using SessionWindows with Kafka Streams. Session windows are driven by user behavior, as opposed to time.

   builder.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
                .groupByKey() (1)
                .windowedBy(SessionWindows.with(Duration.ofMinutes(5)).grace(Duration.ofSeconds(30))) (2)
                .count() (3)
                .toStream()
                .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/SessionWindow.java

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.io.FileInputStream;
import java.io.IOException;
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)
            .withLocale(Locale.US)
            .withZone(ZoneId.systemDefault());

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String inputTopic = allProps.getProperty("input.topic.name");
        final String outputTopic = allProps.getProperty("output.topic.name");
        final SpecificAvroSerde<Clicks> clicksSerde = getSpecificAvroSerde(allProps);

        builder.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
                .groupByKey()
                .windowedBy(SessionWindows.ofInactivityGapAndGrace(Duration.ofMinutes(5), Duration.ofSeconds(30)))
                .count()
                .toStream()
                .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()));

        return builder.build();
    }


    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("input.topic.name"),
                    Integer.parseInt(allProps.getProperty("input.topic.partitions")),
                    Short.parseShort(allProps.getProperty("input.topic.replication.factor")));
            topicList.add(sessionInput);

            NewTopic counts = new NewTopic(allProps.getProperty("output.topic.name"),
                    Integer.parseInt(allProps.getProperty("output.topic.partitions")),
                    Short.parseShort(allProps.getProperty("output.topic.replication.factor")));

            topicList.add(counts);
            client.createTopics(topicList);
        }
    }

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

        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);

        tw.createTopics(allProps);
        ClicksDataGenerator dataGenerator = new ClicksDataGenerator(allProps);
        dataGenerator.generate();

        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") {
            @Override
            public void run() {
                streams.close(Duration.ofSeconds(5));
                latch.countDown();
            }
        });

        try {
            streams.cleanUp();
            streams.start();
            latch.await();
        } catch (Throwable e) {
            System.exit(1);
        }
        System.exit(0);
    }

    static class ClicksDataGenerator {
        final Properties properties;


        public ClicksDataGenerator(final Properties properties) {
            this.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("input.topic.name");
                List<Clicks> sessionClicks = new ArrayList<>();
                final String keyOne = "51.56.119.117";
                final String keyTwo = "53.170.33.192";

                Instant instant = Instant.now();
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("vestibulum/vestibulum/ante/ipsum/primis/in.json").setTimestamp(instant.plusMillis(9000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/mauris/morbi/non.jpg").setTimestamp(instant.plusMillis(24000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(instant.plusMillis(38000).toEpochMilli()).build());

                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.plusMillis(10000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/mauris/morbi/non.jpg").setTimestamp(instant.plusMillis(32000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nec/euismod/scelerisque/quam.xml").setTimestamp(instant.plusMillis(44000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(instant.plusMillis(58000).toEpochMilli()).build());

                Instant newSessionInstant = instant.plus(2, ChronoUnit.HOURS);

                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(newSessionInstant.toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("vestibulum/vestibulum/ante/ipsum/primis/in.json").setTimestamp(newSessionInstant.plusMillis(2000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.plusMillis(4000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyOne).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(newSessionInstant.plusMillis(10000).toEpochMilli()).build());

                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(newSessionInstant.plusMillis(11000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.plusMillis(12000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nec/euismod/scelerisque/quam.xml").setTimestamp(newSessionInstant.plusMillis(14000).toEpochMilli()).build());
                sessionClicks.add(Clicks.newBuilder().setIp(keyTwo).setUrl("/nullam/orci/pede/venenatis.json").setTimestamp(newSessionInstant.plusMillis(28000).toEpochMilli()).build());

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

Compile and run the Kafka Streams program

8

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/dev.properties
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

9

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:

docker exec -t broker kafka-console-consumer \
 --bootstrap-server broker:9092 \
 --topic output-topic \
 --property print.key=true \
 --property key.separator=" : "  \
 --from-beginning \
 --max-messages 4

Your results should look something like this:


51.56.119.117 : Session info started: 1:13:45 PM EST ended: 1:14:23 PM EST with count 4
53.170.33.192 : Session info started: 1:13:55 PM EST ended: 1:14:43 PM EST with count 4
51.56.119.117 : Session info started: 3:13:45 PM EST ended: 3:13:55 PM EST with count 4
53.170.33.192 : Session info started: 3:13:56 PM EST ended: 3:14:13 PM EST with count 4
Processed a total of 4 messages

Go ahead and shut down your streams application now with a CNTR+C command.

Test it

Create a test configuration file

1

First, create a test file at configuration/test.properties:

application.id=session-windows-test
bootstrap.servers=localhost:29092
schema.registry.url=mock://localhost:8081

input.topic.name=temp-readings
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=output-topic
output.topic.partitions=1
output.topic.replication.factor=1

Write a test

2

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 = "51.56.119.117";
final List<Clicks> sessionClicks = new ArrayList<>();
Instant instant = Instant.now();

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

Instant newSessionInstant = instant.plus(6,ChronoUnit.MINUTES); (2)

sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.toEpochMilli()).build());(3)
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/SessionWindowTest.java.

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.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;


public class SessionWindowTest {

    private final static String TEST_CONFIG_FILE = "configuration/test.properties";

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

        final String sessionDataInputTopic = allProps.getProperty("input.topic.name");
        final String outputTopicName = allProps.getProperty("output.topic.name");

        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,
                                                                                              keySerializer,
                                                                                              exampleSerializer);

            final TestOutputTopic<String, String> outputTopic = testDriver.createOutputTopic(outputTopicName, keyDeserializer, valueDeserializer);
            final String key = "51.56.119.117";
            final List<Clicks> sessionClicks = new ArrayList<>();
            Instant instant = Instant.now();
            final int expectedNumberOfSessions = 2;
            sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/etiam/justo/etiam/pretium/iaculis.xml").setTimestamp(instant.toEpochMilli()).build());
            Instant newSessionInstant = instant.plus(6,ChronoUnit.MINUTES);
            sessionClicks.add(Clicks.newBuilder().setIp(key).setUrl("/mauris/morbi/non.jpg").setTimestamp(newSessionInstant.toEpochMilli()).build());
            List<KeyValue<String, Clicks>> keyValues = sessionClicks.stream().map(o -> KeyValue.pair(o.getIp(),o)).collect(Collectors.toList());
            inputTopic.pipeKeyValueList(keyValues);

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

Invoke the tests

3

Now run the test, which is as simple as:

./gradlew test

Deploy on Confluent Cloud

Run your app with Confluent Cloud

1

Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully managed Apache Kafka service.

  1. Sign up for Confluent Cloud, a fully managed Apache Kafka service.

  2. After you log in to Confluent Cloud Console, 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.

  3. 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.

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

Confluent Cloud

Next, from the Confluent Cloud Console, click on Clients to get the cluster-specific configurations, e.g., Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application. In the case of this tutorial, add the following properties to the client application’s input properties file, substituting all curly braces with your Confluent Cloud values.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BROKER_ENDPOINT }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips

# Best practice for Kafka producer to prevent data loss
acks=all

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url=https://{{ SR_ENDPOINT }}
basic.auth.credentials.source=USER_INFO
schema.registry.basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}

Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.