How to join a table and a table with a foreign key


How can you join two tables with different primary keys?

Edit this page

Example use case:

Suppose you are running an internet streaming music service where you offer albums or individual music tracks for sale. You'd like to track trends in listener preferences by joining the track purchases against the table of albums. The track purchase key doesn't align with the primary key for the album table, but since the value of the track purchase contains the ID of the album, you can extract the album ID from the track purchase and complete a foreign key join against the album table.

Hands-on code example:

Run it



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


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

mkdir fk-joins && cd fk-joins

Get Confluent Platform


Next, create the following docker-compose.yml file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud):

version: '2'
    image: confluentinc/cp-kafka:7.4.1
    hostname: broker
    container_name: broker
    - 29092:29092
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_NODE_ID: 1
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
    image: confluentinc/cp-schema-registry:7.3.0
    hostname: schema-registry
    container_name: schema-registry
    - broker
    - 8081:8081
      SCHEMA_REGISTRY_HOST_NAME: schema-registry

And launch it by running:

docker compose up -d

Configure the project


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

buildscript {
  repositories {
  dependencies {
    classpath ""

plugins {
  id "java"
  id "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
version = "0.0.1"

repositories {

  maven {
    url ""

apply plugin: "com.github.johnrengelman.shadow"

dependencies {
  implementation "org.apache.avro:avro:1.11.1"
  implementation "org.slf4j:slf4j-simple:2.0.7"
  implementation 'org.apache.kafka:kafka-streams:3.4.0'
    implementation ('org.apache.kafka:kafka-clients') {
       version {
           strictly '3.4.0'
  implementation "io.confluent:kafka-streams-avro-serde:7.3.0"
  testImplementation "org.apache.kafka:kafka-streams-test-utils:3.4.0"
  testImplementation "junit:junit:4.13.2"

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

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

shadowJar {
  archiveBaseName = "ktable-fkjoins-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/

Create a schema for the events


This tutorial uses three streams: one called albums that holds album reference data, one called trackPurchases that holds an update-stream of inbound music track purchases, and one called musicInterestTable that holds the result of a foreign-key join between trackPurchases and albums.

In this case the inbound keys are different, but the trackPurchases stream has the id of the album in its value. We will use the KTable foreign-key join functionality to extract the album id and perform the join.

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/album.avsc for the album lookup table:

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Album",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "title", "type": "string"},
    {"name": "genre", "type": "string"},
    {"name": "artist", "type": "string"}

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

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "TrackPurchase",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "song_title", "type": "string"},
    {"name": "album_id", "type": "long"},
    {"name": "price", "type": "double"}

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

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "MusicInterest",
  "fields": [
    {"name": "id", "type": "string"},
    {"name": "genre", "type": "string"},
    {"name": "artist", "type": "string"}

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

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/ 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 table() method to create a KStream<Long, Album> object. In this case, we can use a KTable as each we know the topic is keyed by the album id and each album-id is unique.

Now that we have our table of albums, we’ll move on to the tracks available for purchase stream. While it may seem that purchasing music tracks would end up in a KStream, there are a couple of circumstances that allow us to represent the track purchases as a table instead.

First, each track purchase has a simple Long key, representing a increasing sequence number for each purchase. This means each purchase is unique, and we don’t need to worry about later sales replacing earlier purchases by the same customer. Second, we need to join each track purchase with an existing album so we can create a trend of artists and genres gaining or losing popularity.

But if the key is a monotonically increasing number, how can we join against the album table? The trackPurchases table has the album id as part of its value payload, so we can use the KTable.join method with a ForeignKeyExtractor parameter to extract the album id for the join comparison.

Creating the KTable<Long,TrackPurchase> of track purchases looks just like our first step with the albums: we create a table from the topic. Note that we must choose the same key—the album id—for our join to work. You can accomplish this by providing a Java 8 method handle TrackPurchase::getAlbumId to extract the id.

At this point we should discuss the importance of the order in which we use the KTable parameters in the join(). The trackPurchases table is the calling or left-side-table, and it is the table where the primary key is embedded in its value. The left-side-table always provides the ForeignKeyExtractor function.

The albums table is the right-side-table and always has the primary key for the join. This is where order matters, for example: if you tried albums.join(trackPurchases..) the join would never work as the albums table has no knowledge of the trackPurchases table details.

If you have a situation where you have two tables for which the primary keys don’t match, yet each table has a reference to the other’s primary key, then the order of the tables in the join method won’t matter. This scenario is probably unlikely in practice.

With the trackPurchases table and the albums 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 MusicInterestJoiner class. More on that in a moment.

For more background on KTable foreign key joins you can read the original KIP-213 proposal.

package io.confluent.developer;

import org.apache.avro.specific.SpecificRecord;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;

import java.time.Duration;
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 io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.Album;
import io.confluent.developer.avro.MusicInterest;
import io.confluent.developer.avro.TrackPurchase;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

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

public class FkJoinTableToTable {

	public Properties buildStreamsProperties(Properties envProps) {
        Properties props = new Properties();

        props.put(StreamsConfig.APPLICATION_ID_CONFIG, envProps.getProperty(""));
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, envProps.getProperty("bootstrap.servers"));
        props.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath());
        props.put(SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));

        return props;

    public Topology buildTopology(Properties envProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String albumTopic = envProps.getProperty("");
        final String userTrackPurchaseTopic = envProps.getProperty("");
        final String musicInterestTopic = envProps.getProperty("");

        final Serde<Long> longSerde = getPrimitiveAvroSerde(envProps, true);
        final Serde<MusicInterest> musicInterestSerde = getSpecificAvroSerde(envProps);
        final Serde<Album> albumSerde = getSpecificAvroSerde(envProps);
        final Serde<TrackPurchase> trackPurchaseSerde = getSpecificAvroSerde(envProps);

        final KTable<Long, Album> albums = builder.table(albumTopic, Consumed.with(longSerde, albumSerde));

        final KTable<Long, TrackPurchase> trackPurchases = builder.table(userTrackPurchaseTopic, Consumed.with(longSerde, trackPurchaseSerde));
        final MusicInterestJoiner trackJoiner = new MusicInterestJoiner();

        final KTable<Long, MusicInterest> musicInterestTable = trackPurchases.join(albums,

        musicInterestTable.toStream().to(musicInterestTopic, Produced.with(longSerde, musicInterestSerde));


    static <T> Serde<T> getPrimitiveAvroSerde(final Properties envProps, boolean isKey) {
        final KafkaAvroDeserializer deserializer = new KafkaAvroDeserializer();
        final KafkaAvroSerializer serializer = new KafkaAvroSerializer();
        final Map<String, String> config = new HashMap<>();
        deserializer.configure(config, isKey);
        serializer.configure(config, isKey);
        return (Serde<T>)Serdes.serdeFrom(serializer, deserializer);

    static <T extends SpecificRecord> SpecificAvroSerde<T> getSpecificAvroSerde(final Properties envProps) {
        final SpecificAvroSerde<T> specificAvroSerde = new SpecificAvroSerde<>();

        final HashMap<String, String> serdeConfig = new HashMap<>();

        specificAvroSerde.configure(serdeConfig, false);
        return specificAvroSerde;

    public void createTopics(final Properties envProps) {
        final Map<String, Object> config = new HashMap<>();
        config.put("bootstrap.servers", envProps.getProperty("bootstrap.servers"));
        final AdminClient client = AdminClient.create(config);

        final List<NewTopic> topics = new ArrayList<>();

        topics.add(new NewTopic(

        topics.add(new NewTopic(

        topics.add(new NewTopic(


    public Properties loadEnvProperties(String fileName) throws IOException {
        final Properties envProps = new Properties();
        final FileInputStream input = new FileInputStream(fileName);

        return envProps;

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

        final FkJoinTableToTable tableFkJoin = new FkJoinTableToTable();
        final Properties envProps = tableFkJoin.loadEnvProperties(args[0]);
        final Properties streamProps = tableFkJoin.buildStreamsProperties(envProps);
        final Topology topology = tableFkJoin.buildTopology(envProps);


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

        // Attach shutdown handler to catch Control-C.
        Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
            public void run() {

        try {
        } catch (Throwable e) {


Implement a ValueJoiner class


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

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. In Kafka Streams, when you join two tables, you still get a new table, but you must be explicit about which value(s) are included from both tables.

The ValueJoiner interface in the Streams API does this work. The single apply() method takes the "left" table and the "right" table values as parameters, and returns the value of the joined table 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 MusicInterest object and populating it with the relevant fields of the input album and track purchase.

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 io.confluent.developer.avro.MusicInterest;
import io.confluent.developer.avro.TrackPurchase;
import io.confluent.developer.avro.Album;
import org.apache.kafka.streams.kstream.ValueJoiner;

public class MusicInterestJoiner implements ValueJoiner<TrackPurchase, Album, MusicInterest> {
    public MusicInterest apply(TrackPurchase trackPurchase, Album album) {
        return MusicInterest.newBuilder()
                .setId(album.getId() + "-" + trackPurchase.getId())

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/ktable-fkjoins-standalone-0.0.1.jar configuration/

Load in some movie reference data


In a new terminal, run:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic albums --bootstrap-server broker:9092 \
  --property "parse.key=true"\
  --property 'key.schema={"type":"long"}'\
  --property "key.separator=:"\
  --property value.schema="$(< src/main/avro/album.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 a : between the key and the value, so retyping them without the colon will not work.

Each line represents an album that has individual tracks for purchase. To send all of the events below, paste the following into the prompt and press enter:

5:{"id": 5, "title": "Physical Graffiti", "artist": "Led Zeppelin", "genre": "Rock"}
6:{"id": 6, "title": "Highway to Hell",   "artist": "AC/DC", "genre": "Rock"}
7:{"id": 7, "title": "Radio", "artist": "LL Cool J",  "genre": "Hip hop"}
8:{"id": 8, "title": "King of Rock", "artist": "Run-D.M.C", "genre": "Rap rock"}

Before you start producing track purchases, it’s a good idea to set up the consumer on the output topic. This way, as soon as you produce track purchases (and they’re joined to albums creating a music interest trend), you’ll see the results right away. Run this to get ready to consume the music interest trends:

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

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

Produce some track purchases 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 music interest results) 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 purchases --bootstrap-server broker:9092 \
  --property "parse.key=true"\
  --property 'key.schema={"type":"long"}'\
  --property "key.separator=:"\
  --property value.schema="$(< src/main/avro/track-purchase.avsc)"

When the producer starts up, copy and paste these lines into the terminal. Then you can observe the results in the consumer terminal:

100:{"id": 100, "album_id": 5, "song_title": "Houses Of The Holy", "price": 0.99}
101:{"id": 101, "album_id": 8, "song_title": "King Of Rock", "price": 0.99}
102:{"id": 102, "album_id": 6, "song_title": "Shot Down In Flames", "price": 0.99}
103:{"id": 103, "album_id": 7, "song_title": "Rock The Bells", "price": 0.99}
104:{"id": 104, "album_id": 8, "song_title": "Can You Rock It Like This", "price": 0.99}
105:{"id": 105, "album_id": 6, "song_title": "Highway To Hell", "price": 0.99}
106:{"id": 106, "album_id": 5, "song_title": "Kashmir", "price": 0.99}

Please note that do to the nature of how a KTable works, you won’t see results simultaneously. You need to wait roughly 30 seconds or so after pasting the lines above to see any results in the consumer terminal.

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

{"id": "5-100", "genre": "Rock", "artist": "Led Zeppelin"}
{"id": "8-101", "genre": "Rap rock", "artist": "Run-D.M.C"}
{"id": "6-102", "genre": "Rock", "artist": "AC/DC"}
{"id": "7-103", "genre": "Hip hop", "artist": "LL Cool J"}
{"id": "8-104", "genre": "Rap rock", "artist": "Run-D.M.C"}
{"id": "6-105", "genre": "Rock", "artist": "AC/DC"}
{"id": "5-106", "genre": "Rock", "artist": "Led Zeppelin"}

You have now joined a table to a table with a foreign key! Well done.

Test it

Create a test configuration file


First, create a test file at configuration/

You should take note of the schema.registry.url configuration. The config is using a special pseudo-protocol mock://.. which means our test code doesn’t need to have an actual Schema Registry instance running. The test uses a MockSchemaRegistry instead, specifically for unit testing.

Test the MusicInterestJoiner 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/ This tests the helper class that merges the value of the album and the track purchase as each purchase is joined to an album. The class has a dependency on the ValueJoiner interface, but otherwise does not depend on anything external to our domain; it just needs Album, TrackPurchase, and MusicInterest` domain objects. As such, it’s about as testable as code gets:

package io.confluent.developer;

import io.confluent.developer.avro.Album;
import io.confluent.developer.avro.MusicInterest;
import io.confluent.developer.avro.TrackPurchase;
import org.junit.Test;

import static org.junit.Assert.*;

public class MusicInterestJoinerTest {

    public void apply() {

        MusicInterest returnedMusicInterest;

        Album theAlbum = Album.newBuilder().setTitle("Album Title").setId(100).setArtist("the artist").setGenre("testing").build();
        TrackPurchase theTrackPurchase = TrackPurchase.newBuilder().setId(5000).setAlbumId(100).setPrice(1.25).setSongTitle("song-title").build();
        MusicInterest expectedMusicInterest = MusicInterest.newBuilder().setArtist("the artist").setId("100-5000").setGenre("testing").build();

        MusicInterestJoiner joiner = new MusicInterestJoiner();
        returnedMusicInterest = joiner.apply(theTrackPurchase, theAlbum);

        assertEquals(returnedMusicInterest, expectedMusicInterest);

Test the streams topology


Now create the following file at src/test/java/io/confluent/developer/ 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 than it would otherwise be.

There is only one method in FkJoinTableToTableTest 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 static org.junit.Assert.assertEquals;

import io.confluent.developer.avro.Album;
import io.confluent.developer.avro.MusicInterest;
import io.confluent.developer.avro.TrackPurchase;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringDeserializer;
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.junit.Test;

public class FkJoinTableToTableTest {

    private final static String TEST_CONFIG_FILE = "configuration/";

    public void testJoin() throws IOException {
        final FkJoinTableToTable fkJoin = new FkJoinTableToTable();
        final Properties envProps = fkJoin.loadEnvProperties(TEST_CONFIG_FILE);

        final Properties streamProps = fkJoin.buildStreamsProperties(envProps);

        final String albumInputTopic = envProps.getProperty("");
        final String userPurchaseTopic = envProps.getProperty("");
        final String joinedResultOutputTopic = envProps.getProperty("");

        final Topology topology = fkJoin.buildTopology(envProps);
        try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, streamProps)) {

            final Serializer<Long> keySerializer = FkJoinTableToTable.<Long>getPrimitiveAvroSerde(envProps, true).serializer();
            final Serializer<Album> albumSerializer = FkJoinTableToTable.<Album>getSpecificAvroSerde(envProps).serializer();
            final Serializer<TrackPurchase> trackPurchaseSerializer = FkJoinTableToTable.<TrackPurchase>getSpecificAvroSerde(envProps).serializer();

            final Deserializer<MusicInterest> musicInterestDeserializer = FkJoinTableToTable.<MusicInterest>getSpecificAvroSerde(envProps).deserializer();

            final TestInputTopic<Long, Album>  albumTestInputTopic = testDriver.createInputTopic(albumInputTopic, keySerializer, albumSerializer);
            final TestInputTopic<Long, TrackPurchase> trackPurchaseInputTopic = testDriver.createInputTopic(userPurchaseTopic, keySerializer, trackPurchaseSerializer);
            final TestOutputTopic<String, MusicInterest> outputTopic = testDriver.createOutputTopic(joinedResultOutputTopic, new StringDeserializer(), musicInterestDeserializer);

            final List<Album> albums = new ArrayList<>();
            albums.add(Album.newBuilder().setId(5L).setTitle("Physical Graffiti").setArtist("Led Zeppelin").setGenre("Rock").build());
            albums.add(Album.newBuilder().setId(6L).setTitle("Highway to Hell").setArtist("AC/DC").setGenre("Rock").build());
            albums.add(Album.newBuilder().setId(7L).setTitle("Radio").setArtist("LL Cool J").setGenre("Hip hop").build());
            albums.add(Album.newBuilder().setId(8L).setTitle("King of Rock").setArtist("Run-D.M.C").setGenre("Rap rock").build());

            final List<TrackPurchase> trackPurchases = new ArrayList<>();
            trackPurchases.add(TrackPurchase.newBuilder().setId(100).setAlbumId(5L).setSongTitle("Houses Of The Holy").setPrice(0.99).build());
            trackPurchases.add(TrackPurchase.newBuilder().setId(101).setAlbumId(8L).setSongTitle("King Of Rock").setPrice(0.99).build());
            trackPurchases.add(TrackPurchase.newBuilder().setId(102).setAlbumId(6L).setSongTitle("Shot Down In Flames").setPrice(0.99).build());
            trackPurchases.add(TrackPurchase.newBuilder().setId(103).setAlbumId(7L).setSongTitle("Rock The Bells").setPrice(0.99).build());
            trackPurchases.add(TrackPurchase.newBuilder().setId(104).setAlbumId(8L).setSongTitle("Can You Rock It Like This").setPrice(0.99).build());
            trackPurchases.add(TrackPurchase.newBuilder().setId(105).setAlbumId(6L).setSongTitle("Highway To Hell").setPrice(0.99).build());

            final List<MusicInterest> expectedMusicInterestJoinResults = new ArrayList<>();
            expectedMusicInterestJoinResults.add(MusicInterest.newBuilder().setId("5-100").setGenre("Rock").setArtist("Led Zeppelin").build());
            expectedMusicInterestJoinResults.add(MusicInterest.newBuilder().setId("8-101").setGenre("Rap rock").setArtist("Run-D.M.C").build());
            expectedMusicInterestJoinResults.add(MusicInterest.newBuilder().setId("7-103").setGenre("Hip hop").setArtist("LL Cool J").build());
            expectedMusicInterestJoinResults.add(MusicInterest.newBuilder().setId("8-104").setGenre("Rap rock").setArtist("Run-D.M.C").build());
            expectedMusicInterestJoinResults.add(MusicInterest.newBuilder().setId("5-106").setGenre("Rock").setArtist("Led Zeppelin").build());

            for (final Album album : albums) {
                albumTestInputTopic.pipeInput(album.getId(), album);

            for (final TrackPurchase trackPurchase : trackPurchases) {
                trackPurchaseInputTopic.pipeInput(trackPurchase.getId(), trackPurchase);

            final List<MusicInterest> actualJoinResults = outputTopic.readValuesToList();

            assertEquals(expectedMusicInterestJoinResults, actualJoinResults);

Invoke the tests


Now run the test, which is as simple as:

./gradlew test

Deploy on Confluent Cloud

Run your app with 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 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). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.

  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. 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 required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
# Required for correctness in Apache Kafka clients prior to 2.6

# Best practice for Kafka producer to prevent data loss

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url=https://{{ SR_ENDPOINT }}
basic.auth.credentials.source=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.