How to create tumbling windows

Question:

If you have time series events in a Kafka topic, how can you group them into fixed-size, non-overlapping, contiguous time intervals?

Edit this page

Example use case:

Suppose you have a topic with events that represent movie ratings. In this tutorial, we'll write a program to maintain tumbling windows that count the total number of ratings that each movie has received.

Hands-on code example:

New to Confluent Cloud? Get started here.

Run it

Initialize the project

1

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

mkdir tumbling-windows && cd tumbling-windows

Next, create a directory for configuration data:

mkdir configuration

Provision your Kafka cluster

2

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

3

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/ccloud.properties file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
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={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.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

4

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

5

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

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

plugins {
  id 'java'
  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'
  testImplementation 'org.apache.kafka:kafka-streams-test-utils:3.4.0'
  testImplementation 'junit:junit:4.13.2'
}

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

task run(type: JavaExec) {
  mainClass = 'io.confluent.developer.TumblingWindow'
  classpath = sourceSets.main.runtimeClasspath
  args = ['configuration/dev.properties']
}

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

shadowJar {
  archiveBaseName = "kstreams-tumbling-windows-standalone"
  archiveClassifier = ''
}

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

gradle wrapper

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

application.id=tumbling-window-app
replication.factor=3

rating.topic.name=ratings
rating.topic.partitions=6
rating.topic.replication.factor=3

rating.count.topic.name=rating-counts
rating.count.topic.partitions=6
rating.count.topic.replication.factor=3

Update the properties file with Confluent Cloud information

6

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

cat configuration/ccloud.properties >> configuration/dev.properties

Create a schema for the events

7

This tutorial uses a single input stream called ratings. It contains movie ratings for a few different movies submitted at times spanning a few weeks. We’ll need to create a schema for these events.

Create a directory to hold the schema file:

mkdir -p src/main/avro

Next, create an Avro schema file at src/main/avro/rating.avsc for the stream of ratings:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Rating",
  "fields": [
    {"name": "title", "type": "string"},
    {"name": "release_year", "type": "int"},
    {"name": "rating", "type": "double"},
    {"name": "timestamp", "type": "string"}
  ]
}

Because we will use this 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 the Kafka Streams topology

8

Create a directory for the Java files in this project:

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

Then create the following file at src/main/java/io/confluent/developer/TumblingWindow.java.

package io.confluent.developer;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
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.Topology;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.Windowed;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.CountDownLatch;

import io.confluent.developer.avro.Rating;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

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

public class TumblingWindow {

    public Properties buildStreamsProperties(Properties allProps) {
        allProps.put(StreamsConfig.APPLICATION_ID_CONFIG, allProps.getProperty("application.id"));
        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, RatingTimestampExtractor.class.getName());
        allProps.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
        try {
            allProps.put(StreamsConfig.STATE_DIR_CONFIG,
                      Files.createTempDirectory("tumbling-windows").toAbsolutePath().toString());
        }
        catch(IOException e) {
            // If we can't have our own temporary directory, we can leave it with the default. We create a custom
            // one because running the app outside of Docker multiple times in quick succession will find the
            // previous state still hanging around in /tmp somewhere, which is not the expected result.
        }
        return allProps;
    }

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String ratingTopic = allProps.getProperty("rating.topic.name");
        final String ratingCountTopic = allProps.getProperty("rating.count.topic.name");

        builder.<String, Rating>stream(ratingTopic)
            .map((key, rating) -> new KeyValue<>(rating.getTitle(), rating))
            .groupByKey()
            .windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(10), Duration.ofMinutes(1440)))
            .count()
            .toStream()
            .map((Windowed<String> key, Long count) -> new KeyValue<>(key.key(), count.toString()))
            .to(ratingCountTopic, Produced.with(Serdes.String(), Serdes.String()));

        return builder.build();
    }

    private String windowedKeyToString(Windowed<String> key) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZZZZ");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return String.format("[%s@%s/%s]",
                             key.key(),
                             sdf.format(key.window().startTime().getEpochSecond()),
                             sdf.format(key.window().endTime().getEpochSecond()));
    }


    private SpecificAvroSerde<Rating> ratedMovieAvroSerde(final Properties allProps) {
        final SpecificAvroSerde<Rating> movieAvroSerde = new SpecificAvroSerde<>();

        Map<String, String> config = new HashMap<>();
        for (final String name: allProps.stringPropertyNames())
                    config.put(name, allProps.getProperty(name));
        movieAvroSerde.configure(config, false);
        return movieAvroSerde;
    }

    public void createTopics(Properties allProps) {
        AdminClient client = AdminClient.create(allProps);

        List<NewTopic> topics = new ArrayList<>();
        Map<String, String> topicConfigs = new HashMap<>();
        topicConfigs.put("retention.ms", Long.toString(Long.MAX_VALUE));

        NewTopic ratings = new NewTopic(allProps.getProperty("rating.topic.name"),
                                        Integer.parseInt(allProps.getProperty("rating.topic.partitions")),
                                        Short.parseShort(allProps.getProperty("rating.topic.replication.factor")));
        ratings.configs(topicConfigs);
        topics.add(ratings);

        NewTopic counts = new NewTopic(allProps.getProperty("rating.count.topic.name"),
                                       Integer.parseInt(allProps.getProperty("rating.count.topic.partitions")),
                                       Short.parseShort(allProps.getProperty("rating.count.topic.replication.factor")));
        counts.configs(topicConfigs);
        topics.add(counts);


        client.createTopics(topics);
        client.close();
    }

    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.");
        }

        TumblingWindow tw = new TumblingWindow();
        Properties allProps = tw.buildStreamsProperties(tw.loadEnvProperties(args[0]));
        Topology topology = tw.buildTopology(allProps);

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

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

Let’s take a close look at the buildTopology() method, which uses the Kafka Streams DSL.

The first thing the method does is create an instance of StreamsBuilder, which is the helper object that lets us build our topology.

First, we call the stream() method to create a KStream<String, Rating> object. The problem is that we can’t make any assumptions about the key of this stream, so we have to repartition it explicitly. We use the map() method for that, creating a new KeyValue instance for each record, using the title as the new key.

Next we group the events by that new key by calling the groupByKey() method. We want to count the events that occur with each given key, so we must first define a tumbling window by calling windowedBy(TimeWindows.of(Duration.ofMinutes(10))). We then call count(), which directs the topology to count the grouped events that occur within each window. At this point in the topology, the result is a KTable<Windowed<String>, Long>. We use the map() method to turn it into two easy-to-read strings, then emit the result to the output topic with the to() method. You might not always make that last call to map(), but for our purposes here, it makes the output a lot easier to read.

Implement a TimestampExtractor class

9

The preceding topology relies on the messages in its input topic being processed according <em>event time</em>—the time at which the event actually occurred, rather than the time it happened to arrive on the topic. Event time is typically available in the message itself, as it is in this case in the form of the timestamp field. We can automatically extract this timestamp by creating the src/main/java/io/confluent/developer/RatingTimestampExtractor.java class, which is an implementation of the TimestampExtractor interface. The code is simple:

package io.confluent.developer;

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

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class RatingTimestampExtractor implements TimestampExtractor {
    @Override
    public long extract(ConsumerRecord<Object, Object> record, long previousTimestamp) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

        String eventTime = ((Rating)record.value()).getTimestamp();

        try {
            return sdf.parse(eventTime).getTime();
        } catch(ParseException e) {
            return 0;
        }
    }
}

Some special configuration

10

There is always a little bit of boilerplate configuration in any Kafka Streams app, but three lines in this tutorial are worth comment. You don’t have to do anything on this step, so you can come back to it later if you’d like.

First, the TimestampExtractor we created in the previous step is installed into our stream processing topology through a configuration setting. This is the props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, RatingTimestampExtractor.class.getName()) line.

Second, we want to optimize our Streams app for latency at the expense of throughput. (The real thing we want here is to see results in the output terminal pane as quickly as possible, which is a less-fancy way of saying the same thing.) To make this happen, we have to disable the Streams output cache as follows: props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0).

Finally, we need to remember that a Streams app caches its state locally on disk, in a directory pointed to by the state.dir configuration setting. If you run the application once, kill it, then run it again, it will likely find the state left on disk by the previous run. This is very much by design, but can be confusing when you’re experimenting with a small tutorial like this. To make sure state goes into a throwaway temporary directory, we set the state dir with props.put(StreamsConfig.STATE_DIR_CONFIG, Files.createTempDirectory("tumbling-windows").toAbsolutePath().toString()). Note that the call must be wrapped in an exception-handling block, and if we fail to create the temporary directory, we continue running with the default directory in place.

Compile and run the Kafka Streams program

11

In your terminal, run:

./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/kstreams-tumbling-windows-standalone-0.0.1.jar configuration/dev.properties

Get ready to observe the counted ratings in the output topic

12

Before you start producing input data, it’s a good idea to set up the consumer on the output topic. This way, as soon as you produce movie ratings (and windowed and counted), you’ll see the results right away. Run this to get ready to consume the windowed counts:

confluent kafka topic consume rating-counts -b --print-key

You won’t see any results until the next step.

Produce some ratings to the input topic

13

When the console producer starts, it will log some text and hang, waiting for your input. You can copy and paste all of the test data at once to see the results. (Because event times are baked into each message, it doesn’t matter at what time the messages arrive in the input topic. In fact, if you want extra credit, you should be able to experiment with changing the order of the messages in this data, and still get the same output counts.)

Start the console producer with this command in a terminal window of its own:

confluent kafka topic produce ratings --value-format avro --schema src/main/avro/rating.avsc

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

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

When the console producer starts, it will log some messages and hang, waiting for your input. Type in one line at a time and press enter to send it. Each line represents an event. To send all of the events below, paste the following into the prompt and press enter:

{"title": "Die Hard", "release_year": 1998, "rating": 8.2, "timestamp": "2019-04-25T18:00:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 4.5, "timestamp": "2019-04-25T18:03:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 5.1, "timestamp": "2019-04-25T18:04:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 2.0, "timestamp": "2019-04-25T18:07:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 8.3, "timestamp": "2019-04-25T18:32:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 3.4, "timestamp": "2019-04-25T18:36:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 4.2, "timestamp": "2019-04-25T18:43:00-0700"}
{"title": "Die Hard", "release_year": 1998, "rating": 7.6, "timestamp": "2019-04-25T18:44:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 4.9, "timestamp": "2019-04-25T20:01:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 5.6, "timestamp": "2019-04-25T20:02:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 9.0, "timestamp": "2019-04-25T20:03:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 6.5, "timestamp": "2019-04-25T20:12:00-0700"}
{"title": "Tree of Life", "release_year": 2011, "rating": 2.1, "timestamp": "2019-04-25T20:13:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 3.6, "timestamp": "2019-04-25T22:20:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 6.0, "timestamp": "2019-04-25T22:21:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 7.0, "timestamp": "2019-04-25T22:22:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 4.6, "timestamp": "2019-04-25T22:23:00-0700"}
{"title": "A Walk in the Clouds", "release_year": 1995, "rating": 7.1, "timestamp": "2019-04-25T22:24:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 9.9, "timestamp": "2019-04-25T21:15:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 8.6, "timestamp": "2019-04-25T21:16:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 4.2, "timestamp": "2019-04-25T21:17:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 7.0, "timestamp": "2019-04-25T21:18:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 9.5, "timestamp": "2019-04-25T21:19:00-0700"}
{"title": "The Big Lebowski", "release_year": 1998, "rating": 3.2, "timestamp": "2019-04-25T21:20:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 3.5, "timestamp": "2019-04-25T13:00:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 4.0, "timestamp": "2019-04-25T13:07:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 5.1, "timestamp": "2019-04-25T13:30:00-0700"}
{"title": "Super Mario Bros.", "release_year": 1993, "rating": 2.0, "timestamp": "2019-04-25T13:34:00-0700"}

Looking back up in the consumer terminal, these are the results you should see there if you paste in all the ratings as directed above:

Die Hard	1
Die Hard	2
Die Hard	3
Die Hard	4
Die Hard	1
Die Hard	2
Die Hard	1
Die Hard	2
Tree of Life	1
Tree of Life	2
Tree of Life	3
Tree of Life	1
Tree of Life	2
A Walk in the Clouds	1
A Walk in the Clouds	2
A Walk in the Clouds	3
A Walk in the Clouds	4
A Walk in the Clouds	5
The Big Lebowski	1
The Big Lebowski	2
The Big Lebowski	3
The Big Lebowski	4
The Big Lebowski	5
The Big Lebowski	1
Super Mario Bros.	1
Super Mario Bros.	2
Super Mario Bros.	1
Super Mario Bros.	2

Note that each event is counted individually. Since output caching is disabled, we see Die Hard get counted once, then counted again, then counted again, until the Die Hard ratings stop arriving. At that point, we have the final count for that movie. The same happens with all the rest. If we were to interrogate the contents of the resulting KTable after all the input messages have arrived, we would see only the final counts in the table—not the history of the counting as we see in the output topic. This is a good illustration of what we sometimes refer to as the stream-table duality.

That is a topic for further study later on, but for now, you deserve some congratulations! You have now computed an aggregation over a tumbling window. Well done.

Teardown Confluent Cloud resources

14

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

1

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

application.id=tumbling-window-app
bootstrap.servers=localhost:29092
schema.registry.url=mock://tumbling-window-app:8081

rating.topic.name=ratings
rating.topic.partitions=1
rating.topic.replication.factor=1

rating.count.topic.name=rating-counts
rating.count.topic.partitions=1
rating.count.topic.replication.factor=1

Test the RatingTimestampExtractor class

2

Create a directory for the tests to live in:

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

Create the following file at src/test/java/io/confluent/developer/RatingTimestampExtractorTest.java. This tests the helper class that extracts event-time timestamps from incoming messages. The class has a dependency on the TimestampExtractor interface, but otherwise does not depend on anything external to our domain; it just needs a Rating object, and returns a timestamp. As such, it’s very testable code:

package io.confluent.developer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.junit.Test;

import io.confluent.developer.avro.Rating;

import static org.junit.Assert.assertEquals;

public class RatingTimestampExtractorTest {

    @Test
    public void testTimestampExtraction() {
        RatingTimestampExtractor rte = new RatingTimestampExtractor();

        Rating treeOfLife = Rating.newBuilder().setTitle("Tree of Life").setReleaseYear(2011).setRating(9.9).setTimestamp("2019-04-25T18:00:00-0700").build();
        ConsumerRecord<Object, Object> record = new ConsumerRecord<>("ratings", 0, 1, "Tree of Life", treeOfLife);

        long timestamp = rte.extract(record, 0);

        assertEquals(1556240400000L, timestamp);
    }
}

Test the streams topology

3

Now create the following file at src/test/java/io/confluent/developer/TumblingWindowTest.java. Testing a Kafka streams application requires a bit of test harness code, but the org.apache.kafka.streams.TopologyTestDriver class makes this easy.

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

package io.confluent.developer;

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.TestInputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.After;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;

import io.confluent.developer.avro.Rating;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerializer;

import static org.junit.Assert.assertEquals;

public class TumblingWindowTest {
    private final static String TEST_CONFIG_FILE = "configuration/test.properties";
    private TopologyTestDriver testDriver;


    private SpecificAvroSerializer<Rating> makeRatingSerializer(Properties allProps) {
        SpecificAvroSerializer<Rating> serializer = new SpecificAvroSerializer<>();

        Map<String, String> config = new HashMap<>();
        for (final String name: allProps.stringPropertyNames())
                    config.put(name, allProps.getProperty(name));
        serializer.configure(config, false);

        return serializer;
    }

    private List<RatingCount> readOutputTopic(TopologyTestDriver testDriver,
                                              String outputTopic,
                                              Deserializer<String> keyDeserializer,
                                              Deserializer<String> valueDeserializer) {
        return testDriver
            .createOutputTopic(outputTopic, keyDeserializer, valueDeserializer)
            .readKeyValuesToList()
            .stream()
            .filter(Objects::nonNull)
            .map(record -> new RatingCount(record.key, record.value))
            .collect(Collectors.toList());
    }

    @Test
    public void testWindows() throws IOException {
        TumblingWindow tw = new TumblingWindow();
        Properties allProps = tw.buildStreamsProperties(tw.loadEnvProperties(TEST_CONFIG_FILE));

        String inputTopic = allProps.getProperty("rating.topic.name");
        String outputTopic = allProps.getProperty("rating.count.topic.name");

        Topology topology = tw.buildTopology(allProps);
        testDriver = new TopologyTestDriver(topology, allProps);

        Serializer<String> stringSerializer = Serdes.String().serializer();
        SpecificAvroSerializer<Rating> ratingSerializer = makeRatingSerializer(allProps);
        Deserializer<String> stringDeserializer = Serdes.String().deserializer();

        List<Rating> ratings = new ArrayList<>();
        ratings.add(Rating.newBuilder().setTitle("Super Mario Bros.").setReleaseYear(1993).setRating(3.5).setTimestamp("2019-04-25T11:15:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Super Mario Bros.").setReleaseYear(1993).setRating(2.0).setTimestamp("2019-04-25T11:40:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("A Walk in the Clouds").setReleaseYear(1998).setRating(3.6).setTimestamp("2019-04-25T13:00:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("A Walk in the Clouds").setReleaseYear(1998).setRating(7.1).setTimestamp("2019-04-25T13:01:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Die Hard").setReleaseYear(1988).setRating(8.2).setTimestamp("2019-04-25T18:00:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Die Hard").setReleaseYear(1988).setRating(7.6).setTimestamp("2019-04-25T18:05:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("The Big Lebowski").setReleaseYear(1998).setRating(8.6).setTimestamp("2019-04-25T19:30:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("The Big Lebowski").setReleaseYear(1998).setRating(7.0).setTimestamp("2019-04-25T19:35:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Tree of Life").setReleaseYear(2011).setRating(4.9).setTimestamp("2019-04-25T21:00:00-0000").build());
        ratings.add(Rating.newBuilder().setTitle("Tree of Life").setReleaseYear(2011).setRating(9.9).setTimestamp("2019-04-25T21:11:00-0000").build());

        List<RatingCount> ratingCounts = new ArrayList<>();
        ratingCounts.add(new RatingCount("Super Mario Bros.", "1"));
        ratingCounts.add(new RatingCount("Super Mario Bros.", "1"));
        ratingCounts.add(new RatingCount("A Walk in the Clouds", "1"));
        ratingCounts.add(new RatingCount("A Walk in the Clouds", "2"));
        ratingCounts.add(new RatingCount("Die Hard", "1"));
        ratingCounts.add(new RatingCount("Die Hard", "2"));
        ratingCounts.add(new RatingCount("The Big Lebowski", "1"));
        ratingCounts.add(new RatingCount("The Big Lebowski", "2"));
        ratingCounts.add(new RatingCount("Tree of Life", "1"));
        ratingCounts.add(new RatingCount("Tree of Life", "1"));

        final TestInputTopic<String, Rating>
            testDriverInputTopic =
            testDriver.createInputTopic(inputTopic, stringSerializer, ratingSerializer);

        for (Rating rating : ratings) {
            testDriverInputTopic.pipeInput(rating.getTitle(), rating);
        }

        List<RatingCount> actualOutput = readOutputTopic(testDriver,
                                                         outputTopic,
                                                         stringDeserializer,
                                                         stringDeserializer);

        assertEquals(ratingCounts.size(), actualOutput.size());
        for(int n = 0; n < ratingCounts.size(); n++) {
            assertEquals(ratingCounts.get(n).toString(), actualOutput.get(n).toString());
        }
    }

    @After
    public void cleanup() {
        testDriver.close();
    }
}

class RatingCount {

    private final String key;
    private final String value;

    public RatingCount(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String toString() {
        return key + "=" + value;
    }
}

Invoke the tests

4

Now run the test, which is as simple as:

./gradlew test