How to join a stream and a stream

Question:

If you have event streams in two Kafka topics, how can you join them together and create a new topic based on a common identifying attribute, where the new events are enriched from the original topics?

Edit this page

Example use case:

Suppose you have two streams containing events for orders and shipments. In this tutorial, we'll write a program that joins these two streams to create a new, enriched one. The new stream will tell us which orders have been successfully shipped, how long it took for them to ship, and the warehouse from which they shipped.

Hands-on code example:

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 join-stream-and-stream && cd join-stream-and-stream

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 ksqlDB CLI:

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

First, you’ll need to create a Kafka stream and its underlying topic to represent the orders:

CREATE STREAM orders (ID INT KEY, order_ts VARCHAR, total_amount DOUBLE, customer_name VARCHAR)
    WITH (KAFKA_TOPIC='_orders',
          VALUE_FORMAT='AVRO',
          TIMESTAMP='order_ts',
          TIMESTAMP_FORMAT='yyyy-MM-dd''T''HH:mm:ssX',
          PARTITIONS=4);

Note that we are using the field order_ts as the record’s timestamp. This is going to be important later on when we write queries that need to know about the time each event occurred at. By using a field of the event, we can process the events at any time and get a deterministic result. This is known as event time.

Secondly, you’ll need a Kafka stream and its underlying topic to represent the shipments:

CREATE STREAM shipments (ID VARCHAR KEY, ship_ts VARCHAR, order_id INT, warehouse VARCHAR)
    WITH (KAFKA_TOPIC='_shipments',
          VALUE_FORMAT='AVRO',
          TIMESTAMP='ship_ts',
          TIMESTAMP_FORMAT='yyyy-MM-dd''T''HH:mm:ssX',
          PARTITIONS=4);

You might have noticed that we specified 4 partitions for both streams. It’s not random that both streams have the same partition count. For joins to work correctly, the topics need to be co-partitioned, which is a fancy way of saying that all topics have the same number of partitions and are keyed the same way. This helps the stream processing infrastructure reason about where the same "kind" of data is without scanning all of the partitions, which would be prohibitively expensive. If your topics are generated by other ksqlDB operations, ksqlDB will automatically co-partition your topics for you. You can learn more about the joining criteria in the full documentation.

Now let’s play with some events. Create the following orders:

INSERT INTO orders (id, order_ts, total_amount, customer_name) VALUES (1, '2019-03-29T06:01:18Z', 133548.84, 'Ricardo Ferreira');
INSERT INTO orders (id, order_ts, total_amount, customer_name) VALUES (2, '2019-03-29T17:02:20Z', 164839.31, 'Tim Berglund');
INSERT INTO orders (id, order_ts, total_amount, customer_name) VALUES (3, '2019-03-29T13:44:10Z', 90427.66, 'Robin Moffatt');
INSERT INTO orders (id, order_ts, total_amount, customer_name) VALUES (4, '2019-03-29T11:58:25Z', 33462.11, 'Viktor Gamov');

In a similar manner, create the following shipments:

INSERT INTO shipments (id, ship_ts, order_id, warehouse) VALUES ('ship-ch83360', '2019-03-31T18:13:39Z', 1, 'UPS');
INSERT INTO shipments (id, ship_ts, order_id, warehouse) VALUES ('ship-xf72808', '2019-03-31T02:04:13Z', 2, 'UPS');
INSERT INTO shipments (id, ship_ts, order_id, warehouse) VALUES ('ship-kr47454', '2019-03-31T20:47:09Z', 3, 'DHL');

And before we dive in, don’t forget to tell ksqlDB that you want to read from the beginning of the streams:

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

Let’s join these streams together to produce a new one. Our new stream will be enriched from the originals to contain more information about the orders that have shipped. But one question you might be asking yourself is, "Why would I use a stream/stream join to do this?" That’s a great question.

Stream/stream joins are useful when your events are all "facts" that never supersede each other. Every order in the stream is distinct. Every shipment is distinct, too. Stream/stream joins help us reason about how two sources of events come together during some window of time. Contrast this with reference data that can update over time. Reference data is better kept in a table to represent its mutability. If, for example, you wanted to enrich the orders stream with the customers who purchased the orders, it would be better to model that as a stream/table join.

Execute the following query and study its output. This will block and continue to return results until its limit is reached or you tell it to stop.

SELECT o.id AS order_id,
       TIMESTAMPTOSTRING(o.rowtime, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS order_ts,
       o.total_amount,
       o.customer_name,
       s.id as shipment_id,
       TIMESTAMPTOSTRING(s.rowtime, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS shipment_ts,
       s.warehouse,
       (s.rowtime - o.rowtime) / 1000 / 60 AS ship_time
FROM orders o INNER JOIN shipments s
WITHIN 7 DAYS
ON o.id = s.order_id
EMIT CHANGES
LIMIT 3;

This should yield the following output:

+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|ORDER_ID            |ORDER_TS            |TOTAL_AMOUNT        |CUSTOMER_NAME       |SHIPMENT_ID         |SHIPMENT_TS         |WAREHOUSE           |SHIP_TIME           |
+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|1                   |2019-03-29 06:01:18 |133548.84           |Ricardo Ferreira    |ship-ch83360        |2019-03-31 18:13:39 |UPS                 |3612                |
|2                   |2019-03-29 17:02:20 |164839.31           |Tim Berglund        |ship-xf72808        |2019-03-31 02:04:13 |UPS                 |1981                |
|3                   |2019-03-29 13:44:10 |90427.66            |Robin Moffatt       |ship-kr47454        |2019-03-31 20:47:09 |DHL                 |3302                |
Limit Reached
Query terminated

There’s a lot to talk about here.

The query we issued performs an inner join between the orders and shipments. This kind of join only emits events when there’s a match on the criteria of both sides of the join. In effect, this only joins orders that have successfully shipped.

Another thing you’ll notice is that we specified a window duration of seven days to denote the amount of time we’ll allow joins to occur within. In theory, we could wait for any amount of time to join the elements of each stream together. The problem is that they may not occur within close proximity of one another, and we have a finite amount of buffer space to wait for joins to happen within. Join time windows allow us to control for the amount of buffer space that we’ll allow. They can also be useful for modeling an SLA. In this example, we might want to ignore orders whose shipments don’t occur within 7 days of purchasing. And because we defined the timestamp as a field of the record, ksqlDB understands that it should use the field time to determine if the event falls within the window instead of whatever time it happens to be right now.

Lastly, let’s talk about the output itself. We use fields from both the orders and shipments streams to create a new set of columns in the result stream. The new stream contains all orders that have shipped, along with which warehouse they shipped from and the duration of time between order placement and shipping in minutes.

Since the output looks right, the next step is to make the query continuous. Issue the following to create a new stream from the query above. This new stream will have its content updated continuously as new orders and shipments events arrive.

CREATE STREAM shipped_orders AS
    SELECT o.id AS order_id,
           TIMESTAMPTOSTRING(o.rowtime, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS order_ts,
           o.total_amount,
           o.customer_name,
           s.id AS SHIPMENT_ID,
           TIMESTAMPTOSTRING(s.rowtime, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS shipment_ts,
           s.warehouse,
           (s.rowtime - o.rowtime) / 1000 / 60 AS ship_time
    FROM orders o INNER JOIN shipments s
    WITHIN 7 DAYS
    ON o.id = s.order_id;

To check that it’s working, print out the contents of the output stream using the following query:

PRINT SHIPPED_ORDERS FROM BEGINNING LIMIT 3;

This should yield the following output:

Key format: KAFKA_INT or KAFKA_STRING
Value format: AVRO
rowtime: 2019/03/31 20:47:09.000 Z, key: 3, value: {"ORDER_TS": "2019-03-29 13:44:10", "TOTAL_AMOUNT": 90427.66, "CUSTOMER_NAME": "Robin Moffatt", "SHIPMENT_ID": "ship-kr47454", "SHIPMENT_TS": "2019-03-31 20:47:09", "WAREHOUSE": "DHL", "SHIP_TIME": 3302}, partition: 3
rowtime: 2019/03/31 02:04:13.000 Z, key: 2, value: {"ORDER_TS": "2019-03-29 17:02:20", "TOTAL_AMOUNT": 164839.31, "CUSTOMER_NAME": "Tim Berglund", "SHIPMENT_ID": "ship-xf72808", "SHIPMENT_TS": "2019-03-31 02:04:13", "WAREHOUSE": "UPS", "SHIP_TIME": 1981}, partition: 3
rowtime: 2019/03/31 18:13:39.000 Z, key: 1, value: {"ORDER_TS": "2019-03-29 06:01:18", "TOTAL_AMOUNT": 133548.84, "CUSTOMER_NAME": "Ricardo Ferreira", "SHIPMENT_ID": "ship-ch83360", "SHIPMENT_TS": "2019-03-31 18:13:39", "WAREHOUSE": "UPS", "SHIP_TIME": 3612}, partition: 0
Topic printing ceased

As you can see, the output sits in a plain Kafka topic and therefore, any application that is able to consume data from it will be able to have access to this data.

Type 'exit' and hit enter to exit the ksqlDB CLI.

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 orders (ID INT KEY, order_ts VARCHAR, total_amount DOUBLE, customer_name VARCHAR)
    WITH (KAFKA_TOPIC='_orders',
          VALUE_FORMAT='AVRO',
          TIMESTAMP='order_ts',
          TIMESTAMP_FORMAT='yyyy-MM-dd''T''HH:mm:ssX',
          PARTITIONS=4);

CREATE STREAM shipments (ID VARCHAR KEY, ship_ts VARCHAR, order_id INT, warehouse VARCHAR)
    WITH (KAFKA_TOPIC='_shipments',
          VALUE_FORMAT='AVRO',
          TIMESTAMP='ship_ts',
          TIMESTAMP_FORMAT='yyyy-MM-dd''T''HH:mm:ssX',
          PARTITIONS=4);

CREATE STREAM SHIPPED_ORDERS AS
    SELECT O.ID AS ORDER_ID,
           TIMESTAMPTOSTRING(O.ROWTIME, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS ORDER_TS,
           O.TOTAL_AMOUNT,
           O.CUSTOMER_NAME,
           S.ID AS SHIPMENT_ID,
           TIMESTAMPTOSTRING(S.ROWTIME, 'yyyy-MM-dd HH:mm:ss', 'UTC') AS SHIPMENT_TS,
           S.WAREHOUSE,
           (S.ROWTIME - O.ROWTIME) / 1000 / 60 AS SHIP_TIME
    FROM ORDERS O INNER JOIN SHIPMENTS S
    WITHIN 7 DAYS
    ON O.ID = S.ORDER_ID;

Test it

Create the test data

1

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

{
  "inputs": [
    {
      "topic": "_shipments",
      "key": "ship-ch83360",
      "value": {
        "ship_ts": "2019-03-31T18:13:39Z",
        "order_id": 1,
        "warehouse": "UPS"
      }
    },
    {
      "topic": "_shipments",
      "key": "ship-xf72808",
      "value": {
        "ship_ts": "2019-03-31T02:04:13Z",
        "order_id": 2,
        "warehouse": "UPS"
      }
    },
    {
      "topic": "_shipments",
      "key": "ship-kr47454",
      "value": {
        "ship_ts": "2019-03-31T20:47:09Z",
        "order_id": 3,
        "warehouse": "DHL"
      }
    },
    {
      "topic": "_orders",
      "key": 1,
      "value": {
        "order_ts": "2019-03-29T06:01:18Z",
        "total_amount": 133548.84,
        "customer_name": "Ricardo Ferreira"
      }
    },
    {
      "topic": "_orders",
      "key": 2,
      "value": {
        "order_ts": "2019-03-29T17:02:20Z",
        "total_amount": 164839.31,
        "customer_name": "Tim Berglund"
      }
    },
    {
      "topic": "_orders",
      "key": 3,
      "value": {
        "order_ts": "2019-03-29T13:44:10Z",
        "total_amount": 90427.66,
        "customer_name": "Robin Moffatt"
      }
    },
    {
      "topic": "_orders",
      "key": 4,
      "value": {
        "order_ts": "2019-03-29T11:58:25Z",
        "total_amount": 33462.11,
        "customer_name": "Viktor Gamov"
      }
    }
  ]
}

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

{
  "outputs": [
    {
      "topic": "SHIPPED_ORDERS",
      "timestamp": 1554056019000,
      "key": 1,
      "value": {
        "ORDER_TS": "2019-03-29 06:01:18",
        "TOTAL_AMOUNT": 133548.84,
        "CUSTOMER_NAME": "Ricardo Ferreira",
        "SHIPMENT_ID": "ship-ch83360",
        "SHIPMENT_TS": "2019-03-31 18:13:39",
        "WAREHOUSE": "UPS",
        "SHIP_TIME": 3612
      }
    },
    {
      "topic": "SHIPPED_ORDERS",
      "timestamp": 1553997853000,
      "key": 2,
      "value": {
        "ORDER_TS": "2019-03-29 17:02:20",
        "TOTAL_AMOUNT": 164839.31,
        "CUSTOMER_NAME": "Tim Berglund",
        "SHIPMENT_ID": "ship-xf72808",
        "SHIPMENT_TS": "2019-03-31 02:04:13",
        "WAREHOUSE": "UPS",
        "SHIP_TIME": 1981
      }
    },
    {
      "topic": "SHIPPED_ORDERS",
      "timestamp": 1554065229000,
      "key": 3,
      "value": {
        "ORDER_TS": "2019-03-29 13:44:10",
        "TOTAL_AMOUNT": 90427.66,
        "CUSTOMER_NAME": "Robin Moffatt",
        "SHIPMENT_ID": "ship-kr47454",
        "SHIPMENT_TS": "2019-03-31 20:47:09",
        "WAREHOUSE": "DHL",
        "SHIP_TIME": 3302
      }
    }
  ]
}

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.