How to dynamically choose the output topic at runtime

Question:

How can I dynamically route records to different Kafka topics, like a "topic exchange"?

Edit this page

Example use case:

Consider a situation where you want to direct output of different records to different topics, like a "topic exchange". In this tutorial, you'll learn how to instruct Kafka Streams to choose the output topic at runtime, based on information in each record's header, key, or value.


TweetShare your tutorial progress

Hands-on code example:

New to Confluent Cloud? Sign up and then run this tutorial.




Short Answer

Use the TopicNameExtractor interface to apply runtime logic to choose the output topic. The example below derives the output topic name from the record’s value, but it can also be derived from the record’s header (i.e., recordContext) or key.

final TopicNameExtractor <String, CompletedOrder> orderTopicNameExtractor = (key, completedOrder, recordContext) -> {
      final String compositeId = completedOrder.getId();
      final String skuPart = compositeId.substring(compositeId.indexOf('-') + 1, 5);
      final String outTopic;
      if (skuPart.equals("QUA")) {
           outTopic = specialOrderOutput;
      } else {
           outTopic = orderOutputTopic;
      }
      return outTopic;
};

Run it

1
Initialize the project

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

mkdir dynamic-output-topic && cd dynamic-output-topic

Next, create a directory for configuration data:

mkdir configuration

2
Provision your Kafka cluster

The quickest way to get started with Apache Kafka is on Confluent Cloud, which provides it as a fully managed service. First, sign up for Confluent Cloud.

  1. After you log in to Confluent Cloud, 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.

  2. From the Billing & payment section in the Menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details).

  3. Click on LEARN and follow the instructions to launch a Kafka cluster and to enable Schema Registry.

Confluent Cloud

3
Write the cluster information into a local file

From the Confluent Cloud Console, navigate to your Kafka cluster. From the Clients view, get the connection information customized to your cluster (select Java).

Create new credentials for your Kafka cluster and Schema Registry, and then Confluent Cloud will show a configuration similar to below with your new credentials automatically populated (make sure show API keys is checked). Copy and paste it into a configuration/ccloud.properties file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
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={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the Confluent Cloud Console so that it includes your Confluent Cloud information and credentials.

4
Download and setup the Confluent Cloud CLI

This tutorial has some steps for Kafka topic management and/or reading from or writing to Kafka topics, for which you can use the Confluent Cloud Console or install the Confluent Cloud CLI. Instructions for installing Confluent Cloud CLI and configuring it to your Confluent Cloud environment is available from within the Confluent Cloud Console: navigate to your Kafka cluster, click on the CLI and tools section, and run through the steps in the CCloud CLI tab.

5
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"
    id "idea"
    id "eclipse"
}

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.8.1"
    implementation "io.confluent:kafka-streams-avro-serde:6.2.1"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.8.1"
    testImplementation "junit:junit:4.13.2"
    testImplementation 'org.hamcrest:hamcrest:2.2'
}

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

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

shadowJar {
    archivesBaseName = "dynamic-output-topic-standalone"
    archiveClassifier = ''
}

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

gradle wrapper

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

application.id=dynamic-output-topic
replication.factor=3

input.topic.name=input
input.topic.partitions=6
input.topic.replication.factor=3

output.topic.name=regular-order
output.topic.partitions=6
output.topic.replication.factor=3

special.order.topic.name=special-order
special.order.topic.partitions=6
special.order.topic.replication.factor=3

6
Update the properties file with Confluent Cloud information

Using the command below, append the contents of configuration/ccloud.properties (with your Confluent Cloud configuration) to configuration/dev.properties (with the application properties).

cat configuration/ccloud.properties >> configuration/dev.properties

7
Create a schema for the model object

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

mkdir -p src/main/avro

First create the following Avro schema file at src/main/avro/order.avsc to create Order objects to stream:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Order",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "sku", "type": "string"},
    {"name": "name", "type": "string"},
    {"name": "quantity", "type": "long"}
  ]
}

Then create this Avro schema file at src/main/avro/completed-order.avsc to create CompletedOrder objects:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "CompletedOrder",
  "fields": [
    {"name": "id", "type": "string"},
    {"name": "name", "type": "string"},
    {"name": "amount", "type": "double"}
  ]
}

Because we will use an 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

8
Create the Kafka Streams topology

Create a directory for the Java files in this project:

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

The focus of this tutorial is using attributes in the output records to determine the correct output topic. For sending fully-processed records, typically you would use the KStream.to() method, which takes the name of the output topic. You can think of this as setting the output topic statically.

For dynamic output topic choice, Kafka Streams has an overloaded version of the KStream.to() method that takes a TopicNameExtractor interface instead of a singular topic name. The TopicNameExtractor interface contains only one method, extract. This means you can use a lambda in most cases, instead of a concrete class.

The TopicNameExtractor.extract() method accepts three parameters: the key, value, and RecordContext of the current record. It returns a String – the output topic to use.

Now take a detailed look at the TopicNameExtractor you’ll use in this tutorial (found on line 67 in DynamicOutputTopic.java)

final TopicNameExtractor <String, CompletedOrder> orderTopicNameExtractor = (key, completedOrder, recordContext) -> {
      final String compositeId = completedOrder.getId();
      final String skuPart = compositeId.substring(compositeId.indexOf('-') + 1, 5);
      final String outTopic;
      if (skuPart.equals("QUA")) {
           outTopic = specialOrderOutput;
      } else {
           outTopic = orderOutputTopic;
      }
      return outTopic;
};

In the code above, the TopicNameExtractor takes the CompletedOrder.id field. Based on the extracted substring, it returns the name of the topic to use. You should also note that the topics need to be created ahead of time as with any of the topics used by Kafka Streams.

Now go ahead and create the following file at src/main/java/io/confluent/developer/DynamicOutputTopic.java.

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.KStream;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.apache.kafka.streams.processor.TopicNameExtractor;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
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.CompletedOrder;
import io.confluent.developer.avro.Order;
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 DynamicOutputTopic {

    static final double FAKE_PRICE = 0.467423D;

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String orderInputTopic = allProps.getProperty("input.topic.name");
        final String orderOutputTopic = allProps.getProperty("output.topic.name");
        final String specialOrderOutput = allProps.getProperty("special.order.topic.name");

        final Serde<String> stringSerde = Serdes.String();
        final Serde<Order> orderSerde = getSpecificAvroSerde(allProps);
        final Serde<CompletedOrder> completedOrderSerde = getSpecificAvroSerde(allProps);

        final ValueMapper<Order, CompletedOrder> orderProcessingSimulator = v -> {
           double amount = v.getQuantity() * FAKE_PRICE;
           return CompletedOrder.newBuilder().setAmount(amount).setId(v.getId() + "-" + v.getSku()).setName(v.getName()).build();
        };

        final TopicNameExtractor<String, CompletedOrder> orderTopicNameExtractor = (key, completedOrder, recordContext) -> {
              final String compositeId = completedOrder.getId();
              final String skuPart = compositeId.substring(compositeId.indexOf('-') + 1, 5);
              final String outTopic;
              if (skuPart.equals("QUA")) {
                  outTopic = specialOrderOutput;
              } else {
                  outTopic = orderOutputTopic;
              }
              return outTopic;
        };

        final KStream<String, Order> exampleStream = builder.stream(orderInputTopic, Consumed.with(stringSerde, orderSerde));

        exampleStream.mapValues(orderProcessingSimulator).to(orderTopicNameExtractor, Produced.with(stringSerde, completedOrderSerde));

        return builder.build();
    }

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

        final Map<String, String> serdeConfig = (Map)allProps;
        specificAvroSerde.configure(serdeConfig, false);
        return specificAvroSerde;
    }

    public void createTopics(final Properties allProps) {
        try (final AdminClient client = AdminClient.create(allProps)) {

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

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

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

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

            client.createTopics(topics);
        }
    }

    public Properties loadEnvProperties(String fileName) throws IOException {
        final Properties allProps = new Properties();
        final 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.");
        }

        final DynamicOutputTopic instance = new DynamicOutputTopic();

        final Properties allProps = new Properties();
        try (InputStream inputStream = new FileInputStream(args[0])) {
            allProps.load(inputStream);
        }
        allProps.put(StreamsConfig.APPLICATION_ID_CONFIG, allProps.getProperty("application.id"));
        allProps.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath());

        final Topology topology = instance.buildTopology(allProps);

        instance.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);
    }

}

9
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/dynamic-output-topic-standalone-0.0.1.jar configuration/dev.properties

10
Produce sample orders to the input topic

In a new terminal, run:

ccloud kafka topic produce input \
  --parse-key \
  --delimiter ":" \
  --value-format avro \
  --schema src/main/avro/order.avsc

You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ccloud.properties configuration file. Look for the configuration parameter basic.auth.user.info, whereby the ":" is the delimiter between the key and secret.

Enter your Schema Registry API key:
Enter your Schema Registry API secret:

When the console producer starts, it will log some messages and hang, waiting for your input. Type in one line at a time and press enter to send it. Each line represents an event. To send all of the events below, paste the following into the prompt and press enter:

"5":{"id":5,"name":"tp","quantity":10000, "sku":"QUA00000123"}
"6":{"id":6,"name":"coffee","quantity":1000, "sku":"COF0003456"}
"7":{"id":7,"name":"hand-sanitizer","quantity":6000, "sku":"QUA000022334"}
"8":{"id":8,"name":"beer","quantity":4000, "sku":"BER88899222"}

11
Consume orders from the different output topics

Now that you have produced some orders, you should set up a consumer to view the results. In this case, you need to start two consumers as the Kafka Streams application dynamically chooses which output topic to use depending on information contained in the Order object.

In a new terminal window start the following console consumer to view regular sized Order objects.

ccloud kafka topic consume regular-order -b --value-format avro

You should see output that looks like this:

{"id":"6-COF0003456","name":"coffee","amount":467.423}
{"id":"8-BER88899222","name":"beer","amount":1869.692}

Then close the current console consumer or open a second terminal window and start another console consumer to view the special CompletedOrder objects. Remember the Kafka Streams application determines at runtime where to send each order based on the information contained in the CompletedOrder object.

ccloud kafka topic consume special-order -b --value-format avro

The special order console consumer should yield this output:

{"id":"5-QUA00000123","name":"tp","amount":4674.23}
{"id":"7-QUA000022334","name":"hand-sanitizer","amount":2804.538}

12
Teardown Confluent Cloud resources

You may try another Kafka tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud Console or CLI to destroy all the resources you created. Verify they are destroyed to avoid unexpected charges.

Test it

1
Create a test configuration file

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

application.id=dynamic-output-topic
bootstrap.servers=localhost:29092
schema.registry.url=mock://dynamic-output-topic-test

input.topic.name=input
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=regular-order
output.topic.partitions=1
output.topic.replication.factor=1

special.order.topic.name=special-order
special.order.topic.partitions=1
special.order.topic.replication.factor=1

2
Write a test

Create a directory for the tests to live in:

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

Now create the following file at src/test/java/io/confluent/developer/DynamicOutputTopicTest.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 DynamicOutputTopicTest annotated with @Test, and that is shouldChooseCorrectOutputTopic(). 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.Serde;
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.junit.Test;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import io.confluent.developer.avro.CompletedOrder;
import io.confluent.developer.avro.Order;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;


public class DynamicOutputTopicTest {

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

  @Test
  public void shouldChooseCorrectOutputTopic() throws IOException {
    final DynamicOutputTopic instance = new DynamicOutputTopic();

    final Properties allProps = new Properties();
    try (InputStream inputStream = new FileInputStream(TEST_CONFIG_FILE)) {
        allProps.load(inputStream);
    }

    final String orderInputTopic = allProps.getProperty("input.topic.name");
    final String orderOutputTopic = allProps.getProperty("output.topic.name");
    final String specialOrderOutputTopic = allProps.getProperty("special.order.topic.name");

    final Topology topology = instance.buildTopology(allProps);
    try (final TopologyTestDriver testDriver = new TopologyTestDriver(topology, allProps)) {

      final Serde<String> stringSerde = Serdes.String();
      final SpecificAvroSerde<Order> orderAvroSerde = DynamicOutputTopic.getSpecificAvroSerde(allProps);
      final SpecificAvroSerde<CompletedOrder>
          completedOrderAvroSerde =
          DynamicOutputTopic.getSpecificAvroSerde(allProps);

      final Serializer<String> keySerializer = stringSerde.serializer();
      final Deserializer<String> keyDeserializer = stringSerde.deserializer();
      final Serializer<Order> orderSerializer = orderAvroSerde.serializer();
      final Deserializer<CompletedOrder> completedOrderDeserializer = completedOrderAvroSerde.deserializer();

      final TestInputTopic<String, Order>
          inputTopic =
          testDriver.createInputTopic(orderInputTopic, keySerializer, orderSerializer);
      final TestOutputTopic<String, CompletedOrder>
          orderTopic =
          testDriver.createOutputTopic(orderOutputTopic, keyDeserializer, completedOrderDeserializer);
      final TestOutputTopic<String, CompletedOrder>
          specialOrderTopic =
          testDriver.createOutputTopic(specialOrderOutputTopic, keyDeserializer, completedOrderDeserializer);

      final List<Order> orders = new ArrayList<>();
      orders.add(Order.newBuilder().setId(5L).setName("tp").setQuantity(10_000L).setSku("QUA00000123").build());
      orders.add(Order.newBuilder().setId(6L).setName("coffee").setQuantity(1_000L).setSku("COF0003456").build());
      orders.add(
          Order.newBuilder().setId(7L).setName("hand-sanitizer").setQuantity(6_000L).setSku("QUA000022334").build());
      orders.add(Order.newBuilder().setId(8L).setName("beer").setQuantity(4_000L).setSku("BER88899222").build());

      final List<CompletedOrder> expectedRegularCompletedOrders = new ArrayList<>();
      expectedRegularCompletedOrders.add(CompletedOrder.newBuilder().setName("coffee").setId("6-COF0003456")
                                             .setAmount(1_000L * DynamicOutputTopic.FAKE_PRICE).build());
      expectedRegularCompletedOrders.add(CompletedOrder.newBuilder().setName("beer").setId("8-BER88899222")
                                             .setAmount(4_000L * DynamicOutputTopic.FAKE_PRICE).build());

      final List<CompletedOrder> expectedSpecialOrders = new ArrayList<>();
      expectedSpecialOrders.add(CompletedOrder.newBuilder().setId("5-QUA00000123").setName("tp")
                                    .setAmount(10_000L * DynamicOutputTopic.FAKE_PRICE).build());
      expectedSpecialOrders.add(CompletedOrder.newBuilder().setId("7-QUA000022334").setName("hand-sanitizer")
                                    .setAmount(6_000L * DynamicOutputTopic.FAKE_PRICE).build());

      for (final Order order : orders) {
        inputTopic.pipeInput(String.valueOf(order.getId()), order);
      }

      final List<CompletedOrder> actualRegularOrderResults = orderTopic.readValuesToList();
      final List<CompletedOrder> actualSpecialCompletedOrders = specialOrderTopic.readValuesToList();

      assertThat(expectedRegularCompletedOrders, equalTo(actualRegularOrderResults));
      assertThat(expectedSpecialOrders, equalTo(actualSpecialCompletedOrders));
    }
  }
}

3
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=dynamic-output-topic
bootstrap.servers=<<FILL ME IN>>
schema.registry.url=<<FILL ME IN>>

example.topic.name=<<FILL ME IN>>
example.topic.partitions=<<FILL ME IN>>
example.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/dynamic-output-topic-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/dynamic-output-topic-join:0.0.1 config.properties