How to create tumbling windows

Problem:

you have time-series events in a Kafka topic, and you want to 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 ratings of movies. In this tutorial, we'll write a program that maintains tumbling windows counting the total number of ratings that each movie has received.

Code example:

Try it

1
Initialize the project

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

mkdir tumbling-windows && cd tumbling-windows

Then make the following directories to set up its structure:

mkdir src test

2
Get Confluent Platform

Next, create the following docker-compose.yml file to obtain Confluent Platform:

---
version: '2'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.3.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-enterprise-kafka:5.3.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: broker:9092
      CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      CONFLUENT_METRICS_ENABLE: 'true'
      CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'

  schema-registry:
    image: confluentinc/cp-schema-registry:5.3.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - zookeeper
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: 'zookeeper:2181'

  ksql-server:
    image: confluentinc/cp-ksql-server:5.3.0
    hostname: ksql-server
    container_name: ksql-server
    depends_on:
      - broker
      - schema-registry
    ports:
      - "8088:8088"
    environment:
      KSQL_CONFIG_DIR: "/etc/ksql"
      KSQL_LOG4J_OPTS: "-Dlog4j.configuration=file:/etc/ksql/log4j-rolling.properties"
      KSQL_BOOTSTRAP_SERVERS: "broker:9092"
      KSQL_HOST_NAME: ksql-server
      KSQL_APPLICATION_ID: "cp-all-in-one"
      KSQL_LISTENERS: "http://0.0.0.0:8088"
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      KSQL_PRODUCER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringProducerInterceptor"
      KSQL_CONSUMER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor"

  ksql-cli:
    image: confluentinc/cp-ksql-cli:5.3.0
    container_name: ksql-cli
    depends_on:
      - broker
      - ksql-server
    entrypoint: /bin/sh
    tty: true
    volumes:
      - ./src:/opt/app/src
      - ./test:/opt/app/test

And launch it by running:

docker-compose up

3
Write the program interactively using the CLI

To begin developing interactively, open up the KSQL CLI:

docker exec -it ksql-cli ksql http://ksql-server:8088

The first thing we’ll need to start modeling this scenario is a stream that represents ratings of movies. One important attribute of these events is their timestamp since we’ll be modeling the number of ratings that each movie receives over time.

CREATE STREAM ratings (title VARCHAR, release_year INT, rating DOUBLE, timestamp VARCHAR)
    WITH (kafka_topic='ratings',
          key='title',
          timestamp='timestamp',
          timestamp_format='yyyy-MM-dd HH:mm:ss',
          partitions=1,
          value_format='avro');

Produce events that represent ratings about each movie over time. Note how the timestamps are varying across different hours of the day.

INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('Die Hard', 1998, 8.2, '2019-07-09 01:00:00');
INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('Die Hard', 1998, 4.5, '2019-07-09 05:00:00');
INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('Die Hard', 1998, 5.1, '2019-07-09 07:00:00');

INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('Tree of Life', 2011, 4.9, '2019-07-09 09:00:00');
INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('Tree of Life', 2011, 5.6, '2019-07-09 08:00:00');

INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('A Walk in the Clouds', 1995, 3.6, '2019-07-09 12:00:00');
INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('A Walk in the Clouds', 1995, 6.0, '2019-07-09 15:00:00');
INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('A Walk in the Clouds', 1995, 4.6, '2019-07-09 22:00:00');

INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('The Big Lebowski', 1998, 9.9, '2019-07-09 05:00:00');
INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('The Big Lebowski', 1998, 4.2, '2019-07-09 02:00:00');

INSERT INTO ratings (title, release_year, rating, timestamp) VALUES ('Super Mario Bros.', 1993, 3.5, '2019-07-09 18:00:00');

Now that you have stream with some events in it, let’s start to leverage them. The first thing to do is set the following properties to ensure that you’re reading from the beginning of the stream:

SET 'auto.offset.reset' = 'earliest';

Let’s figure out how many ratings were given to each movie in 6 hour tumbling intervals. To do that, we issue the following transient query to aggregate the ratings grouped by the movie’s name. This tells KSQL that you only want to sum up the ratings on a per movie basis. It also captures the window start and end times. These functions describe the boundaries that represent each 6 hour interval. The following will block and continue to return results until its limit is reached or you tell it to stop.

SELECT title,
       COUNT(*) AS rating_count,
       WINDOWSTART() AS window_start,
       WINDOWEND() AS window_end
FROM ratings
WINDOW TUMBLING (SIZE 6 HOURS)
GROUP BY title
LIMIT 11;

This should yield the following output:

Die Hard | 1 | 1562630400000 | 1562652000000
Die Hard | 2 | 1562630400000 | 1562652000000
Die Hard | 1 | 1562652000000 | 1562673600000
Tree of Life | 1 | 1562652000000 | 1562673600000
Tree of Life | 2 | 1562652000000 | 1562673600000
A Walk in the Clouds | 1 | 1562673600000 | 1562695200000
A Walk in the Clouds | 2 | 1562673600000 | 1562695200000
A Walk in the Clouds | 1 | 1562695200000 | 1562716800000
The Big Lebowski | 1 | 1562630400000 | 1562652000000
The Big Lebowski | 2 | 1562630400000 | 1562652000000
Super Mario Bros. | 1 | 1562695200000 | 1562716800000
Limit Reached
Query terminated

That’s a fine snapshot, but we want to make this rolling count of ratings continuous. The following creates a new table that is continously populated by its query:

CREATE TABLE rating_count
    WITH (kafka_topic='rating_count') AS
    SELECT title,
           COUNT(*) AS rating_count,
           WINDOWSTART() AS window_start,
           WINDOWEND() AS window_end
    FROM ratings
    WINDOW TUMBLING (SIZE 6 HOURS)
    GROUP BY title;

As a bonus, we can prove to ourselves that the window boundaries are in fact 6 hour intervals. Run the following transient query, which uses the TIMESTAMPTOSTRING function to convert the UNIX timestamps into something that we can read:

SELECT title,
       rating_count,
       TIMESTAMPTOSTRING(window_start, 'yyy-MM-dd HH:mm:ss'),
       TIMESTAMPTOSTRING(window_end, 'yyy-MM-dd HH:mm:ss')
FROM rating_count
LIMIT 11;

The output should look similar to:

Die Hard | 1 | 2019-07-09 00:00:00 | 2019-07-09 06:00:00
Die Hard | 2 | 2019-07-09 00:00:00 | 2019-07-09 06:00:00
Die Hard | 1 | 2019-07-09 06:00:00 | 2019-07-09 12:00:00
Tree of Life | 1 | 2019-07-09 06:00:00 | 2019-07-09 12:00:00
Tree of Life | 2 | 2019-07-09 06:00:00 | 2019-07-09 12:00:00
A Walk in the Clouds | 1 | 2019-07-09 12:00:00 | 2019-07-09 18:00:00
A Walk in the Clouds | 2 | 2019-07-09 12:00:00 | 2019-07-09 18:00:00
A Walk in the Clouds | 1 | 2019-07-09 18:00:00 | 2019-07-10 00:00:00
The Big Lebowski | 1 | 2019-07-09 00:00:00 | 2019-07-09 06:00:00
The Big Lebowski | 2 | 2019-07-09 00:00:00 | 2019-07-09 06:00:00
Super Mario Bros. | 1 | 2019-07-09 18:00:00 | 2019-07-10 00:00:00
Limit Reached
Query terminated

Finally, let’s see what’s available on the underlying Kafka topic for the table. We can print that out easily.

PRINT 'rating_count' FROM BEGINNING LIMIT 11;

Notice that the key for each message contains some strange characters that aren’t quite printable. KSQL has combined the grouping key (movie title) with its window boundaries using a format that’s not quite printable in this format. It should look something like this:

Format:AVRO
7/9/19 1:00:00 AM UTC, Die Hardk��, {"TITLE": "Die Hard", "RATING_COUNT": 1, "WINDOW_START": 1562630400000, "WINDOW_END": 1562652000000}
7/9/19 5:00:00 AM UTC, Die Hardk��, {"TITLE": "Die Hard", "RATING_COUNT": 2, "WINDOW_START": 1562630400000, "WINDOW_END": 1562652000000}
7/9/19 7:00:00 AM UTC, Die Hardk�Q?, {"TITLE": "Die Hard", "RATING_COUNT": 1, "WINDOW_START": 1562652000000, "WINDOW_END": 1562673600000}
7/9/19 9:00:00 AM UTC, Tree of Lifek�Q?, {"TITLE": "Tree of Life", "RATING_COUNT": 1, "WINDOW_START": 1562652000000, "WINDOW_END": 1562673600000}
7/9/19 9:00:00 AM UTC, Tree of Lifek�Q?, {"TITLE": "Tree of Life", "RATING_COUNT": 2, "WINDOW_START": 1562652000000, "WINDOW_END": 1562673600000}
7/9/19 12:00:00 PM UTC, A Walk in the Cloudsk֚�, {"TITLE": "A Walk in the Clouds", "RATING_COUNT": 1, "WINDOW_START": 1562673600000, "WINDOW_END": 1562695200000}
7/9/19 3:00:00 PM UTC, A Walk in the Cloudsk֚�, {"TITLE": "A Walk in the Clouds", "RATING_COUNT": 2, "WINDOW_START": 1562673600000, "WINDOW_END": 1562695200000}
7/9/19 10:00:00 PM UTC, A Walk in the Cloudsk��m, {"TITLE": "A Walk in the Clouds", "RATING_COUNT": 1, "WINDOW_START": 1562695200000, "WINDOW_END": 1562716800000}
7/9/19 5:00:00 AM UTC, The Big Lebowskik��, {"TITLE": "The Big Lebowski", "RATING_COUNT": 1, "WINDOW_START": 1562630400000, "WINDOW_END": 1562652000000}
7/9/19 5:00:00 AM UTC, The Big Lebowskik��, {"TITLE": "The Big Lebowski", "RATING_COUNT": 2, "WINDOW_START": 1562630400000, "WINDOW_END": 1562652000000}
7/9/19 6:00:00 PM UTC, Super Mario Bros.k��m, {"TITLE": "Super Mario Bros.", "RATING_COUNT": 1, "WINDOW_START": 1562695200000, "WINDOW_END": 1562716800000}

4
Write your statements to a file

Now that you have a series of statements that’s doing the right thing, the last step is to put them into a file so that they can be used outside the CLI session. Create a file at src/statements.sql with the following content:

CREATE STREAM ratings (title VARCHAR, release_year INT, rating DOUBLE, timestamp VARCHAR)
    WITH (kafka_topic='ratings',
          key='title',
          timestamp='timestamp',
          timestamp_format='yyyy-MM-dd HH:mm:ss',
          partitions=1,
          value_format='avro');

CREATE TABLE rating_count
    WITH (kafka_topic='rating_count') AS
    SELECT title,
           COUNT(*) AS rating_count,
           WINDOWSTART() AS window_start,
           WINDOWEND() AS window_end
    FROM ratings
    WINDOW TUMBLING (SIZE 6 HOURS)
    GROUP BY title;

Test it

1
Create the test data

Create a file at test/input.json with the inputs for testing:

{
  "inputs": [
    {
      "topic": "ratings",
      "key": "Die Hard",
      "value": {
        "title": "Die Hard",
        "release_year": 1998,
        "rating": 8.2,
        "timestamp": "2019-07-09 01:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "Die Hard",
      "value": {
        "title": "Die Hard",
        "release_year": 1998,
        "rating": 4.5,
        "timestamp": "2019-07-09 05:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "Die Hard",
      "value": {
        "title": "Die Hard",
        "release_year": 1998,
        "rating": 5.1,
        "timestamp": "2019-07-09 07:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "Tree of Life",
      "value": {
        "title": "Tree of Life",
        "release_year": 2011,
        "rating": 4.9,
        "timestamp": "2019-07-09 09:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "Tree of Life",
      "value": {
        "title": "Tree of Life",
        "release_year": 2011,
        "rating": 5.6,
        "timestamp": "2019-07-09 08:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "A Walk in the Clouds",
      "value": {
        "title": "A Walk in the Clouds",
        "release_year": 1995,
        "rating": 3.6,
        "timestamp": "2019-07-09 12:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "A Walk in the Clouds",
      "value": {
        "title": "A Walk in the Clouds",
        "release_year": 1995,
        "rating": 6.0,
        "timestamp": "2019-07-09 15:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "A Walk in the Clouds",
      "value": {
        "title": "A Walk in the Clouds",
        "release_year": 1995,
        "rating": 4.6,
        "timestamp": "2019-07-09 22:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "The Big Lebowski",
      "value": {
        "title": "The Big Lebowski",
        "release_year": 1998,
        "rating": 9.9,
        "timestamp": "2019-07-09 05:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "The Big Lebowski",
      "value": {
        "title": "The Big Lebowski",
        "release_year": 1998,
        "rating": 4.2,
        "timestamp": "2019-07-09 02:00:00"
      }
    },
    {
      "topic": "ratings",
      "key": "Super Mario Bros.",
      "value": {
        "title": "Super Mario Bros.",
        "release_year": 1993,
        "rating": 3.5,
        "timestamp": "2019-07-09 18:00:00"
      }
    }
  ]
}

Similarly, create a file at test/output.json with the expected outputs. Notice that because KSQL joins its grouping key with the window boundaries, we need to use a bit of extra expression to describe what to expect. We leverage the window key to describe the start and end boundaries that the key represents.

{
  "outputs": [
    {
      "topic": "rating_count",
      "key": "Die Hard",
      "window": {
        "start": 1562630400000,
        "end": 1562652000000,
        "type": "time"
      },
      "value": {
        "TITLE": "Die Hard",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562630400000,
        "WINDOW_END": 1562652000000
      },
      "timestamp": 1562634000000
    },
    {
      "topic": "rating_count",
      "key": "Die Hard",
      "window": {
        "start": 1562630400000,
        "end": 1562652000000,
        "type": "time"
      },
      "value": {
        "TITLE": "Die Hard",
        "RATING_COUNT": 2,
        "WINDOW_START": 1562630400000,
        "WINDOW_END": 1562652000000
      },
      "timestamp": 1562648400000
    },
    {
      "topic": "rating_count",
      "key": "Die Hard",
      "window": {
        "start": 1562652000000,
        "end": 1562673600000,
        "type": "time"
      },
      "value": {
        "TITLE": "Die Hard",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562652000000,
        "WINDOW_END": 1562673600000
      },
      "timestamp": 1562655600000
    },
    {
      "topic": "rating_count",
      "key": "Tree of Life",
      "window": {
        "start": 1562652000000,
        "end": 1562673600000,
        "type": "time"
      },
      "value": {
        "TITLE": "Tree of Life",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562652000000,
        "WINDOW_END": 1562673600000
      },
      "timestamp": 1562662800000
    },
    {
      "topic": "rating_count",
      "key": "Tree of Life",
      "window": {
        "start": 1562652000000,
        "end": 1562673600000,
        "type": "time"
      },
      "value": {
        "TITLE": "Tree of Life",
        "RATING_COUNT": 2,
        "WINDOW_START": 1562652000000,
        "WINDOW_END": 1562673600000
      },
      "timestamp": 1562662800000
    },
    {
      "topic": "rating_count",
      "key": "A Walk in the Clouds",
      "window": {
        "start": 1562673600000,
        "end": 1562695200000,
        "type": "time"
      },
      "value": {
        "TITLE": "A Walk in the Clouds",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562673600000,
        "WINDOW_END": 1562695200000
      },
      "timestamp": 1562673600000
    },
    {
      "topic": "rating_count",
      "key": "A Walk in the Clouds",
      "window": {
        "start": 1562673600000,
        "end": 1562695200000,
        "type": "time"
      },
      "value": {
        "TITLE": "A Walk in the Clouds",
        "RATING_COUNT": 2,
        "WINDOW_START": 1562673600000,
        "WINDOW_END": 1562695200000
      },
      "timestamp": 1562684400000
    },
    {
      "topic": "rating_count",
      "key": "A Walk in the Clouds",
      "window": {
        "start": 1562695200000,
        "end": 1562716800000,
        "type": "time"
      },
      "value": {
        "TITLE": "A Walk in the Clouds",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562695200000,
        "WINDOW_END": 1562716800000
      },
      "timestamp": 1562709600000
    },
    {
      "topic": "rating_count",
      "key": "The Big Lebowski",
      "window": {
        "start": 1562630400000,
        "end": 1562652000000,
        "type": "time"
      },
      "value": {
        "TITLE": "The Big Lebowski",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562630400000,
        "WINDOW_END": 1562652000000
      },
      "timestamp": 1562648400000
    },
    {
      "topic": "rating_count",
      "key": "The Big Lebowski",
      "window": {
        "start": 1562630400000,
        "end": 1562652000000,
        "type": "time"
      },
      "value": {
        "TITLE": "The Big Lebowski",
        "RATING_COUNT": 2,
        "WINDOW_START": 1562630400000,
        "WINDOW_END": 1562652000000
      },
      "timestamp": 1562648400000
    },
    {
      "topic": "rating_count",
      "key": "Super Mario Bros.",
      "window": {
        "start": 1562695200000,
        "end": 1562716800000,
        "type": "time"
      },
      "value": {
        "TITLE": "Super Mario Bros.",
        "RATING_COUNT": 1,
        "WINDOW_START": 1562695200000,
        "WINDOW_END": 1562716800000
      },
      "timestamp": 1562695200000
    }
  ]
}

2
Invoke the tests

Lastly, invoke the tests using the test runner and the statements file that you created earlier:

docker exec ksql-cli ksql-test-runner -i /opt/app/test/input.json -s opt/app/src/statements.sql -o /opt/app/test/output.json

Which should pass:

	 >>> Test passed!

Take it to production

1
Send the statements to the REST API

Launch your statements into production by sending them to the REST API with the following command:

statements=$(< src/statements.sql) && \
    echo '{"ksql":"'$statements'", "streamsProperties": {}}' | \
        curl -X "POST" "http://localhost:8088/ksql" \
             -H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8" \
             -d @- | \
        jq