How to split a stream of events into substreams


How do you split events in a Kafka topic so that the events are placed into subtopics?

Edit this page

Example use case:

Suppose that you have a Kafka topic representing appearances of an actor or actress in a film, with each event denoting the genre. In this tutorial, we'll write a program that splits the stream into substreams based on the genre. We'll have a topic for drama films, a topic for fantasy films, and a topic for everything else. Related pattern: Event Router.

Hands-on code example:

New to Confluent Cloud? Get started here.

Short Answer

Use the split() and branch() method, see below. Notice the last predicate which simply returns true, which acts as an "else" statement to catch all events that don’t match the other predicates.

        builder.<String, ActingEvent>stream(inputTopic)
                   (key, appearance) -> "drama".equals(appearance.getGenre()),
                   Branched.withConsumer(ks ->""))))
                   (key, appearance) -> "fantasy".equals(appearance.getGenre()),
                   Branched.withConsumer(ks ->""))))
                   (key, appearance) -> true,
                   Branched.withConsumer(ks ->""))));

Run it

Initialize the project


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

mkdir split-stream && cd split-stream

Next, create a directory for configuration data:

mkdir configuration

Provision your Kafka cluster


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

Write the cluster information into a local file


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/ file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
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={{ SR_URL }}
basic.auth.credentials.source=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 setup the Confluent 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 CLI. Instructions for installing Confluent 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 link, and run through the steps in the Confluent CLI tab.

Configure the project


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

buildscript {
  repositories {
  dependencies {
    classpath ""

plugins {
  id "java"
  id "" version "3.3.1"
  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.SplitStream"

shadowJar {
  archiveBaseName = "kstreams-split-standalone"
  archiveClassifier = ""

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

gradle wrapper

Then create a development configuration file at configuration/

Update the properties file with Confluent Cloud information


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

cat configuration/ >> configuration/

Create a schema for the events


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/acting_event.avsc for the acting appearance events:

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "ActingEvent",
  "fields": [
    {"name": "name", "type": "string"},
    {"name": "title", "type": "string"},
    {"name": "genre", "type": "string"}

Because we will use this Avro schema in our Java code, we’ll need to compile it. Run the following:

./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/ Notice the buildTopology method, which uses the Kafka Streams DSL. By using the split and Branched methods, which are stateless record-by-record operations, you can create branches for messages that match the predicate. If no predicates are matched, the event gets dropped from further processing, but in this case, notice the last predicate, which simply returns true. This acts as an "else" statement to catch all events that don’t match the other predicates.

KIP-418 for details on method-chaining to branch a KStream.

package io.confluent.developer;

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

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

import io.confluent.developer.avro.ActingEvent;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

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

public class SplitStream {

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String inputTopic = allProps.getProperty("");

        builder.<String, ActingEvent>stream(inputTopic)
                   (key, appearance) -> "drama".equals(appearance.getGenre()),
                   Branched.withConsumer(ks ->""))))
                   (key, appearance) -> "fantasy".equals(appearance.getGenre()),
                   Branched.withConsumer(ks ->""))))
                   (key, appearance) -> true,
                   Branched.withConsumer(ks ->""))));


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

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

        topics.add(new NewTopic(

        topics.add(new NewTopic(

        topics.add(new NewTopic(

        topics.add(new NewTopic(


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

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

        SplitStream ss = new SplitStream();
        Properties allProps = ss.loadEnvProperties(args[0]);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);

        Topology topology = ss.buildTopology(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") {
            public void run() {

        try {
        } catch (Throwable e) {

Compile and run the Kafka Streams program


In your terminal, run:

./gradlew shadowJar

Now that an uberjar for the Kafka Streams application has been built, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it:

java -jar build/libs/kstreams-split-standalone-0.0.1.jar configuration/

Produce events to the input topic


In a new terminal, run:

confluent kafka topic produce acting-events --value-format avro --schema src/main/avro/acting_event.avsc

You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ configuration file. Look for the configuration parameter, 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:

{"name": "Meryl Streep", "title": "The Iron Lady", "genre": "drama"}
{"name": "Will Smith", "title": "Men in Black", "genre": "comedy"}
{"name": "Matt Damon", "title": "The Martian", "genre": "drama"}
{"name": "Judy Garland", "title": "The Wizard of Oz", "genre": "fantasy"}
{"name": "Jennifer Aniston", "title": "Office Space", "genre": "comedy"}
{"name": "Bill Murray", "title": "Ghostbusters", "genre": "fantasy"}
{"name": "Christian Bale", "title": "The Dark Knight", "genre": "crime"}
{"name": "Laura Dern", "title": "Jurassic Park", "genre": "fantasy"}
{"name": "Keanu Reeves", "title": "The Matrix", "genre": "fantasy"}
{"name": "Russell Crowe", "title": "Gladiator", "genre": "drama"}
{"name": "Diane Keaton", "title": "The Godfather: Part II", "genre": "crime"}

Consume the event subsets from the output topics


Leave your original terminal running. To consume the output events from each of the topic, you’ll need to open several new terminal windows. In each instance, the prompt will hang, waiting for more events to arrive. To continue studying the example, send more events through the input terminal prompt. Otherwise, you can Control-C to exit the process.

First, to consume the events of drama films, run the following:

confluent kafka topic consume drama-acting-events --from-beginning --value-format avro

This should yield the following messages:

{"name":"Meryl Streep","title":"The Iron Lady","genre":"drama"}
{"name":"Matt Damon","title":"The Martian","genre":"drama"}
{"name":"Russell Crowe","title":"Gladiator","genre":"drama"}

Second, to consume those from fantasy films, run the following:

confluent kafka topic consume fantasy-acting-events --from-beginning --value-format avro

This should yield the following messages:

{"name":"Judy Garland","title":"The Wizard of Oz","genre":"fantasy"}
{"name":"Bill Murray","title":"Ghostbusters","genre":"fantasy"}
{"name":"Laura Dern","title":"Jurassic Park","genre":"fantasy"}
{"name":"Keanu Reeves","title":"The Matrix","genre":"fantasy"}

And finally, to consume all the other genres, run the following:

 confluent kafka topic consume other-acting-events --from-beginning --value-format avro

This should yield the following messages:

{"name":"Will Smith","title":"Men in Black","genre":"comedy"}
{"name":"Jennifer Aniston","title":"Office Space","genre":"comedy"}
{"name":"Christian Bale","title":"The Dark Knight","genre":"crime"}
{"name":"Diane Keaton","title":"The Godfather: Part II","genre":"crime"}

Teardown Confluent Cloud resources


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


First, create a test file at configuration/

Write a test


Then, create a directory for the tests to live in:

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

Create the following test file at src/test/java/io/confluent/developer/

package io.confluent.developer;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

import io.confluent.developer.avro.ActingEvent;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroDeserializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

public class SplitStreamTest {

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

    public SpecificAvroSerializer<ActingEvent> makeSerializer(Properties allProps) {
        SpecificAvroSerializer<ActingEvent> serializer = new SpecificAvroSerializer<>();

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

        return serializer;

    public SpecificAvroDeserializer<ActingEvent> makeDeserializer(Properties allProps) {
        SpecificAvroDeserializer<ActingEvent> deserializer = new SpecificAvroDeserializer<>();

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

        return deserializer;

    private List<ActingEvent> readOutputTopic(TopologyTestDriver testDriver,
                                              String topic,
                                              Deserializer<String> keyDeserializer,
                                              SpecificAvroDeserializer<ActingEvent> valueDeserializer) {

        return testDriver
            .createOutputTopic(topic, keyDeserializer, valueDeserializer)
            .map(record -> record.value)

    public void testSplitStream() throws IOException {
        SplitStream ss = new SplitStream();
        Properties allProps = ss.loadEnvProperties(TEST_CONFIG_FILE);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);

        String inputTopic = allProps.getProperty("");
        String outputDramaTopic = allProps.getProperty("");
        String outputFantasyTopic = allProps.getProperty("");
        String outputOtherTopic = allProps.getProperty("");

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

        Serializer<String> keySerializer = Serdes.String().serializer();
        SpecificAvroSerializer<ActingEvent> valueSerializer = makeSerializer(allProps);

        Deserializer<String> keyDeserializer = Serdes.String().deserializer();
        SpecificAvroDeserializer<ActingEvent> valueDeserializer = makeDeserializer(allProps);

        ActingEvent streep = ActingEvent.newBuilder()
                .setName("Meryl Streep").setTitle("The Iron Lady").setGenre("drama").build();
        ActingEvent smith = ActingEvent.newBuilder()
                .setName("Will Smith").setTitle("Men in Black").setGenre("comedy").build();
        ActingEvent damon = ActingEvent.newBuilder()
                .setName("Matt Damon").setTitle("The Martian").setGenre("drama").build();
        ActingEvent garland = ActingEvent.newBuilder()
                .setName("Judy Garland").setTitle("The Wizard of Oz").setGenre("fantasy").build();
        ActingEvent aniston = ActingEvent.newBuilder()
                .setName("Jennifer Aniston").setTitle("Office Space").setGenre("comedy").build();
        ActingEvent murray = ActingEvent.newBuilder()
                .setName("Bill Murray").setTitle("Ghostbusters").setGenre("fantasy").build();
        ActingEvent bale = ActingEvent.newBuilder()
                .setName("Christian Bale").setTitle("The Dark Knight").setGenre("crime").build();
        ActingEvent dern = ActingEvent.newBuilder()
                .setName("Laura Dern").setTitle("Jurassic Park").setGenre("fantasy").build();
        ActingEvent reeves = ActingEvent.newBuilder()
                .setName("Keanu Reeves").setTitle("The Matrix").setGenre("fantasy").build();
        ActingEvent crowe = ActingEvent.newBuilder()
                .setName("Russell Crowe").setTitle("Gladiator").setGenre("drama").build();
        ActingEvent keaton = ActingEvent.newBuilder()
                .setName("Diane Keaton").setTitle("The Godfather: Part II").setGenre("crime").build();

        List<ActingEvent> input = new ArrayList<>();

        List<ActingEvent> expectedDrama = new ArrayList<>();

        List<ActingEvent> expectedFantasy = new ArrayList<>();

        List<ActingEvent> expectedOther = new ArrayList<>();

        final TestInputTopic<String, ActingEvent>
            actingEventTestInputTopic =
            testDriver.createInputTopic(inputTopic, keySerializer, valueSerializer);
        for (ActingEvent event : input) {
            actingEventTestInputTopic.pipeInput(event.getName(), event);

        List<ActingEvent> actualDrama = readOutputTopic(testDriver, outputDramaTopic, keyDeserializer, valueDeserializer);
        List<ActingEvent> actualFantasy = readOutputTopic(testDriver, outputFantasyTopic, keyDeserializer, valueDeserializer);
        List<ActingEvent> actualOther = readOutputTopic(testDriver, outputOtherTopic, keyDeserializer, valueDeserializer);

        Assert.assertEquals(expectedDrama, actualDrama);
        Assert.assertEquals(expectedFantasy, actualFantasy);
        Assert.assertEquals(expectedOther, actualOther);

    public void cleanup() {

Invoke the tests


Now run the test, which is as simple as:

./gradlew test

Take it to production

Create a production configuration file


First, create a new configuration file at configuration/ 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.
bootstrap.servers=<< FILL ME IN >>
schema.registry.url=<< FILL ME IN >>
input.topic.partitions=<< FILL ME IN >>
input.topic.replication.factor=<< FILL ME IN >>
output.drama.topic.partitions=<< FILL ME IN >>
output.drama.topic.replication.factor=<< FILL ME IN >>
output.fantasy.topic.partitions=<< FILL ME IN >>
output.fantasy.topic.replication.factor=<< FILL ME IN >>
output.other.topic.partitions=<< FILL ME IN >>
output.other.topic.replication.factor=<< FILL ME IN >>

Build a Docker image


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

gradle jibDockerBuild --image=io.confluent.developer/kstreams-split:0.0.1

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/ io.confluent.developer/kstreams-split:0.0.1