How to combine stream aggregates together in a single larger object

Question:

How do I combine aggregate values like `count` from multiple streams into a single result?

Edit this page

Example use case:

You want to compute the count of user login events per application in your system, grouping the individual result from each source stream into one aggregated object. In this tutorial we'll cover how to use the Kafka Streams Cogrouping functionality to accomplish this task with clear, performant code

Code example:

Try it

1
Initialize the project

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

mkdir cogrouping-streams && cd cogrouping-streams

2
Get Confluent Platform

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

---
version: '2'

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

  broker:
    image: confluentinc/cp-kafka:6.0.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_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TOOLS_LOG4J_LOGLEVEL: ERROR

  schema-registry:
    image: confluentinc/cp-schema-registry:6.0.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'broker:9092'
      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.21.0"
        classpath "com.github.jengelman.gradle.plugins:shadow:4.0.2"
    }
}

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

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

repositories {
    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.10.0"
    implementation "org.slf4j:slf4j-simple:1.7.30"
    implementation "org.apache.kafka:kafka-streams:2.5.1"
    implementation "org.apache.kafka:kafka-clients:2.5.1"
    implementation "io.confluent:kafka-streams-avro-serde:5.5.1"

    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.5.1"
    testImplementation "junit:junit:4.13.1"
    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.CogroupingStreams"
    )
  }
}

shadowJar {
    archiveBaseName = "cogrouping-streams-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=cogrouping-streams
bootstrap.servers=localhost:29092
schema.registry.url=http://localhost:8081

app-one.topic.name=app-one-topic
app-one.topic.partitions=1
app-one.topic.replication.factor=1

app-two.topic.name=app-two-topic
app-two.topic.partitions=1
app-two.topic.replication.factor=1

app-three.topic.name=app-three-topic
app-three.topic.partitions=1
app-three.topic.replication.factor=1

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

4
Create a schema for the model obect

This tutorial uses 4 streams. The three input streams have a record type of LoginEvent used to represent a user logging into an application. The fourth stream is an output stream that writes a LoginRollup object out to a topic. In the next steps you’ll create the Avro schemas for these objects.

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/login-event.avsc to create the LoginEvent event:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "LoginEvent",
  "fields": [
    {"name": "app_id", "type": "string"},
    {"name": "user_id", "type": "string"},
    {"name": "time", "type": "long"}
  ]
}

Next create another schema file src/main/avro/login-rollup.avsc to create the LoginRollup for the cogrouping result:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "LoginRollup",
  "fields": [
    {"name": "login_by_app_and_user", "type": {
      "type": "map",
      "values": {
        "type": "map",
        "values": {"type": "long"}
      }
    }
    }
  ]
}

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

Before you create the Java class to run the Cogrouping example, let’s dive into the main point of this tutorial, how we use cogrouping:

    
        final Aggregator<String, LoginEvent, LoginRollup> loginAggregator = new LoginAggregator();

        final KGroupedStream<String, LoginEvent> appOneGrouped = appOneStream.groupByKey();
        final KGroupedStream<String, LoginEvent> appTwoGrouped = appTwoStream.groupByKey();
        final KGroupedStream<String, LoginEvent> appThreeGrouped = appThreeStream.groupByKey();

        appOneGrouped.cogroup(loginAggregator)
            .cogroup(appTwoGrouped, loginAggregator)
            .cogroup(appThreeGrouped, loginAggregator)
            .aggregate(() -> new LoginRollup(new HashMap<>()), Materialized.with(Serdes.String(), loginRollupSerde))
            .toStream().to(totalResultOutputTopic, Produced.with(stringSerde, loginRollupSerde));
    

You’re using the cogrouping functionality here to get an overall grouping of logins per application. Kafka Streams creates this total grouping by using an Aggregator who knows how to extract records from each grouped stream. Your Aggregator instance here knows how to correctly combine each LoginEvent into the larger LoginRollup object. You’ll learn more about Aggregator in the next step.

Next, you have three input streams: appOneStream, appTwoStream, and appThreeStream. You need the intermediate object KGroupedStream, so you execute the groupByKey() method on each stream. For this tutorial, we have assumed the incoming records already have keys. In cases where records lack keys, you need to use a key-selecting method (selectKey(), map(), or groupBy()) to successfully group by key.

Now with your KGroupedStream objects, you start creating your larger aggregate by calling KGroupedStream.cogroup() on the first stream, using your Aggregator. This first step returns a CogroupedKStream instance. Then for each remaining KGroupedStream, you execute CogroupedKSteam.cogroup() using one of the KGroupedStream instances and the Aggregator you created previously. You repeat this sequence of calls for all of the KGroupedStream objects you want to combine into an overall aggregate.

For more background on cogrouping functionality in stream you can read the KIP-150 proposal.

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

package io.confluent.developer;


import io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.LoginEvent;
import io.confluent.developer.avro.LoginRollup;
import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
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.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 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.Aggregator;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KGroupedStream;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;

public class CogroupingStreams {


	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(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
        props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 10 * 1024 * 1024);
        return props;
    }

    public Topology buildTopology(Properties envProps) {
        final StreamsBuilder builder = new StreamsBuilder();
            final String appOneInputTopic = envProps.getProperty("app-one.topic.name");
            final String appTwoInputTopic = envProps.getProperty("app-two.topic.name");
            final String appThreeInputTopic = envProps.getProperty("app-three.topic.name");
            final String totalResultOutputTopic = envProps.getProperty("output.topic.name");

        final Serde<String> stringSerde = getPrimitiveAvroSerde(envProps, true);
        final Serde<LoginEvent> loginEventSerde = getSpecificAvroSerde(envProps);
        final Serde<LoginRollup> loginRollupSerde = getSpecificAvroSerde(envProps);


        final KStream<String, LoginEvent> appOneStream = builder.stream(appOneInputTopic, Consumed.with(stringSerde, loginEventSerde));
        final KStream<String, LoginEvent> appTwoStream = builder.stream(appTwoInputTopic, Consumed.with(stringSerde, loginEventSerde));
        final KStream<String, LoginEvent> appThreeStream = builder.stream(appThreeInputTopic, Consumed.with(stringSerde, loginEventSerde));

        final Aggregator<String, LoginEvent, LoginRollup> loginAggregator = new LoginAggregator();

        final KGroupedStream<String, LoginEvent> appOneGrouped = appOneStream.groupByKey();
        final KGroupedStream<String, LoginEvent> appTwoGrouped = appTwoStream.groupByKey();
        final KGroupedStream<String, LoginEvent> appThreeGrouped = appThreeStream.groupByKey();

        appOneGrouped.cogroup(loginAggregator)
            .cogroup(appTwoGrouped, loginAggregator)
            .cogroup(appThreeGrouped, loginAggregator)
            .aggregate(() -> new LoginRollup(new HashMap<>()), Materialized.with(Serdes.String(), loginRollupSerde))
            .toStream().to(totalResultOutputTopic, Produced.with(stringSerde, loginRollupSerde));

        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(AbstractKafkaSchemaSerDeConfig.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(AbstractKafkaSchemaSerDeConfig.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("app-one.topic.name"),
                    Integer.parseInt(envProps.getProperty("app-one.topic.partitions")),
                    Short.parseShort(envProps.getProperty("app-one.topic.replication.factor"))));

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

            topics.add(new NewTopic(
                    envProps.getProperty("app-three.topic.name"),
                    Integer.parseInt(envProps.getProperty("app-three.topic.partitions")),
                    Short.parseShort(envProps.getProperty("app-three.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"))));

            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 CogroupingStreams instance = new CogroupingStreams();
        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
Implement a Cogrouping Aggregator

The Aggregator you saw in the previous step constructs a map of maps: the count of logins per user, per application. Below is the core logic of the LoginAggregator.

Each call to Aggregator.apply retrieves the user login map for the given application id (or creates one if it doesn’t exist). From there, the Aggregator increments the login count for the given user.

    
        final String userId = loginEvent.getUserId();
        final Map<String, Map<String, Long>> allLogins = loginRollup.getLoginByAppAndUser();
        final Map<String, Long> userLogins = allLogins.computeIfAbsent(appId, key -> new HashMap<>());
        userLogins.compute(userId, (k, v) -> v == null ? 1L : v + 1L);
    

While you could add the Aggregator instance as an in-line lambda to the topology, creating a separate class allows you to test the aggregator in isolation.

Next, create the following file at src/main/java/io/confluent/developer/LoginAggregator.java.

package io.confluent.developer;

import io.confluent.developer.avro.LoginEvent;
import io.confluent.developer.avro.LoginRollup;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.streams.kstream.Aggregator;

public class LoginAggregator implements Aggregator<String, LoginEvent, LoginRollup> {

  @Override
  public LoginRollup apply(final String appId,
                           final LoginEvent loginEvent,
                           final LoginRollup loginRollup) {
    final String userId = loginEvent.getUserId();
    final Map<String, Map<String, Long>> allLogins = loginRollup.getLoginByAppAndUser();
    final Map<String, Long> userLogins = allLogins.computeIfAbsent(appId, key -> new HashMap<>());
    userLogins.compute(userId, (k, v) -> v == null ? 1L : v + 1L);
    return loginRollup;
  }
}

7
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/cogrouping-streams-standalone-0.0.1.jar configuration/dev.properties

8
Produce sample data to the input topics

In a new terminal, run:

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

When the console producer starts, it will log some messages and hang, waiting for your input. Copy and paste one line at a time and press enter to send it. Note that these lines contain hard tabs between the key and the value, so retyping them without the tab will not work.

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:

"one":{"app_id":"one","user_id":"Ted", "time": 12456}
"one":{"app_id":"one","user_id":"Ted", "time": 12457}
"one":{"app_id":"one","user_id":"Carol", "time": 12458}
"one":{"app_id":"one","user_id":"Carol", "time": 12458}
"one":{"app_id":"one","user_id":"Alice", "time": 12458}
"one":{"app_id":"one","user_id":"Carol", "time": 12458}

After you’ve sent the records you can use CTRL+C to close this producer.

Using the same window, now run the following command to produce records to the second topic

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

To send all of the events below, paste the following into the prompt and press enter:

"two":{"app_id":"two","user_id":"Bob", "time": 12456}
"two":{"app_id":"two","user_id":"Carol", "time": 12457}
"two":{"app_id":"two","user_id":"Ted", "time": 12458}
"two":{"app_id":"two","user_id":"Carol", "time": 12459}

After you’ve sent the records you can use CTRL+C to close this producer.

Finally, using the same window run the following command to produce records to the third topic

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

To send all of the events below, paste the following into the prompt and press enter:

"three":{"app_id":"three","user_id":"Bob", "time": 12456}
"three":{"app_id":"three","user_id":"Alice", "time": 12457}
"three":{"app_id":"three","user_id":"Alice", "time": 12458}
"three":{"app_id":"three","user_id":"Carol", "time": 12459}

After you’ve sent the records you can use CTRL+C to close this producer.

9
Consume data from the output topic

Now that you have sent the login events, let’s run a consumer to read the cogrouped output from your streams application

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

You should see something like this

{"login_by_app_and_user":{"one":{"Carol":3,"Alice":1,"Ted":2}}}
{"login_by_app_and_user":{"two":{"Carol":2,"Bob":1,"Ted":1}}}
{"login_by_app_and_user":{"three":{"Carol":1,"Bob":1,"Alice":2}}}

Test it

1
Create a test configuration file

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

application.id=cogrouping-streams
bootstrap.servers=localhost:29092
schema.registry.url=mock://cogrouping-streams-test

app-one.topic.name=app-one-topic
app-one.topic.partitions=1
app-one.topic.replication.factor=1

app-two.topic.name=app-two-topic
app-two.topic.partitions=1
app-two.topic.replication.factor=1

app-three.topic.name=app-three-topic
app-three.topic.partitions=1
app-three.topic.replication.factor=1

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

2
Test the LoginAggregator class

Create a directory for the tests to live in:

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

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

This tests the Aggregator the Cogrouping operation uses. As I said previously, you can easily include an instance of the Aggregator in-line as a lambda in the original topology. But by having it as a stand alone class, you can easily test the Aggregator in a unit test.

package io.confluent.developer;


import org.junit.Test;

import java.util.HashMap;

import io.confluent.developer.avro.LoginEvent;
import io.confluent.developer.avro.LoginRollup;

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

public class LoginAggregatorTest {

  @Test
  public void shouldAggregateValues() {
    final LoginAggregator loginAggregator = new LoginAggregator();
    final LoginRollup loginRollup = new LoginRollup();
    loginRollup.setLoginByAppAndUser(new HashMap<>());

    final String appOne = "app-one";
    final String appTwo = "app-two";
    final String appThree = "app-three";

    final String user1 = "user1";
    final String user2 = "user2";

    loginAggregator.apply(appOne, login(appOne, user1), loginRollup);
    loginAggregator.apply(appTwo, login(appTwo, user1), loginRollup);
    loginAggregator.apply(appThree, login(appThree, user1), loginRollup);

    assertThat(loginRollup.getLoginByAppAndUser().get(appOne).get(user1), is(1L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appTwo).get(user1), is(1L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appThree).get(user1), is(1L));

    loginAggregator.apply(appOne, login(appOne, user1), loginRollup);
    loginAggregator.apply(appTwo, login(appTwo, user1), loginRollup);

    assertThat(loginRollup.getLoginByAppAndUser().get(appOne).get(user1), is(2L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appTwo).get(user1), is(2L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appThree).get(user1), is(1L));

    loginAggregator.apply(appOne, login(appOne, user2), loginRollup);
    loginAggregator.apply(appTwo, login(appTwo, user2), loginRollup);
    loginAggregator.apply(appThree, login(appThree, user2), loginRollup);

    loginAggregator.apply(appOne, login(appOne, user1), loginRollup);
    loginAggregator.apply(appTwo, login(appTwo, user1), loginRollup);
    loginAggregator.apply(appThree, login(appThree, user1), loginRollup);

    assertThat(loginRollup.getLoginByAppAndUser().get(appOne).get(user1), is(3L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appTwo).get(user1), is(3L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appThree).get(user1), is(2L));

    assertThat(loginRollup.getLoginByAppAndUser().get(appOne).get(user2), is(1L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appTwo).get(user2), is(1L));
    assertThat(loginRollup.getLoginByAppAndUser().get(appThree).get(user2), is(1L));

  }

  private LoginEvent login(String appId, String userId) {
       return new LoginEvent(appId, userId, System.currentTimeMillis());
  }
}

3
Test the Cogrouping Topology

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


import io.confluent.developer.avro.LoginEvent;
import io.confluent.developer.avro.LoginRollup;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
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 CogroupingStreamsTest {

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

    @Test
    public void cogroupingTest() throws IOException {
        final CogroupingStreams instance = new CogroupingStreams();
        final Properties envProps = instance.loadEnvProperties(TEST_CONFIG_FILE);

        final Properties streamProps = instance.buildStreamsProperties(envProps);

        final String appOneInputTopicName = envProps.getProperty("app-one.topic.name");
        final String appTwoInputTopicName = envProps.getProperty("app-two.topic.name");
        final String appThreeInputTopicName = envProps.getProperty("app-three.topic.name");
        final String totalResultOutputTopicName = envProps.getProperty("output.topic.name");

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

            final Serde<String> stringAvroSerde = CogroupingStreams.getPrimitiveAvroSerde(envProps, true);
            final SpecificAvroSerde<LoginEvent> loginEventSerde = CogroupingStreams.getSpecificAvroSerde(envProps);
            final SpecificAvroSerde<LoginRollup> rollupSerde = CogroupingStreams.getSpecificAvroSerde(envProps);

            final Serializer<String> keySerializer = stringAvroSerde.serializer();
            final Deserializer<String> keyDeserializer = stringAvroSerde.deserializer();
            final Serializer<LoginEvent> loginEventSerializer = loginEventSerde.serializer();


            final TestInputTopic<String, LoginEvent>  appOneInputTopic = testDriver.createInputTopic(appOneInputTopicName, keySerializer, loginEventSerializer);
            final TestInputTopic<String, LoginEvent>  appTwoInputTopic = testDriver.createInputTopic(appTwoInputTopicName, keySerializer, loginEventSerializer);
            final TestInputTopic<String, LoginEvent>  appThreeInputTopic = testDriver.createInputTopic(appThreeInputTopicName, keySerializer, loginEventSerializer);

            final TestOutputTopic<String, LoginRollup> outputTopic = testDriver.createOutputTopic(totalResultOutputTopicName, keyDeserializer, rollupSerde.deserializer());


            final List<LoginEvent> appOneEvents = new ArrayList<>();
            appOneEvents.add(LoginEvent.newBuilder().setAppId("one").setUserId("foo").setTime(5L).build());
            appOneEvents.add(LoginEvent.newBuilder().setAppId("one").setUserId("bar").setTime(6l).build());
            appOneEvents.add(LoginEvent.newBuilder().setAppId("one").setUserId("bar").setTime(7L).build());

            final List<LoginEvent> appTwoEvents = new ArrayList<>();
            appTwoEvents.add(LoginEvent.newBuilder().setAppId("two").setUserId("foo").setTime(5L).build());
            appTwoEvents.add(LoginEvent.newBuilder().setAppId("two").setUserId("foo").setTime(6l).build());
            appTwoEvents.add(LoginEvent.newBuilder().setAppId("two").setUserId("bar").setTime(7L).build());

            final List<LoginEvent> appThreeEvents = new ArrayList<>();
            appThreeEvents.add(LoginEvent.newBuilder().setAppId("three").setUserId("foo").setTime(5L).build());
            appThreeEvents.add(LoginEvent.newBuilder().setAppId("three").setUserId("foo").setTime(6l).build());
            appThreeEvents.add(LoginEvent.newBuilder().setAppId("three").setUserId("bar").setTime(7L).build());
            appThreeEvents.add(LoginEvent.newBuilder().setAppId("three").setUserId("bar").setTime(9L).build());

            final Map<String, Map<String, Long>> expectedEventRollups = new TreeMap<>();
            final Map<String, Long> expectedAppOneRollup = new HashMap<>();
            final LoginRollup expectedLoginRollup = new LoginRollup(expectedEventRollups);
            expectedAppOneRollup.put("foo", 1L);
            expectedAppOneRollup.put("bar", 2L);
            expectedEventRollups.put("one", expectedAppOneRollup);

            final Map<String, Long> expectedAppTwoRollup = new HashMap<>();
            expectedAppTwoRollup.put("foo", 2L);
            expectedAppTwoRollup.put("bar", 1L);
            expectedEventRollups.put("two", expectedAppTwoRollup);

            final Map<String, Long> expectedAppThreeRollup = new HashMap<>();
            expectedAppThreeRollup.put("foo", 2L);
            expectedAppThreeRollup.put("bar", 2L);
            expectedEventRollups.put("three", expectedAppThreeRollup);

            sendEvents(appOneEvents, appOneInputTopic);
            sendEvents(appTwoEvents, appTwoInputTopic);
            sendEvents(appThreeEvents, appThreeInputTopic);

            final List<LoginRollup> actualLoginEventResults = outputTopic.readValuesToList();
            final Map<String, Map<String, Long>> actualRollupMap = new HashMap<>();
            for (LoginRollup actualLoginEventResult : actualLoginEventResults) {
                  actualRollupMap.putAll(actualLoginEventResult.getLoginByAppAndUser());
            }
            final LoginRollup actualLoginRollup = new LoginRollup(actualRollupMap);

            assertEquals(expectedLoginRollup, actualLoginRollup);
        }
    }


    private void sendEvents(List<LoginEvent> events, TestInputTopic<String, LoginEvent> testInputTopic) {
        for (LoginEvent event : events) {
             testInputTopic.pipeInput(event.getAppId(), event);
        }
    }
}

4
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=cogrouping-streams
bootstrap.servers=<<FILL ME IN>>
schema.registry.url=<<FILL ME IN>>

app-one.topic.name=app-one-topic
app-one.topic.partitions=1
app-one.topic.replication.factor=1

app-two.topic.name=app-two-topic
app-two.topic.partitions=1
app-two.topic.replication.factor=1

app-three.topic.name=app-three-topic
app-three.topic.partitions=1
app-three.topic.replication.factor=1

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

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/cogrouping-streams-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/cogrouping-streams-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.