How to dynamically choose the output topic

Question:

How can I dynamically route records to different Kafka topics?

Edit this page

Example use case:

Consider a situation where, depending on data in your records, you need to direct output to different topic. In this tutorial, you'll learn how to instruct Kafka Streams to choose the output topic at runtime.

Code example:

Try 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

2
Get Confluent Platform

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

---
version: '2'

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

  broker:
    image: confluentinc/cp-enterprise-kafka:5.5.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: broker:9092
      CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      CONFLUENT_METRICS_ENABLE: 'true'
      CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'

  schema-registry:
    image: confluentinc/cp-schema-registry:5.5.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - zookeeper
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: 'zookeeper:2181'
      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 {
        jcenter()
    }
    dependencies {
        classpath "com.commercehub.gradle.plugin:gradle-avro-plugin:0.15.1"
        classpath "com.github.jengelman.gradle.plugins:shadow:4.0.2"
    }
}

plugins {
    id "java"
    id "com.google.cloud.tools.jib" version "2.5.0"
    id "idea"
    id "eclipse"
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"
version = "0.0.1"

repositories {
    mavenCentral()
    jcenter()

    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.8.2"
    implementation "org.slf4j:slf4j-simple:1.7.30"
    implementation "org.apache.kafka:kafka-streams:2.4.1"
    implementation "io.confluent:kafka-streams-avro-serde:5.4.0"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.4.1"
    testImplementation "junit:junit:4.12"
    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

Next, create a directory for configuration data:

mkdir configuration

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

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

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

4
Create a schema for the model obect

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

5
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<Long, 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 io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.CompletedOrder;
import io.confluent.developer.avro.Order;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.SecureRandom;
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.Random;
import java.util.concurrent.CountDownLatch;
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;

public class DynamicOutputTopic {

    static final double FAKE_PRICE = 0.467423D;

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

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

        return props;
    }

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

        final Serde<Long> longSerde = getPrimitiveAvroSerde(envProps, true);
        final Serde<Order> orderSerde = getSpecificAvroSerde(envProps);
        final Serde<CompletedOrder> completedOrderSerde = getSpecificAvroSerde(envProps);

        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<Long, 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<Long, Order> exampleStream = builder.stream(orderInputTopic, Consumed.with(longSerde, orderSerde));

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

        return builder.build();
    }

    @SuppressWarnings("unchecked")
    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<>();
        config.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                envProps.getProperty("schema.registry.url"));
        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<>();
        serdeConfig.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                envProps.getProperty("schema.registry.url"));

        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"));
        try (final AdminClient client = AdminClient.create(config)) {

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

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

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

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

            client.createTopics(topics);
        }
    }

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

        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 DynamicOutputTopic instance = new DynamicOutputTopic();
        final Properties envProps = instance.loadEnvProperties(args[0]);
        final Properties streamProps = instance.buildStreamsProperties(envProps);
        final Topology topology = instance.buildTopology(envProps);

        instance.createTopics(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") {
            @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
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

7
Produce sample orders to the input topic

In a new terminal, run:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic input --broker-list broker:9092\
  --property "parse.key=true"\
  --property 'key.schema={"type":"long"}'\
  --property "key.separator=:"\
  --property value.schema="$(< src/main/avro/order.avsc)"

When the console producer starts, it will log some messages and hang, waiting for your input. Each line represents input data for the Kafka Streams application. 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"}

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

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

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.

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

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}

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 static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import io.confluent.developer.avro.CompletedOrder;
import io.confluent.developer.avro.Order;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import java.io.IOException;
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.Serde;
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;


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 envProps = instance.loadEnvProperties(TEST_CONFIG_FILE);

        final Properties streamProps = instance.buildStreamsProperties(envProps);

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

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

            final Serde<Long> longAvroSerde = DynamicOutputTopic.getPrimitiveAvroSerde(envProps, true);
            final SpecificAvroSerde<Order> orderAvroSerde = DynamicOutputTopic.getSpecificAvroSerde(envProps);
            final SpecificAvroSerde<CompletedOrder> completedOrderAvroSerde = DynamicOutputTopic.getSpecificAvroSerde(envProps);

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

            final TestInputTopic<Long, Order>  inputTopic = testDriver.createInputTopic(orderInputTopic, keySerializer, orderSerializer);
            final TestOutputTopic<Long, CompletedOrder> orderTopic = testDriver.createOutputTopic(orderOutputTopic, keyDeserializer, completedOrderDeserializer);
            final TestOutputTopic<Long, 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(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

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.

First, create your Kafka cluster in Confluent Cloud. Use the promo code CC100KTS to receive an additional $100 free usage (details).

Next, from the Confluent Cloud UI, click on Tools & client config 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.

Now you’re all set to your run application locally while your Kafka topics and stream processing is backed to your Confluent Cloud instance.