How to create hopping windows

Question:

If you have time series events in a Kafka topic, how can you group them into fixed-size, possibly overlapping, contiguous time intervals to identify a specific scenario?

Edit this page

Example use case:

You want to build an alerting system that automatically detects if the temperature of a room drops below a threshold over a period of time. In this tutorial, we'll write a program that monitors a stream of temperature readings and detects when the temperature drops below 45 degrees Fahrenheit for a period of 10 minutes.

Hands-on code example:

Short Answer

Create a TABLE with the WINDOW HOPPING syntax, and specify the window duration with SIZE and its advance interval with ADVANCE BY within the parentheses.

SELECT
    ID,
    TIMESTAMPTOSTRING(WINDOWSTART, 'HH:mm:ss', 'UTC') AS START_PERIOD,
    TIMESTAMPTOSTRING(WINDOWEND, 'HH:mm:ss', 'UTC') AS END_PERIOD,
    SUM(READING)/COUNT(READING) AS AVG_READING
  FROM TEMPERATURE_READINGS
    WINDOW HOPPING (SIZE 10 MINUTES, ADVANCE BY 5 MINUTES)
  GROUP BY ID
  HAVING SUM(READING)/COUNT(READING) < 45
  EMIT CHANGES
  LIMIT 3;

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 hopping-windows && cd hopping-windows

Then make the following directories to set up its structure:

mkdir src test

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
  ksqldb-server:
    image: confluentinc/ksqldb-server:0.28.2
    hostname: ksqldb-server
    container_name: ksqldb-server
    depends_on:
    - broker
    - schema-registry
    ports:
    - 8088:8088
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
      KSQL_LOG4J_OPTS: -Dlog4j.configuration=file:/etc/ksqldb/log4j.properties
      KSQL_BOOTSTRAP_SERVERS: broker:9092
      KSQL_HOST_NAME: ksqldb-server
      KSQL_LISTENERS: http://0.0.0.0:8088
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: http://schema-registry:8081
  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.28.2
    container_name: ksqldb-cli
    depends_on:
    - broker
    - ksqldb-server
    entrypoint: /bin/sh
    tty: true
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
    volumes:
    - ./src:/opt/app/src
    - ./test:/opt/app/test

And launch it by running:

docker compose up -d

Write the program interactively using the CLI

4

To begin developing interactively, open up the KSQL CLI:

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

To start off the implementation of this scenario, you need to create a stream that represents the temperature readings coming from the sensors. Since we will be handling time in this scenario, it is important that each reading contains a timestamp indicating when that reading was taken. The field TIMESTAMP will be used for this purpose.

CREATE STREAM TEMPERATURE_READINGS (ID VARCHAR KEY, TIMESTAMP VARCHAR, READING BIGINT)
    WITH (KAFKA_TOPIC = 'TEMPERATURE_READINGS',
          VALUE_FORMAT = 'JSON',
          TIMESTAMP = 'TIMESTAMP',
          TIMESTAMP_FORMAT = 'yyyy-MM-dd HH:mm:ss',
          PARTITIONS = 1);

Now let’s produce some events that represent temperature readings from a sensor. Note how the timestamps are increasing on intervals of 5 minutes, to indicate that the sensor emits those events every 5 minutes. Moreover, note that we simulate a temperature drop from 02:25 until 02:40. This is the period that our alerting system should focus on.

INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:15:30', 55);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:20:30', 50);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:25:30', 45);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:30:30', 40);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:35:30', 45);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:40:30', 50);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:45:30', 55);
INSERT INTO TEMPERATURE_READINGS (ID, TIMESTAMP, READING) VALUES ('1', '2020-01-15 02:50:30', 60);

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

Now here comes the fun part. We need to create a query capable of detecting when the temperature drops below 45 °F for a period of 10 minutes. However, since our sensor emits readings every 5 minutes, we need to come up with a way to detect this even if the drop goes beyond the interval of 10 minutes. Hence why we are using hopping windows for this scenario. Hopping windows may overlap, thus if the temperature dropped for 10 minutes but the drop was kept up to 5 minutes beyond an given window — the query will be able to detect that as well.

Along with implementing a hopping window, we will base our logic on the average temperature within the detected period, and we will show this period through two different fields called START_PERIOD and END_PERIOD. This may come in handy if your alert system needs to display the specific time period associated with each alert.

SELECT
    ID,
    TIMESTAMPTOSTRING(WINDOWSTART, 'HH:mm:ss', 'UTC') AS START_PERIOD,
    TIMESTAMPTOSTRING(WINDOWEND, 'HH:mm:ss', 'UTC') AS END_PERIOD,
    SUM(READING)/COUNT(READING) AS AVG_READING
  FROM TEMPERATURE_READINGS
    WINDOW HOPPING (SIZE 10 MINUTES, ADVANCE BY 5 MINUTES)
  GROUP BY ID
  HAVING SUM(READING)/COUNT(READING) < 45
  EMIT CHANGES
  LIMIT 3;

This query should produce the following output:

+--------------------+--------------------+--------------------+--------------------+
|ID                  |START_PERIOD        |END_PERIOD          |AVG_READING         |
+--------------------+--------------------+--------------------+--------------------+
|1                   |02:25:00            |02:35:00            |42                  |
|1                   |02:30:00            |02:40:00            |40                  |
|1                   |02:30:00            |02:40:00            |42                  |
Limit Reached
Query terminated

Note that the period where the average temperature fell below 45F was exactly from 02:25 until 02:40. This means that our alerting system is working properly. Now let’s create some continuous queries to implement this scenario.

CREATE TABLE TRIGGERED_ALERTS AS
    SELECT
        ID AS KEY,
        AS_VALUE(ID) AS ID,
        TIMESTAMPTOSTRING(WINDOWSTART, 'HH:mm:ss', 'UTC') AS START_PERIOD,
        TIMESTAMPTOSTRING(WINDOWEND, 'HH:mm:ss', 'UTC') AS END_PERIOD,
        SUM(READING)/COUNT(READING) AS AVG_READING
    FROM TEMPERATURE_READINGS
      WINDOW HOPPING (SIZE 10 MINUTES, ADVANCE BY 5 MINUTES)
    GROUP BY ID
    HAVING SUM(READING)/COUNT(READING) < 45;

CREATE STREAM RAW_ALERTS (ID VARCHAR, START_PERIOD VARCHAR, END_PERIOD VARCHAR, AVG_READING BIGINT)
    WITH (KAFKA_TOPIC = 'TRIGGERED_ALERTS',
          VALUE_FORMAT = 'JSON');

CREATE STREAM ALERTS AS
    SELECT
        ID,
        START_PERIOD,
        END_PERIOD,
        AVG_READING
    FROM RAW_ALERTS
    WHERE ID IS NOT NULL
    PARTITION BY ID;

Note that we called the query that detects the temperature drop as TRIGGERED_ALERTS and we modeled as a table, since we are performing some aggregations in the query. But just like the temperature readings, alerts can happen continuously – therefore we transform the table back to a stream so we can have multiple alerts throughout time. Finally, also note that we rekeyed the stream to use the ID field as key.

SELECT
    ID,
    START_PERIOD,
    END_PERIOD,
    AVG_READING
FROM ALERTS
EMIT CHANGES
LIMIT 3;

The output should look similar to:

+--------------------+--------------------+--------------------+--------------------+
|ID                  |START_PERIOD        |END_PERIOD          |AVG_READING         |
+--------------------+--------------------+--------------------+--------------------+
|1                   |02:25:00            |02:35:00            |42                  |
|1                   |02:30:00            |02:40:00            |40                  |
|1                   |02:30:00            |02:40:00            |42                  |
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 ALERTS FROM BEGINNING LIMIT 3;

The output should look similar to:

Key format: JSON or KAFKA_STRING
Value format: JSON or KAFKA_STRING
rowtime: 2020/01/15 02:30:30.000 Z, key: 1, value: {"START_PERIOD":"02:25:00","END_PERIOD":"02:35:00","AVG_READING":42}, partition: 0
rowtime: 2020/01/15 02:30:30.000 Z, key: 1, value: {"START_PERIOD":"02:30:00","END_PERIOD":"02:40:00","AVG_READING":40}, partition: 0
rowtime: 2020/01/15 02:35:30.000 Z, key: 1, value: {"START_PERIOD":"02:30:00","END_PERIOD":"02:40:00","AVG_READING":42}, partition: 0
Topic printing ceased

Write your statements to a file

5

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 TEMPERATURE_READINGS (ID VARCHAR KEY, TIMESTAMP VARCHAR, READING BIGINT)
    WITH (KAFKA_TOPIC = 'TEMPERATURE_READINGS',
          VALUE_FORMAT = 'JSON',
          TIMESTAMP = 'TIMESTAMP',
          TIMESTAMP_FORMAT = 'yyyy-MM-dd HH:mm:ss',
          PARTITIONS = 1);

CREATE TABLE TRIGGERED_ALERTS AS
    SELECT
        ID AS KEY,
        AS_VALUE(ID) AS ID,
        TIMESTAMPTOSTRING(WINDOWSTART, 'HH:mm:ss', 'UTC') AS START_PERIOD,
        TIMESTAMPTOSTRING(WINDOWEND, 'HH:mm:ss', 'UTC') AS END_PERIOD,
        SUM(READING)/COUNT(READING) AS AVG_READING
    FROM TEMPERATURE_READINGS
    WINDOW HOPPING (SIZE 10 MINUTES, ADVANCE BY 5 MINUTES)
    GROUP BY ID HAVING SUM(READING)/COUNT(READING) < 45;

CREATE STREAM RAW_ALERTS (ID VARCHAR, START_PERIOD VARCHAR, END_PERIOD VARCHAR, AVG_READING BIGINT)
    WITH (KAFKA_TOPIC = 'TRIGGERED_ALERTS',
          VALUE_FORMAT = 'JSON');

CREATE STREAM ALERTS AS
    SELECT
        ID,
        START_PERIOD,
        END_PERIOD,
        AVG_READING
    FROM RAW_ALERTS
    WHERE ID IS NOT NULL
    PARTITION BY ID;

Test it

Create the test data

1

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

{
  "inputs": [
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:20:30",
        "READING": 50
      }
    },
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:25:30",
        "READING": 45
      }
    },
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:30:30",
        "READING": 40
      }
    },
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:35:30",
        "READING": 45
      }
    },
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:40:30",
        "READING": 50
      }
    },
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:45:30",
        "READING": 55
      }
    },
    {
      "topic": "TEMPERATURE_READINGS",
      "key": "1",
      "value": {
        "TIMESTAMP": "2020-01-15 02:50:30",
        "READING": 60
      }
    }
  ]
}

Similarly, create a file at test/output.json with the expected outputs.

{
  "outputs": [
    {
      "topic": "ALERTS",
      "key": "1",
      "value": {
        "START_PERIOD": "02:25:00",
        "END_PERIOD": "02:35:00",
        "AVG_READING": 42
      },
      "timestamp": 1579055430000
    },
    {
      "topic": "ALERTS",
      "key": "1",
      "value": {
        "START_PERIOD": "02:30:00",
        "END_PERIOD": "02:40:00",
        "AVG_READING": 40
      },
      "timestamp": 1579055430000
    },
    {
      "topic": "ALERTS",
      "key": "1",
      "value": {
        "START_PERIOD": "02:30:00",
        "END_PERIOD": "02:40:00",
        "AVG_READING": 42
      },
      "timestamp": 1579055730000
    }
  ]
}

Invoke the tests

2

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

docker exec ksqldb-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!

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

  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.

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