How to merge many streams into one stream


If I have many Kafka topics with events, how do I merge them all into a single topic?

Edit this page

Example use case:

Suppose that you have a set of Kafka topics representing songs being played of a particular genre. You might have a topic for rock songs, another for classical songs, and so forth. In this tutorial, we'll write a program that merges all of the song play events into a single topic.

Code example:

Short Answer

The input streams are combined using the merge function, which creates a new stream that represents all of the events of its inputs. The merged stream is forwarded to a combined topic via the to method, which accepts the topic as a parameter.

KStream<String, SongEvent> rockSongs =;
KStream<String, SongEvent> classicalSongs =;
KStream<String, SongEvent> allSongs = rockSongs.merge(classicalSongs);;

Try it

Initialize the project

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

mkdir merge-streams && cd merge-streams

Next, create a directory for configuration data:

mkdir configuration

Provision your fully managed Kafka cluster in Confluent Cloud

  1. Sign up for Confluent Cloud, a fully-managed Apache Kafka service.

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

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

  4. 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. 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/ 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 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.

Configure the project

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

buildscript {
    repositories {
    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 "" version "3.1.1"

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

repositories {

    maven {
        url ""

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.7.0"
    implementation "io.confluent:kafka-streams-avro-serde:6.1.1"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.7.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.MergeStreams"

shadowJar {
    archiveBaseName = "kstreams-merge-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/song_event.avsc for the events representing a song being played:

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "SongEvent",
  "fields": [
    {"name": "artist", "type": "string"},
    {"name": "title", "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. A stream is opened up for each input topic. The input streams are then combined using the merge function, which creates a new stream that represents all of the events of its inputs. Note that you can chain merge to combine as many streams as needed. The merged stream is then connected to the to method, which the name of a Kafka topic to send the events to.

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 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.SongEvent;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

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

public class MergeStreams {

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();

        final String rockTopic = allProps.getProperty("");
        final String classicalTopic = allProps.getProperty("");
        final String allGenresTopic = allProps.getProperty("");

        KStream<String, SongEvent> rockSongs =;
        KStream<String, SongEvent> classicalSongs =;
        KStream<String, SongEvent> allSongs = rockSongs.merge(classicalSongs);;

    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(


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

        MergeStreams ms = new MergeStreams();
        Properties allProps = ms.loadEnvProperties(args[0]);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
        allProps.put(SCHEMA_REGISTRY_URL_CONFIG, allProps.getProperty("schema.registry.url"));
        Topology topology = ms.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-merge-standalone-0.0.1.jar configuration/

Produce events to the input topics

To produce the input events to their respective topics, you’ll want two terminals running. To send the rock songs to their topic, open up a terminal and run the following:

ccloud kafka topic produce rock-song-events \
      --value-format avro \
      --schema src/main/avro/song_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:

{"artist": "Metallica", "title": "Fade to Black"}
{"artist": "Smashing Pumpkins", "title": "Today"}
{"artist": "Pink Floyd", "title": "Another Brick in the Wall"}
{"artist": "Van Halen", "title": "Jump"}
{"artist": "Led Zeppelin", "title": "Kashmir"}

To produce the classical songs, open up another terminal and run:

ccloud kafka topic produce classical-song-events \
    --value-format avro \
    --schema src/main/avro/song_event.avsc

Then paste in the following events:

{"artist": "Wolfgang Amadeus Mozart", "title": "The Magic Flute"}
{"artist": "Johann Pachelbel", "title": "Canon"}
{"artist": "Ludwig van Beethoven", "title": "Symphony No. 5"}
{"artist": "Edward Elgar", "title": "Pomp and Circumstance"}

Consume events from the output topic

Leaving your original terminals running, open another to consume the events that have been merged:

ccloud kafka topic consume all-song-events \
      --from-beginning \
      --value-format avro

After the consumer starts, you should see the following messages. The order might vary depending on the timing of which the input events are sent to each topic and processed by the app. Kafka Streams will coalesce the respective input topics together in an indeterminate manner. To continue studying the example, send more events through the input terminal prompt. Otherwise, you can Control-C to exit the process.

{"artist":"Metallica","title":"Fade to Black"}
{"artist":"Smashing Pumpkins","title":"Today"}
{"artist":"Pink Floyd","title":"Another Brick in the Wall"}
{"artist":"Van Halen","title":"Jump"}
{"artist":"Led Zeppelin","title":"Kashmir"}
{"artist":"Wolfgang Amadeus Mozart","title":"The Magic Flute"}
{"artist":"Johann Pachelbel","title":"Canon"}
{"artist":"Ludwig van Beethoven","title":"Symphony No. 5"}
{"artist":"Edward Elgar","title":"Pomp and Circumstance"}

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

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.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.Properties;

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

public class MergeStreamsTest {

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

    public SpecificAvroSerializer<SongEvent> makeSerializer(Properties allProps) {
        SpecificAvroSerializer<SongEvent> 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<SongEvent> makeDeserializer(Properties allProps) {
        SpecificAvroDeserializer<SongEvent> 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;

    public void testMergeStreams() throws IOException {
        MergeStreams ms = new MergeStreams();
        Properties allProps = ms.loadEnvProperties(TEST_CONFIG_FILE);

        String rockTopic = allProps.getProperty("");
        String classicalTopic = allProps.getProperty("");
        String allGenresTopic = allProps.getProperty("");

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

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

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

        List<SongEvent> rockSongs = new ArrayList<>();
        List<SongEvent> classicalSongs = new ArrayList<>();

        rockSongs.add(SongEvent.newBuilder().setArtist("Metallica").setTitle("Fade to Black").build());
        rockSongs.add(SongEvent.newBuilder().setArtist("Smashing Pumpkins").setTitle("Today").build());
        rockSongs.add(SongEvent.newBuilder().setArtist("Pink Floyd").setTitle("Another Brick in the Wall").build());
        rockSongs.add(SongEvent.newBuilder().setArtist("Van Halen").setTitle("Jump").build());
        rockSongs.add(SongEvent.newBuilder().setArtist("Led Zeppelin").setTitle("Kashmir").build());

        classicalSongs.add(SongEvent.newBuilder().setArtist("Wolfgang Amadeus Mozart").setTitle("The Magic Flute").build());
        classicalSongs.add(SongEvent.newBuilder().setArtist("Johann Pachelbel").setTitle("Canon").build());
        classicalSongs.add(SongEvent.newBuilder().setArtist("Ludwig van Beethoven").setTitle("Symphony No. 5").build());
        classicalSongs.add(SongEvent.newBuilder().setArtist("Edward Elgar").setTitle("Pomp and Circumstance").build());

        final TestInputTopic<String, SongEvent>
            rockSongsTestDriverTopic =
            testDriver.createInputTopic(rockTopic, keySerializer, valueSerializer);

        final TestInputTopic<String, SongEvent>
            classicRockSongsTestDriverTopic =
            testDriver.createInputTopic(classicalTopic, keySerializer, valueSerializer);

        for (SongEvent song : rockSongs) {
            rockSongsTestDriverTopic.pipeInput(song.getArtist(), song);

        for (SongEvent song : classicalSongs) {
            classicRockSongsTestDriverTopic.pipeInput(song.getArtist(), song);

        List<SongEvent> actualOutput =
                .createOutputTopic(allGenresTopic, keyDeserializer, valueDeserializer)
                .filter(record -> record.value != null)
                .map(record -> record.value)

        List<SongEvent> expectedOutput = new ArrayList<>();

        Assert.assertEquals(expectedOutput, actualOutput);

    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.rock.topic.partitions=<< FILL ME IN >>
input.rock.topic.replication.factor=<< FILL ME IN >>
input.classical.topic.partitions=<< FILL ME IN >>
input.classical.topic.replication.factor=<< FILL ME IN >>
output.topic.partitions=<< FILL ME IN >>
output.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:

./gradlew jibDockerBuild --image=io.confluent.developer/kstreams-merge: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-merge:0.0.1