How to join a stream and a stream together

Problem:

you have two Kafka topics whose events share a common identifying attribute and correlate during some period of time. You want to join the topics together and create a new one based on that 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 which warehouse they shipped from.

Code example:

Try it

1
Initialize the project

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

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_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

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

CREATE STREAM orders (order_id INT, 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 (shipment_id VARCHAR, 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 KSQL operations, KSQL 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 (order_id, order_ts, total_amount, customer_name) VALUES (1, '2019-03-29T06:01:18Z', 133548.84, 'Ricardo Ferreira');
INSERT INTO orders (order_id, order_ts, total_amount, customer_name) VALUES (2, '2019-03-29T17:02:20Z', 164839.31, 'Tim Berglund');
INSERT INTO orders (order_id, order_ts, total_amount, customer_name) VALUES (3, '2019-03-29T13:44:10Z', 90427.66, 'Robin Moffatt');
INSERT INTO orders (order_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 (shipment_id, ship_ts, order_id, warehouse) VALUES ('ship-ch83360', '2019-03-31T18:13:39Z', 1, 'UPS');
INSERT INTO shipments (shipment_id, ship_ts, order_id, warehouse) VALUES ('ship-xf72808', '2019-03-31T02:04:13Z', 2, 'UPS');
INSERT INTO shipments (shipment_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 KSQL 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 it’s limit is reached or you tell it to stop.

SELECT o.order_id AS order_id,
       TIMESTAMPTOSTRING(o.rowtime, 'yyyy-MM-dd HH:mm:ss') AS order_ts,
       o.total_amount,
       o.customer_name,
       s.shipment_id,
       TIMESTAMPTOSTRING(s.rowtime, 'yyyy-MM-dd HH:mm:ss') 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.order_id = s.order_id
LIMIT 3;

This should yield the following output:

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, KSQL 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.order_id AS order_id,
           TIMESTAMPTOSTRING(o.rowtime, 'yyyy-MM-dd HH:mm:ss') AS order_ts,
           o.total_amount,
           o.customer_name,
           s.shipment_id,
           TIMESTAMPTOSTRING(s.rowtime, 'yyyy-MM-dd HH:mm:ss') 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.order_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:

Format:AVRO
3/31/19 6:13:39 PM UTC, 1, {"ORDER_ID": 1, "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}
3/31/19 2:04:13 AM UTC, 2, {"ORDER_ID": 2, "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}
3/31/19 8:47:09 PM UTC, 3, {"ORDER_ID": 3, "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}

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.

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 orders (order_id INT, 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 (shipment_id VARCHAR, 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.ORDER_ID AS ORDER_ID,
           TIMESTAMPTOSTRING(O.ROWTIME, 'yyyy-MM-dd HH:mm:ss') AS ORDER_TS,
           O.TOTAL_AMOUNT,
           O.CUSTOMER_NAME,
           S.SHIPMENT_ID,
           TIMESTAMPTOSTRING(S.ROWTIME, 'yyyy-MM-dd HH:mm:ss') 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.ORDER_ID = S.ORDER_ID;

Test it

1
Create the test data

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

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

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