How to dynamically choose the output topic at runtime

Question:

How can you 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 the 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. Related pattern: Event Router.

Hands-on code example:

New to Confluent Cloud? Get started here.

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

Initialize the project

1

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

Provision your Kafka cluster

2

This tutorial requires access to an Apache Kafka cluster, and the quickest way to get started free is on Confluent Cloud, which provides Kafka as a fully managed service.

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

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

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

Confluent Cloud

Write the cluster information into a local file

3

From the Confluent Cloud Console, navigate to your Kafka cluster and then select Clients in the lefthand navigation. From the Clients view, create a new client and click Java to get the connection information customized to your cluster.

Create new credentials for your Kafka cluster and Schema Registry, writing in appropriate descriptions so that the keys are easy to find and delete later. The Confluent Cloud Console 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.

Download and set up the Confluent CLI

4

This tutorial has some steps for Kafka topic management and producing and consuming events, for which you can use the Confluent Cloud Console or the Confluent CLI. Follow the instructions here to install the Confluent CLI, and then follow these steps connect the CLI to your Confluent Cloud cluster.

Configure the project

5

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

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "gradle.plugin.com.github.jengelman.gradle.plugins:shadow:7.0.0"
    }
}

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

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

repositories {
    mavenCentral()

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

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

Update the properties file with Confluent Cloud information

6

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

Create a schema for the model object

7

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

Create the Kafka Streams topology

8

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

}

Compile and run the Kafka Streams program

9

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

Produce sample orders to the input topic

10

In a new terminal, run:

confluent kafka topic produce input \
  --parse-key \
  --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"}

Consume orders from the different output topics

11

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.

confluent 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.

confluent 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}

Teardown Confluent Cloud resources

12

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

Test it

Create a test configuration file

1

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

Write a test

2

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

Invoke the tests

3

Now run the test, which is as simple as:

./gradlew test