Create session windows

Question:

If I have time-series events in a Kafka topic, how can I group them into variable-size, non-overlapping time intervals based on a configurable inactivity period?

Edit this page

Example use case:

Given a topic of click events on a website, there are various ways that we can process it. As well as simply counting the number of clicks in a regular time frame (using hopping or tumbling windows), we can also perform sessionization on the data. Here the length of the time window is based on the concept of a session, which is defined based on a period of inactivity. A given user might visit a website multiple times a day, but in distinct visits. Using session windows, we can analyze the number of clicks and duration per visit.

Code example:

Try it

1
Initialize the project

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

mkdir session-windows && cd session-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.5.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.5.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_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      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.5.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'

  ksqldb:
    image: confluentinc/ksqldb-server:0.11.0
    hostname: ksqldb
    container_name: ksqldb
    depends_on:
      - broker
      - schema-registry
    ports:
      - "8088:8088"
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
      KSQL_BOOTSTRAP_SERVERS: "broker:9092"
      KSQL_HOST_NAME: ksqldb
      KSQL_APPLICATION_ID: "app01"
      KSQL_LISTENERS: "http://0.0.0.0:8088"
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
    volumes:
      - ./src:/opt/app/src
      - ./test:/opt/app/test

And launch it by running:

docker-compose up -d

3
Write the program interactively using the CLI

To begin developing interactively, open up the ksqlDB CLI:

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

The first thing we’ll do is create and populate the stream of click data. An important characteristic of this data is the timestamp because this is what drives the session window. ksqlDB can use either the Kafka message timestamp, or a field from the message value as the timestamp. In this example we’ll use the latter—the event time as stored in the timestamp field of the message value.

CREATE STREAM clicks (ip VARCHAR, url VARCHAR, timestamp VARCHAR)
WITH (KAFKA_TOPIC='clicks',
      TIMESTAMP='timestamp',
      TIMESTAMP_FORMAT='yyyy-MM-dd''T''HH:mm:ssX',
      PARTITIONS=1,
      VALUE_FORMAT='Avro');

Once the stream is created, insert some data to it. Note how the timestamps show how there are different sessions for each IP address.

INSERT INTO clicks (ip, timestamp, url) VALUES ('51.56.119.117','2019-07-18T10:00:00Z','/etiam/justo/etiam/pretium/iaculis.xml');
INSERT INTO clicks (ip, timestamp, url) VALUES ('51.56.119.117','2019-07-18T10:01:00Z','/nullam/orci/pede/venenatis.json');
INSERT INTO clicks (ip, timestamp, url) VALUES ('53.170.33.192','2019-07-18T10:01:31Z','/mauris/morbi/non.jpg');
INSERT INTO clicks (ip, timestamp, url) VALUES ('51.56.119.117','2019-07-18T10:01:36Z','/convallis/nunc/proin.jsp');
INSERT INTO clicks (ip, timestamp, url) VALUES ('53.170.33.192','2019-07-18T10:02:00Z','/vestibulum/vestibulum/ante/ipsum/primis/in.json');
INSERT INTO clicks (ip, timestamp, url) VALUES ('51.56.119.117','2019-07-18T11:03:21Z','/vehicula/consequat/morbi/a/ipsum/integer/a.jpg');
INSERT INTO clicks (ip, timestamp, url) VALUES ('51.56.119.117','2019-07-18T11:03:50Z','/pede/venenatis.jsp');
INSERT INTO clicks (ip, timestamp, url) VALUES ('53.170.33.192','2019-07-18T11:40:00Z','/nec/euismod/scelerisque/quam.xml');
INSERT INTO clicks (ip, timestamp, url) VALUES ('53.170.33.192','2019-07-18T11:40:09Z','/ligula/nec/sem/duis.jsp');

Now that you have stream with some events in it, let’s start to use them. The first thing that we’ll do is ensure that the timestamp that ksqlDB will use for our time-based aggregation is the one that we expect. ksqlDB’s timestamp is exposed as a column called ROWTIME, and we can compare this to our declared timestamp column; they should match. Before checking the timestamps, set the following property to ensure that you’re reading from the beginning of the stream:

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

Now compare the timestamp we want to use (timestamp column) with the system column exposing how KSQL sees the timestamp (ROWTIME):

SELECT TIMESTAMPTOSTRING(ROWTIME,'yyyy-MM-dd HH:mm:ss', 'UTC') AS ROWTIME_STR, TIMESTAMP FROM CLICKS EMIT CHANGES LIMIT 5;

You should see that both columns match in time value (only the formatting differs):

+--------------------+--------------------+
|ROWTIME_STR         |TIMESTAMP           |
+--------------------+--------------------+
|2019-07-18 10:00:00 |2019-07-18T10:00:00Z|
|2019-07-18 10:01:00 |2019-07-18T10:01:00Z|
|2019-07-18 10:01:31 |2019-07-18T10:01:31Z|
|2019-07-18 10:01:36 |2019-07-18T10:01:36Z|
|2019-07-18 10:02:00 |2019-07-18T10:02:00Z|
Limit Reached
Query terminated

Now let’s see how many clicks were made in each user session (based on IP address), and also calculate the duration of the session. To do that, we issue the following transient push query to aggregate the clicks grouped by the IP address. We declare that we want to use session windowing, with a gap of five minutes or more denoting the end of the previous session. The query also captures the window start and end times, and it uses these to calculate the session duration.

For the purposes of this example only, we are also going to configure ksqlDB to buffer the aggregates as it builds them. This makes the query feel like it responds more slowly, but it means that you get just one row per window. This makes it simpler to understand the concept:

SET 'ksql.streams.cache.max.bytes.buffering'='2000000';

The following will block and continue to return results until its limit is reached or you tell it to stop.

SELECT IP,
       TIMESTAMPTOSTRING(WINDOWSTART,'yyyy-MM-dd HH:mm:ss', 'UTC') AS SESSION_START_TS,
       TIMESTAMPTOSTRING(WINDOWEND,'yyyy-MM-dd HH:mm:ss', 'UTC')   AS SESSION_END_TS,
       COUNT(*)                                                    AS CLICK_COUNT,
       WINDOWEND - WINDOWSTART                                     AS SESSION_LENGTH_MS
  FROM CLICKS
       WINDOW SESSION (5 MINUTES)
GROUP BY IP
EMIT CHANGES LIMIT 4;

This should yield the following output:

+--------------------+--------------------+--------------------+--------------------+--------------------+
|IP                  |SESSION_START_TS    |SESSION_END_TS      |CLICK_COUNT         |SESSION_LENGTH_MS   |
+--------------------+--------------------+--------------------+--------------------+--------------------+
|51.56.119.117       |2019-07-18 10:00:00 |2019-07-18 10:01:36 |3                   |96000               |
|53.170.33.192       |2019-07-18 10:01:31 |2019-07-18 10:02:00 |2                   |29000               |
|51.56.119.117       |2019-07-18 11:03:21 |2019-07-18 11:03:50 |2                   |29000               |
|53.170.33.192       |2019-07-18 11:40:00 |2019-07-18 11:40:09 |2                   |9000                |
Limit Reached
Query terminated

When ksqlDB builds aggregates, it emits the values as new messages are processed, meaning that you may see intermediate results on the screen too. When ksql.streams.cache.max.bytes.buffering was set above, this suppressed these. If you change the value to zero and re-run the above query you’ll see the intermediate emissions too:

SET 'ksql.streams.cache.max.bytes.buffering'='0';
SELECT IP,
       TIMESTAMPTOSTRING(WINDOWSTART,'yyyy-MM-dd HH:mm:ss', 'UTC') AS SESSION_START_TS,
       TIMESTAMPTOSTRING(WINDOWEND,'yyyy-MM-dd HH:mm:ss', 'UTC')   AS SESSION_END_TS,
       COUNT(*)                                                    AS CLICK_COUNT,
       WINDOWEND - WINDOWSTART                                     AS SESSION_LENGTH_MS
  FROM CLICKS
       WINDOW SESSION (5 MINUTES)
GROUP BY IP
EMIT CHANGES
LIMIT 9;

This time you’ll see each aggregate update and be re-emitted as new messages are processed:

+--------------------+--------------------+--------------------+--------------------+--------------------+
|IP                  |SESSION_START_TS    |SESSION_END_TS      |CLICK_COUNT         |SESSION_LENGTH_MS   |
+--------------------+--------------------+--------------------+--------------------+--------------------+
|51.56.119.117       |2019-07-18 10:00:00 |2019-07-18 10:00:00 |1                   |0                   |
|51.56.119.117       |2019-07-18 10:00:00 |2019-07-18 10:01:00 |2                   |60000               |
|53.170.33.192       |2019-07-18 10:01:31 |2019-07-18 10:01:31 |1                   |0                   |
|51.56.119.117       |2019-07-18 10:00:00 |2019-07-18 10:01:36 |3                   |96000               |
|53.170.33.192       |2019-07-18 10:01:31 |2019-07-18 10:02:00 |2                   |29000               |
|51.56.119.117       |2019-07-18 11:03:21 |2019-07-18 11:03:21 |1                   |0                   |
|51.56.119.117       |2019-07-18 11:03:21 |2019-07-18 11:03:50 |2                   |29000               |
|53.170.33.192       |2019-07-18 11:40:00 |2019-07-18 11:40:00 |1                   |0                   |
|53.170.33.192       |2019-07-18 11:40:00 |2019-07-18 11:40:09 |2                   |9000                |
Limit Reached
Query terminated

Now let’s take this snapshot, and persist it as a table, populated continually by the results of the ongoing query:

CREATE TABLE IP_SESSIONS AS
SELECT IP,
       TIMESTAMPTOSTRING(WINDOWSTART,'yyyy-MM-dd HH:mm:ss', 'UTC') AS SESSION_START_TS,
       TIMESTAMPTOSTRING(WINDOWEND,'yyyy-MM-dd HH:mm:ss', 'UTC')   AS SESSION_END_TS,
       COUNT(*)                                                    AS CLICK_COUNT,
       WINDOWEND - WINDOWSTART                                     AS SESSION_LENGTH_MS
  FROM CLICKS
       WINDOW SESSION (5 MINUTES)
GROUP BY IP;

This creates and populate a table that we could query with a SELECT, but also a Kafka topic, which we can examine from within KSQL using PRINT.

PRINT IP_SESSIONS FROM BEGINNING LIMIT 5;

Notice the key for each message. ksqlDB has combined the grouping key (IP address) with its window boundaries. It should look something like this:

Key format: SESSION(KAFKA_STRING)
Value format: AVRO
rowtime: 7/18/19 10:00:00 AM UTC, key: [51.56.119.117@1563444000000/1563444000000], value: {"SESSION_START_TS": "2019-07-18 10:00:00", "SESSION_END_TS": "2019-07-18 10:00:00", "CLICK_COUNT": 1, "SESSION_LENGTH_MS": 0}
rowtime: 7/18/19 10:00:00 AM UTC, key: [51.56.119.117@1563444000000/1563444000000], value: <null>
rowtime: 7/18/19 10:01:00 AM UTC, key: [51.56.119.117@1563444000000/1563444060000], value: {"SESSION_START_TS": "2019-07-18 10:00:00", "SESSION_END_TS": "2019-07-18 10:01:00", "CLICK_COUNT": 2, "SESSION_LENGTH_MS": 60000}
rowtime: 7/18/19 10:01:31 AM UTC, key: [53.170.33.192@1563444091000/1563444091000], value: {"SESSION_START_TS": "2019-07-18 10:01:31", "SESSION_END_TS": "2019-07-18 10:01:31", "CLICK_COUNT": 1, "SESSION_LENGTH_MS": 0}
rowtime: 7/18/19 10:01:00 AM UTC, key: [51.56.119.117@1563444000000/1563444060000], value: <null>
Topic printing ceased

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 clicks (ip VARCHAR, url VARCHAR, timestamp VARCHAR)
WITH (KAFKA_TOPIC='clicks',
      TIMESTAMP='timestamp',
      TIMESTAMP_FORMAT='yyyy-MM-dd''T''HH:mm:ssX',
      PARTITIONS=1,
      VALUE_FORMAT='Avro');

CREATE TABLE IP_SESSIONS AS
SELECT IP,
       TIMESTAMPTOSTRING(WINDOWSTART,'yyyy-MM-dd HH:mm:ss', 'UTC') AS SESSION_START_TS,
       TIMESTAMPTOSTRING(WINDOWEND,'yyyy-MM-dd HH:mm:ss', 'UTC')   AS SESSION_END_TS,
       COUNT(*)                                                    AS CLICK_COUNT,
       WINDOWEND - WINDOWSTART                                     AS SESSION_LENGTH_MS
  FROM CLICKS
       WINDOW SESSION (5 MINUTES)
GROUP BY IP;

Test it

1
Create the test data

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

{
  "inputs": [
    { "topic": "clicks", "value": { "IP": "51.56.119.117", "URL": "/etiam/justo/etiam/pretium/iaculis.xml", "TIMESTAMP": "2019-07-18T10:00:00Z" } },
    { "topic": "clicks", "value": { "IP": "51.56.119.117", "URL": "/nullam/orci/pede/venenatis.json", "TIMESTAMP": "2019-07-18T10:01:00Z" } },
    { "topic": "clicks", "value": { "IP": "53.170.33.192", "URL": "/mauris/morbi/non.jpg", "TIMESTAMP": "2019-07-18T10:01:31Z" } },
    { "topic": "clicks", "value": { "IP": "51.56.119.117", "URL": "/convallis/nunc/proin.jsp", "TIMESTAMP": "2019-07-18T10:01:36Z" } },
    { "topic": "clicks", "value": { "IP": "53.170.33.192", "URL": "/vestibulum/vestibulum/ante/ipsum/primis/in.json", "TIMESTAMP": "2019-07-18T10:02:00Z" } },
    { "topic": "clicks", "value": { "IP": "51.56.119.117", "URL": "/vehicula/consequat/morbi/a/ipsum/integer/a.jpg", "TIMESTAMP": "2019-07-18T11:03:21Z" } },
    { "topic": "clicks", "value": { "IP": "51.56.119.117", "URL": "/pede/venenatis.jsp", "TIMESTAMP": "2019-07-18T11:03:50Z" } },
    { "topic": "clicks", "value": { "IP": "53.170.33.192", "URL": "/nec/euismod/scelerisque/quam.xml", "TIMESTAMP": "2019-07-18T11:40:00Z" } },
    { "topic": "clicks", "value": { "IP": "53.170.33.192", "URL": "/ligula/nec/sem/duis.jsp", "TIMESTAMP": "2019-07-18T11:40:09Z" } }
  ]
}

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

{
  "outputs": [
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563444000000, "end":1563444000000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 10:00:00", "SESSION_START_TS":"2019-07-18 10:00:00", "CLICK_COUNT":1, "SESSION_LENGTH_MS":0},"timestamp":1563444000000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563444000000, "end":1563444000000,"type":"session"},"value": null,"timestamp":1563444000000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563444000000, "end":1563444060000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 10:01:00", "SESSION_START_TS":"2019-07-18 10:00:00", "CLICK_COUNT":2, "SESSION_LENGTH_MS":60000},"timestamp":1563444060000},
    {"topic":"IP_SESSIONS","key": "53.170.33.192", "window": {"start":1563444091000, "end":1563444091000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 10:01:31", "SESSION_START_TS":"2019-07-18 10:01:31", "CLICK_COUNT":1, "SESSION_LENGTH_MS":0},"timestamp":1563444091000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563444000000, "end":1563444060000,"type":"session"},"value": null,"timestamp":1563444060000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563444000000, "end":1563444096000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 10:01:36", "SESSION_START_TS":"2019-07-18 10:00:00", "CLICK_COUNT":3, "SESSION_LENGTH_MS":96000},"timestamp":1563444096000},
    {"topic":"IP_SESSIONS","key": "53.170.33.192", "window": {"start":1563444091000, "end":1563444091000,"type":"session"},"value": null,"timestamp":1563444091000},
    {"topic":"IP_SESSIONS","key": "53.170.33.192", "window": {"start":1563444091000, "end":1563444120000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 10:02:00", "SESSION_START_TS":"2019-07-18 10:01:31", "CLICK_COUNT":2, "SESSION_LENGTH_MS":29000},"timestamp":1563444120000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563447801000, "end":1563447801000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 11:03:21", "SESSION_START_TS":"2019-07-18 11:03:21", "CLICK_COUNT":1, "SESSION_LENGTH_MS":0},"timestamp":1563447801000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563447801000, "end":1563447801000,"type":"session"},"value": null,"timestamp":1563447801000},
    {"topic":"IP_SESSIONS","key": "51.56.119.117", "window": {"start":1563447801000, "end":1563447830000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 11:03:50", "SESSION_START_TS":"2019-07-18 11:03:21", "CLICK_COUNT":2, "SESSION_LENGTH_MS":29000},"timestamp":1563447830000},
    {"topic":"IP_SESSIONS","key": "53.170.33.192", "window": {"start":1563450000000, "end":1563450000000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 11:40:00", "SESSION_START_TS":"2019-07-18 11:40:00", "CLICK_COUNT":1, "SESSION_LENGTH_MS":0},"timestamp":1563450000000},
    {"topic":"IP_SESSIONS","key": "53.170.33.192", "window": {"start":1563450000000, "end":1563450000000,"type":"session"},"value": null,"timestamp":1563450000000},
    {"topic":"IP_SESSIONS","key": "53.170.33.192", "window": {"start":1563450000000, "end":1563450009000,"type":"session"},"value": {"SESSION_END_TS":"2019-07-18 11:40:09", "SESSION_START_TS":"2019-07-18 11:40:00", "CLICK_COUNT":2, "SESSION_LENGTH_MS":9000},"timestamp":1563450009000}
]
}

2
Invoke the tests

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

#!/usr/bin/env bash

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

tr '\n' ' ' < src/statements.sql | \
sed 's/;/;\'$'\n''/g' | \
while read stmt; do
    echo '{"ksql":"'$stmt'", "streamsProperties": {}}' | \
        curl -s -X "POST" "http://localhost:8088/ksql" \
             -H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8" \
             -d @- | \
        jq
done

Deploy on Confluent Cloud

1
Run your app to Confluent Cloud

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

First, create your Kafka cluster in Confluent Cloud. Use the promo code CC100KTS to receive an additional $100 free usage (details).

Next, from the Confluent Cloud UI, click on Tools & client config 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 your run application locally while your Kafka topics and stream processing is backed to your Confluent Cloud instance.