How to join a stream and a lookup table

Question:

If I have events in a Kafka topic and a table of reference data (aka a lookup table), how can I join each event in the stream to a piece of data in the table based on a common key?

Edit this page

Example use case:

Suppose you have a set of movies that have been released and a stream of ratings from movie-goers about how entertaining they are. In this tutorial, we'll write a program that joins each rating with content about the movie.

Code example:





Short Answer

Use the builder.table() method to create a KTable. Then use the ValueJoiner interface in the Streams API to join the KStream and KTable.

KStream<String, Rating> ratings = ...
KTable<String, Movie> movies = ...
final MovieRatingJoiner joiner = new MovieRatingJoiner();
KStream<String, RatedMovie> ratedMovie = ratings.join(movies, joiner);

Try it

1
Initialize the project

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

mkdir join-stream && cd join-stream

2
Get Confluent Platform

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

---
version: '2'

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

  broker:
    image: confluentinc/cp-kafka:6.1.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_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0

  schema-registry:
    image: confluentinc/cp-schema-registry:6.1.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'
      SCHEMA_REGISTRY_LOG4J_ROOT_LOGLEVEL: WARN

And launch it by running:

docker-compose up -d

3
Configure the project

Create the following Gradle build file, named build.gradle for the project:

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.commercehub.gradle.plugin:gradle-avro-plugin:0.22.0'
    classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.2'
  }
}

plugins {
  id 'java'
  id 'com.google.cloud.tools.jib' version '3.1.1'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '0.0.1'

repositories {
  mavenCentral()


  maven {
    url 'https://packages.confluent.io/maven'
  }
}

apply plugin: 'com.commercehub.gradle.plugin.avro'
apply plugin: 'com.github.johnrengelman.shadow'

dependencies {
  implementation 'org.apache.avro:avro:1.10.2'
  implementation 'org.slf4j:slf4j-simple:1.7.30'
  implementation 'org.apache.kafka:kafka-streams:2.7.0'
  implementation 'io.confluent:kafka-streams-avro-serde:6.1.1'
  testImplementation 'org.apache.kafka:kafka-streams-test-utils:2.7.0'
  testImplementation 'junit:junit:4.13.2'
}

test {
  testLogging {
    outputs.upToDateWhen { false }
    showStandardStreams = true
    exceptionFormat = 'full'
  }
}

task run(type: JavaExec) {
  main = 'io.confluent.developer.JoinStreamToTable'
  classpath = sourceSets.main.runtimeClasspath
  args = ['configuration/dev.properties']
}

jar {
  manifest {
    attributes(
        'Class-Path': configurations.compileClasspath.collect { it.getName() }.join(' '),
        'Main-Class': 'io.confluent.developer.JoinStreamToTable'
    )
  }
}

shadowJar {
  archiveBaseName = "kstreams-stream-table-join-standalone"
  archiveClassifier = ''
}

And be sure to run the following command to obtain the Gradle wrapper:

gradle wrapper

Next, create a directory for configuration data:

mkdir configuration

Then create a development file at configuration/dev.properties:

application.id=joining-app
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081

movie.topic.name=movies
movie.topic.partitions=1
movie.topic.replication.factor=1

rekeyed.movie.topic.name=rekeyed-movies
rekeyed.movie.topic.partitions=1
rekeyed.movie.topic.replication.factor=1

rating.topic.name=ratings
rating.topic.partitions=1
rating.topic.replication.factor=1

rated.movies.topic.name=rated-movies
rated.movies.topic.partitions=1
rated.movies.topic.replication.factor=1

4
Create a schema for the events

This tutorial uses three streams: one called movies that holds movie reference data, one called ratings that holds a stream of inbound movie ratings, and one called rated-movies that holds the result of the join between ratings and movies. Let’s create schemas for all three.

Create a directory for the schemas that represent the events in the stream:

mkdir -p src/main/avro

Then create the following Avro schema file at src/main/avro/movie.avsc for the movies lookup table:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Movie",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "title", "type": "string"},
    {"name": "release_year", "type": "int"}
  ]
}

Next, create another Avro schema file at src/main/avro/rating.avsc for the stream of ratings:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Rating",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "rating", "type": "double"}
  ]
}

And finally, create another Avro schema file at src/main/avro/rated-movie.avsc for the result of the join:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "RatedMovie",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "title", "type": "string"},
    {"name": "release_year", "type": "int"},
    {"name": "rating", "type": "double"}
  ]
}

Because we will use this Avro schema in our Java code, we’ll need to compile it. The Gradle Avro plugin is a part of the build, so it will see your new Avro files, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:

./gradlew build

5
Create the Kafka Streams topology

Create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer

Then create the following file at src/main/java/io/confluent/developer/JoinStreamToTable.java. Let’s take a close look at the buildTopology() method, which uses the Kafka Streams DSL.

The first thing the method does is create an instance of StreamsBuilder, which is the helper object that lets us build our topology. With our builder in hand, there are three things we need to do. First, we call the stream() method to create a KStream<String, Movie> object. The problem is that we can’t make any assumptions about the key of this stream, so we have to repartition it explicitly. We use the map() method for that, creating a new KeyValue instance for each record, using the movie ID as the new key.

The movies start their life in a stream, but fundamentally, movies are entities that belong in a table. To turn them into a table, we first emit the rekeyed stream to a Kafka topic using the to() method. We can then use the builder.table() method to create a KTable<String,Movie>. We have successfully turned a topic full of movie entities into a scalable, key-addressable table of Movie objects. With that, we’re ready to move on to ratings.

Creating the KStream<String,Rating> of ratings looks just like our first step with the movies: we create a stream from the topic, then repartition it with the map() method. Note that we must choose the same key—movie ID—for our join to work.

With the ratings stream and the movie table in hand, all that remains is to join them using the join() method. It’s a wonderfully simply one-liner, but we have concealed a bit of complexity in the form of the MovieRatingJoiner class. More on that in a moment.

package io.confluent.developer;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.time.Duration;

import io.confluent.developer.avro.Movie;
import io.confluent.developer.avro.RatedMovie;
import io.confluent.developer.avro.Rating;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;

public class JoinStreamToTable {

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String movieTopic = allProps.getProperty("movie.topic.name");
        final String rekeyedMovieTopic = allProps.getProperty("rekeyed.movie.topic.name");
        final String ratingTopic = allProps.getProperty("rating.topic.name");
        final String ratedMoviesTopic = allProps.getProperty("rated.movies.topic.name");
        final MovieRatingJoiner joiner = new MovieRatingJoiner();

        KStream<String, Movie> movieStream = builder.<String, Movie>stream(movieTopic)
                .map((key, movie) -> new KeyValue<>(String.valueOf(movie.getId()), movie));

        movieStream.to(rekeyedMovieTopic);

        KTable<String, Movie> movies = builder.table(rekeyedMovieTopic);

        KStream<String, Rating> ratings = builder.<String, Rating>stream(ratingTopic)
                .map((key, rating) -> new KeyValue<>(String.valueOf(rating.getId()), rating));

        KStream<String, RatedMovie> ratedMovie = ratings.join(movies, joiner);

        ratedMovie.to(ratedMoviesTopic, Produced.with(Serdes.String(), ratedMovieAvroSerde(allProps)));

        return builder.build();
    }

    private SpecificAvroSerde<RatedMovie> ratedMovieAvroSerde(Properties allProps) {
        SpecificAvroSerde<RatedMovie> movieAvroSerde = new SpecificAvroSerde<>();
        movieAvroSerde.configure((Map)allProps, false);
        return movieAvroSerde;
    }

    public void createTopics(Properties allProps) {
        AdminClient client = AdminClient.create(allProps);
        List<NewTopic> topics = new ArrayList<>();
        topics.add(new NewTopic(
                allProps.getProperty("movie.topic.name"),
                Integer.parseInt(allProps.getProperty("movie.topic.partitions")),
                Short.parseShort(allProps.getProperty("movie.topic.replication.factor"))));

        topics.add(new NewTopic(
                allProps.getProperty("rekeyed.movie.topic.name"),
                Integer.parseInt(allProps.getProperty("rekeyed.movie.topic.partitions")),
                Short.parseShort(allProps.getProperty("rekeyed.movie.topic.replication.factor"))));

        topics.add(new NewTopic(
                allProps.getProperty("rating.topic.name"),
                Integer.parseInt(allProps.getProperty("rating.topic.partitions")),
                Short.parseShort(allProps.getProperty("rating.topic.replication.factor"))));

        topics.add(new NewTopic(
                allProps.getProperty("rated.movies.topic.name"),
                Integer.parseInt(allProps.getProperty("rated.movies.topic.partitions")),
                Short.parseShort(allProps.getProperty("rated.movies.topic.replication.factor"))));

        client.createTopics(topics);
        client.close();
    }

    public Properties loadEnvProperties(String fileName) throws IOException {
        Properties allProps = new Properties();
        FileInputStream input = new FileInputStream(fileName);
        allProps.load(input);
        input.close();

        return allProps;
    }

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            throw new IllegalArgumentException("This program takes one argument: the path to an environment configuration file.");
        }

        JoinStreamToTable ts = new JoinStreamToTable();
        Properties allProps = ts.loadEnvProperties(args[0]);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
        Topology topology = ts.buildTopology(allProps);

        ts.createTopics(allProps);

        final KafkaStreams streams = new KafkaStreams(topology, allProps);
        final CountDownLatch latch = new CountDownLatch(1);

        // Attach shutdown handler to catch Control-C.
        Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
            @Override
            public void run() {
                streams.close(Duration.ofSeconds(5));
                latch.countDown();
            }
        });

        try {
            streams.start();
            latch.await();
        } catch (Throwable e) {
            System.exit(1);
        }
        System.exit(0);
    }
}

6
Implement a ValueJoiner class

For the ValueJoiner class, create the following file at src/main/java/io/confluent/developer/MovieRatingJoiner.java.

When you join two tables in a relational database, by default you get a new table containing all of the columns of the left table plus all of the columns of the right table. When you join a stream and a table, you get a new stream, but you must be explicit about the value of that stream—the combination between the value in the stream and the associated value in the table. The ValueJoiner interface in the Streams API does this work. The single apply() method takes the stream and table values as parameters, and returns the value of the joined stream as output. (Their keys are not a part of the equation, because they are equal by definition and do not change in the result.) As you can see here, this is just a matter of creating a RatedMovie object and populating it with the relevant fields of the input movie and rating.

You can do this in a Java Lambda in the call to the join() method where you’re building the stream topology, but the joining logic may become complex, and breaking it off into its own trivially testable class is a good move.

package io.confluent.developer;

import org.apache.kafka.streams.kstream.ValueJoiner;

import io.confluent.developer.avro.Movie;
import io.confluent.developer.avro.RatedMovie;
import io.confluent.developer.avro.Rating;

public class MovieRatingJoiner implements ValueJoiner<Rating, Movie, RatedMovie> {

  public RatedMovie apply(Rating rating, Movie movie) {
    return RatedMovie.newBuilder()
        .setId(movie.getId())
        .setTitle(movie.getTitle())
        .setReleaseYear(movie.getReleaseYear())
        .setRating(rating.getRating())
        .build();
  }
}

7
Compile and run the Kafka Streams program

In your terminal, run:

./gradlew shadowJar

Now that you have an uberjar for the Kafka Streams application, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it. There is always another message to process, so streaming applications don’t exit until you force them.

java -jar build/libs/kstreams-stream-table-join-standalone-0.0.1.jar configuration/dev.properties

8
Load in some movie reference data

In a new terminal, run:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic movies --bootstrap-server broker:9092 --property value.schema="$(< src/main/avro/movie.avsc)"

When the console producer starts, it will log some messages and hang, waiting for your input. Copy and paste one line at a time and press enter to send it. Note that these lines contain hard tabs between the key and the value, so retyping them without the tab will not work.

Each line represents a movie we will be able to rate. To send all of the events below, paste the following into the prompt and press enter:

{"id": 294, "title": "Die Hard", "release_year": 1988}
{"id": 354, "title": "Tree of Life", "release_year": 2011}
{"id": 782, "title": "A Walk in the Clouds", "release_year": 1995}
{"id": 128, "title": "The Big Lebowski", "release_year": 1998}
{"id": 780, "title": "Super Mario Bros.", "release_year": 1993}

In this case the table data originates from a Kafka topic that was populated by a console producer but this doesn’t always have to be the case. You can use Kafka Connect to stream data from a source system (such as a database) into a Kafka topic, which could then be the foundation for a lookup table. For further reading checkout this tutorial on creating a Kafka Streams table from SQLite data using Kafka Connect.

9
Get ready to observe the rated movies in the output topic

Before you start producing ratings, it’s a good idea to set up the consumer on the output topic. This way, as soon as you produce ratings (and they’re joined to movies), you’ll see the results right away. Run this to get ready to consume the rated movies:

docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic rated-movies --bootstrap-server broker:9092 --from-beginning

You won’t see any results until the next step.

10
Produce some ratings to the input topic

Run the following in a new terminal window. This process is the most fun if you can see this and the previous terminal (which is consuming the rated movies) at the same time. If your terminal program lets you do horizontal split panes, try it that way:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic ratings --bootstrap-server broker:9092 --property value.schema="$(< src/main/avro/rating.avsc)"

When the producer starts up, copy and paste these lines into the terminal. Try doing them one at a time, observing the results in the consumer terminal:

{"id": 294, "rating": 8.2}
{"id": 294, "rating": 8.5}
{"id": 354, "rating": 9.9}
{"id": 354, "rating": 9.7}
{"id": 782, "rating": 7.8}
{"id": 782, "rating": 7.7}
{"id": 128, "rating": 8.7}
{"id": 128, "rating": 8.4}
{"id": 780, "rating": 2.1}

Speaking of that consumer terminal, these are the results you should see there if you paste in all the movies and ratings as shown in this tutorial:

{"id":294,"title":"Die Hard","release_year":1988,"rating":8.2}
{"id":294,"title":"Die Hard","release_year":1988,"rating":8.5}
{"id":354,"title":"Tree of Life","release_year":2011,"rating":9.9}
{"id":354,"title":"Tree of Life","release_year":2011,"rating":9.7}
{"id":782,"title":"A Walk in the Clouds","release_year":1995,"rating":7.8}
{"id":782,"title":"A Walk in the Clouds","release_year":1995,"rating":7.7}
{"id":128,"title":"The Big Lebowski","release_year":1998,"rating":8.7}
{"id":128,"title":"The Big Lebowski","release_year":1998,"rating":8.4}
{"id":780,"title":"Super Mario Bros.","release_year":1993,"rating":2.1}

You have now joined a stream to a table! Well done.

Test it

1
Create a test configuration file

First, create a test file at configuration/test.properties:

application.id=joining-app
bootstrap.servers=localhost:29092
schema.registry.url=mock://joining-stream-table:8081

movie.topic.name=movies
movie.topic.partitions=1
movie.topic.replication.factor=1

rekeyed.movie.topic.name=rekeyed-movies
rekeyed.movie.topic.partitions=1
rekeyed.movie.topic.replication.factor=1

rating.topic.name=ratings
rating.topic.partitions=1
rating.topic.replication.factor=1

rated.movies.topic.name=rated-movies
rated.movies.topic.partitions=1
rated.movies.topic.replication.factor=1

2
Test the MovieRatingJoiner class

Create a directory for the tests to live in:

mkdir -p src/test/java/io/confluent/developer

Create the following file at src/test/java/io/confluent/developer/MovieRatingJoinerTest.java. This tests the helper class that merges the value of the movie and the rating as each rating is joined to a movie. The class has a dependency on the ValueJoiner interface, but otherwise does not depend on anything external to our domain; it just needs Movie, Rating, and RatedMovie` domain objects. As such, it’s about as testable as code gets:

package io.confluent.developer;

import org.junit.Test;

import io.confluent.developer.avro.Movie;
import io.confluent.developer.avro.RatedMovie;
import io.confluent.developer.avro.Rating;

import static org.junit.Assert.assertEquals;

public class MovieRatingJoinerTest {

  @Test
  public void apply() {
    RatedMovie actualRatedMovie;

    Movie treeOfLife = Movie.newBuilder().setTitle("Tree of Life").setId(354).setReleaseYear(2011).build();
    Rating rating = Rating.newBuilder().setId(354).setRating(9.8).build();
    RatedMovie expectedRatedMovie = RatedMovie.newBuilder()
        .setTitle("Tree of Life")
        .setId(354)
        .setReleaseYear(2011)
        .setRating(9.8)
        .build();

    MovieRatingJoiner joiner = new MovieRatingJoiner();
    actualRatedMovie = joiner.apply(rating, treeOfLife);

    assertEquals(actualRatedMovie, expectedRatedMovie);
  }
}

3
Test the streams topology

Now create the following file at src/test/java/io/confluent/developer/JoinStreamToTableTest.java. Testing a Kafka streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver class makes this much more pleasant that it would otherwise be.

There is only one method in JoinStreamToTableTest annotated with @Test, and that is testJoin(). This method actually runs our Streams topology using the TopologyTestDriver and some mocked data that is set up inside the test method.

package io.confluent.developer;

import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.test.TestRecord;
import org.apache.kafka.streams.StreamsConfig;
import org.junit.After;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import io.confluent.developer.avro.Movie;
import io.confluent.developer.avro.RatedMovie;
import io.confluent.developer.avro.Rating;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroDeserializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

import static org.junit.Assert.assertEquals;

public class JoinStreamToTableTest {

    private final static String TEST_CONFIG_FILE = "configuration/test.properties";
    private TopologyTestDriver testDriver;

    private SpecificAvroSerializer<Movie> makeMovieSerializer(Properties allProps) {
        SpecificAvroSerializer<Movie> serializer = new SpecificAvroSerializer<>();

        Map<String, String> config = new HashMap<>();
        config.put("schema.registry.url", allProps.getProperty("schema.registry.url"));
        serializer.configure(config, false);

        return serializer;
    }

    private SpecificAvroSerializer<Rating> makeRatingSerializer(Properties allProps) {
        SpecificAvroSerializer<Rating> serializer = new SpecificAvroSerializer<>();

        Map<String, String> config = new HashMap<>();
        config.put("schema.registry.url", allProps.getProperty("schema.registry.url"));
        serializer.configure(config, false);

        return serializer;
    }

    private SpecificAvroDeserializer<RatedMovie> makeRatedMovieDeserializer(Properties allProps) {
        SpecificAvroDeserializer<RatedMovie> deserializer = new SpecificAvroDeserializer<>();

        Map<String, String> config = new HashMap<>();
        config.put("schema.registry.url", allProps.getProperty("schema.registry.url"));
        deserializer.configure(config, false);

        return deserializer;
    }

    private List<RatedMovie> readOutputTopic(TopologyTestDriver testDriver,
                                             String topic,
                                             Deserializer<String> keyDeserializer,
                                             SpecificAvroDeserializer<RatedMovie> makeRatedMovieDeserializer) {
        List<RatedMovie> results = new ArrayList<>();
        final TestOutputTopic<String, RatedMovie>
            testOutputTopic =
            testDriver.createOutputTopic(topic, keyDeserializer, makeRatedMovieDeserializer);
        testOutputTopic
            .readKeyValuesToList()
            .forEach(record -> {
                         if (record != null) {
                             results.add(record.value);
                         }
                     }
            );
        return results;
    }

    @Test
    public void testJoin() throws IOException {
        JoinStreamToTable jst = new JoinStreamToTable();
        Properties allProps = jst.loadEnvProperties(TEST_CONFIG_FILE);

        String tableTopic = allProps.getProperty("movie.topic.name");
        String streamTopic = allProps.getProperty("rating.topic.name");
        String outputTopic = allProps.getProperty("rated.movies.topic.name");
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);

        Topology topology = jst.buildTopology(allProps);
        testDriver = new TopologyTestDriver(topology, allProps);

        Serializer<String> keySerializer = Serdes.String().serializer();
        SpecificAvroSerializer<Movie> movieSerializer = makeMovieSerializer(allProps);
        SpecificAvroSerializer<Rating> ratingSerializer = makeRatingSerializer(allProps);

        Deserializer<String> stringDeserializer = Serdes.String().deserializer();
        SpecificAvroDeserializer<RatedMovie> valueDeserializer = makeRatedMovieDeserializer(allProps);

        List<Movie> movies = new ArrayList<>();
        movies.add(Movie.newBuilder().setId(294).setTitle("Die Hard").setReleaseYear(1988).build());
        movies.add(Movie.newBuilder().setId(354).setTitle("Tree of Life").setReleaseYear(2011).build());
        movies.add(Movie.newBuilder().setId(782).setTitle("A Walk in the Clouds").setReleaseYear(1998).build());
        movies.add(Movie.newBuilder().setId(128).setTitle("The Big Lebowski").setReleaseYear(1998).build());
        movies.add(Movie.newBuilder().setId(780).setTitle("Super Mario Bros.").setReleaseYear(1993).build());

        List<Rating> ratings = new ArrayList<>();
        ratings.add(Rating.newBuilder().setId(294).setRating(8.2).build());
        ratings.add(Rating.newBuilder().setId(294).setRating(8.5).build());
        ratings.add(Rating.newBuilder().setId(354).setRating(9.9).build());
        ratings.add(Rating.newBuilder().setId(354).setRating(9.7).build());
        ratings.add(Rating.newBuilder().setId(782).setRating(7.8).build());
        ratings.add(Rating.newBuilder().setId(782).setRating(7.7).build());
        ratings.add(Rating.newBuilder().setId(128).setRating(8.7).build());
        ratings.add(Rating.newBuilder().setId(128).setRating(8.4).build());
        ratings.add(Rating.newBuilder().setId(780).setRating(2.1).build());

        List<RatedMovie> ratedMovies = new ArrayList<>();
        ratedMovies.add(RatedMovie.newBuilder().setTitle("Die Hard").setId(294).setReleaseYear(1988).setRating(8.2).build());
        ratedMovies.add(RatedMovie.newBuilder().setTitle("Die Hard").setId(294).setReleaseYear(1988).setRating(8.5).build());
        ratedMovies.add(RatedMovie.newBuilder().setTitle("Tree of Life").setId(354).setReleaseYear(2011).setRating(9.9).build());
        ratedMovies.add(RatedMovie.newBuilder().setTitle("Tree of Life").setId(354).setReleaseYear(2011).setRating(9.7).build());
        ratedMovies.add(RatedMovie.newBuilder().setId(782).setTitle("A Walk in the Clouds").setReleaseYear(1998).setRating(7.8).build());
        ratedMovies.add(RatedMovie.newBuilder().setId(782).setTitle("A Walk in the Clouds").setReleaseYear(1998).setRating(7.7).build());
        ratedMovies.add(RatedMovie.newBuilder().setId(128).setTitle("The Big Lebowski").setReleaseYear(1998).setRating(8.7).build());
        ratedMovies.add(RatedMovie.newBuilder().setId(128).setTitle("The Big Lebowski").setReleaseYear(1998).setRating(8.4).build());
        ratedMovies.add(RatedMovie.newBuilder().setId(780).setTitle("Super Mario Bros.").setReleaseYear(1993).setRating(2.1).build());

        final TestInputTopic<String, Movie>
            movieTestInputTopic = testDriver.createInputTopic(tableTopic, keySerializer, movieSerializer);

        for (Movie movie : movies) {
            movieTestInputTopic.pipeInput(String.valueOf(movie.getId()), movie);
        }

        final TestInputTopic<String, Rating>
            ratingTestInputTopic =
            testDriver.createInputTopic(streamTopic, keySerializer, ratingSerializer);
        for (Rating rating : ratings) {
            ratingTestInputTopic.pipeInput(String.valueOf(rating.getId()), rating);
        }

        List<RatedMovie> actualOutput = readOutputTopic(testDriver, outputTopic, stringDeserializer, valueDeserializer);

        assertEquals(ratedMovies, actualOutput);
    }

    @After
    public void cleanup() {
        testDriver.close();
    }

}

4
Invoke the tests

Now run the test, which is as simple as:

./gradlew test

Take it to production

1
Create a production configuration file

First, create a new configuration file at configuration/prod.properties with the following content. Be sure to fill in the addresses of your production hosts and change any other parameters that make sense for your setup.

application.id=joining-app
bootstrap.servers=<< FILL ME IN >>
schema.registry.url=<< FILL ME IN >>

table.topic.name=movies
table.topic.partitions=<< FILL ME IN >>
table.topic.replication.factor=<< FILL ME IN >>

stream.topic.name=ratings
stream.topic.partitions=<< FILL ME IN >>
stream.topic.replication.factor=<< FILL ME IN >>

output.topic.name=rated-movies
output.topic.partitions=<< FILL ME IN >>
output.topic.replication.factor=<< FILL ME IN >>

2
Build a Docker image

In your terminal, execute the following to invoke the Jib plugin to build an image:

gradle jibDockerBuild --image=io.confluent.developer/kstreams-stream-table-join:0.0.1

3
Launch the container

Finally, launch the container using your preferred container orchestration service. If you want to run it locally, you can execute the following:

docker run -v $PWD/configuration/prod.properties:/config.properties io.confluent.developer/kstreams-stream-table-join:0.0.1 config.properties

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.

  1. Sign up for Confluent Cloud, a fully-managed Apache Kafka service.

  2. After you log in to Confluent Cloud Console, 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 to 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. In the case of this tutorial, add the following properties to the client application’s input properties file, substituting all curly braces with your Confluent Cloud values.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BROKER_ENDPOINT }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips

# Best practice for Kafka producer to prevent data loss
acks=all

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url=https://{{ SR_ENDPOINT }}
basic.auth.credentials.source=USER_INFO
schema.registry.basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}

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