How to create tumbling windows


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


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


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:

buildscript {
  repositories {
  dependencies {
    classpath ''

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 {

  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'
  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/']

jar {
  manifest {
        '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/

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 events


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


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/

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.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(""));
        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 {
        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("");
        final String ratingCountTopic = allProps.getProperty("");

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


    private String windowedKeyToString(Windowed<String> key) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZZZZ");
        return String.format("[%s@%s/%s]",

    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("", Long.toString(Long.MAX_VALUE));

        NewTopic ratings = 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.");

        TumblingWindow tw = new TumblingWindow();
        Properties allProps = tw.buildStreamsProperties(tw.loadEnvProperties(args[0]));
        Topology topology = tw.buildTopology(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) {

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


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/ 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 {
    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


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


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/

Get ready to observe the counted ratings in the output topic


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


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/ 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:

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


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/

Test the RatingTimestampExtractor class


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/ 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 {

    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


Now create the following file at src/test/java/io/confluent/developer/ 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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

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/";
    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)
            .map(record -> new RatingCount(record.key, record.value))

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

        String inputTopic = allProps.getProperty("");
        String outputTopic = allProps.getProperty("");

        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,

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

    public void cleanup() {

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


Now run the test, which is as simple as:

./gradlew test