Compute an average aggregation

Problem:

Kafka Streams natively supports "incremental" aggregation functions, in which the aggregation result is updated based on the values captured by each window. Incremental functions include count, sum, min, and max. An average aggregation cannot be computed incrementally. However, as this tutorial shows, it can be implemented by composing incremental functions, namely count and sum.

Edit this page

Example use case:

Consider a topic with events that represent ratings of movies. In this tutorial, we'll write a program that calculates and maintains a running average rating for each movie.

Code example:

Try it

1
Initialize the project

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

mkdir aggregating-average && cd aggregating-average

2
Get Confluent Platform

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

---
version: '3.5'

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

  broker:
    image: confluentinc/cp-enterprise-kafka:5.4.1
    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
      KAFKA_TOOLS_LOG4J_LOGLEVEL: ERROR
      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'
    networks:
      - cp

  schema-registry:
    image: confluentinc/cp-schema-registry:5.4.1
    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
    networks:
      - cp

networks:
  cp:
    name: cp_network

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 "application"
  id "com.google.cloud.tools.jib" version "1.1.1"
  id "idea"
  id "eclipse"
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"
version = "0.0.1"
mainClassName = "io.confluent.developer.RunningAverage"

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.8.2"
  implementation "org.slf4j:slf4j-simple:1.7.26"
  implementation "org.apache.kafka:kafka-streams:2.4.0"
  implementation "io.confluent:kafka-streams-avro-serde:5.4.1"
  implementation "com.typesafe:config:1.4.0"

  testImplementation "org.apache.kafka:kafka-streams-test-utils:2.4.1"
  testImplementation "junit:junit:4.12"
  testImplementation 'org.hamcrest:hamcrest:2.2'

  testCompileOnly "org.projectlombok:lombok:1.18.12"
  testAnnotationProcessor "org.projectlombok:lombok:1.18.12"
}

test {
  testLogging {
    outputs.upToDateWhen { false }
    showStandardStreams = true
    exceptionFormat = "full"
  }
}

jar {
  manifest {
    attributes(
        "Class-Path": configurations.runtime.collect { it.getName() }.join(" "),
        "Main-Class": mainClassName
    )
  }
}

shadowJar {
  archiveFileName = "aggregating-average-standalone-$version.$extension"
}

jib {
  container {
    mainClass = mainClassName
    jvmFlags =["-Dconfig.file=/prod.properties"]
  }

  extraDirectory = file("${rootDir.getPath()}/configuration")
}

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=kafka-films
request.timeout.ms=20000
bootstrap.servers=localhost\:29092
retry.backoff.ms=500
schema.registry.url=http://localhost:8081

default.topic.replication.factor=1
offset.reset.policy=latest

input.ratings.topic.name=ratings
input.ratings.topic.partitions=1
input.ratings.topic.replication.factor=1

# avro output topics
output.rating-averages.topic.name=rating-averages
output.rating-averages.topic.partitions=1
output.rating-averages.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

Create an Avro schema file at src/main/avro/rating.avsc for the stream of ratings:

{
  "namespace": "io.confluent.demo",
  "type": "record",
  "name": "Rating",
  "fields": [
    {
      "name": "movie_id",
      "type": "long"
    },
    {
      "name": "rating",
      "type": "double"
    }
  ]
}

Next, create an Avro schema file at src/main/avro/countsum.avsc for the pair of counts and sums:

{
  "namespace": "io.confluent.demo",
  "type": "record",
  "name": "CountAndSum",
  "fields": [
    {
      "name": "count",
      "type": "long"
    },
    {
      "name": "sum",
      "type": "double"
    }
  ]
}

Note: We’re going to use this record to store intermediate results. The reason why we’re using avro schema for this is that we can use SpecificAvroSerde to handle all our serialization needs.

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

Then create the following file at src/main/java/io/confluent/developer/RunningAverage.java. Let’s take a close look at the buildTopology() method, which uses the Kafka Streams DSL.

package io.confluent.developer;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
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.KGroupedStream;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;

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 java.util.stream.Stream;

import io.confluent.demo.CountAndSum;
import io.confluent.demo.Rating;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

import static io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
import static java.lang.Integer.parseInt;
import static java.lang.Short.parseShort;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toMap;
import static org.apache.kafka.common.serialization.Serdes.Double;
import static org.apache.kafka.common.serialization.Serdes.Long;
import static org.apache.kafka.streams.StreamsConfig.APPLICATION_ID_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.REPLICATION_FACTOR_CONFIG;
import static org.apache.kafka.streams.kstream.Grouped.with;

public class RunningAverage {

  //region buildStreamsProperties
  protected Properties buildStreamsProperties(Properties envProps) {
    Properties config = new Properties();
    config.putAll(envProps);

    config.put(APPLICATION_ID_CONFIG, envProps.getProperty("application.id"));
    config.put(BOOTSTRAP_SERVERS_CONFIG, envProps.getProperty("bootstrap.servers"));
    config.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, Long().getClass());
    config.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, Double().getClass());
    config.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));

    config.put(REPLICATION_FACTOR_CONFIG, envProps.getProperty("default.topic.replication.factor"));
    config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, envProps.getProperty("offset.reset.policy"));

    config.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);

    return config;
  }
  //endregion

  //region createTopics

  /**
   * Create topics using AdminClient API
   */
  private void createTopics(Properties envProps) {
    Map<String, Object> config = new HashMap<>();

    config.put("bootstrap.servers", envProps.getProperty("bootstrap.servers"));
    AdminClient client = AdminClient.create(config);

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

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

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

    client.createTopics(topics);
    client.close();

  }
  //endregion

  private void run() {

    Properties envProps = this.loadEnvProperties();
    Properties streamProps = this.buildStreamsProperties(envProps);
    Topology topology = this.buildTopology(new StreamsBuilder(), envProps);

    this.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.cleanUp();
      streams.start();
      latch.await();
    } catch (Throwable e) {
      System.exit(1);
    }
    System.exit(0);
  }

  protected static KTable<Long, Double> getRatingAverageTable(KStream<Long, Rating> ratings,
                                                              String avgRatingsTopicName,
                                                              SpecificAvroSerde<CountAndSum> countAndSumSerde) {

    // Grouping Ratings
    KGroupedStream<Long, Double> ratingsById = ratings
        .map((key, rating) -> new KeyValue<>(rating.getMovieId(), rating.getRating()))
        .groupByKey(with(Long(), Double()));

    final KTable<Long, CountAndSum> ratingCountAndSum =
        ratingsById.aggregate(() -> new CountAndSum(0L, 0.0),
                              (key, value, aggregate) -> {
                                aggregate.setCount(aggregate.getCount() + 1);
                                aggregate.setSum(aggregate.getSum() + value);
                                return aggregate;
                              },
                              Materialized.with(Long(), countAndSumSerde));

    final KTable<Long, Double> ratingAverage =
        ratingCountAndSum.mapValues(value -> value.getSum() / value.getCount(),
                                    Materialized.as("average-ratings"));

    // persist the result in topic
    ratingAverage.toStream().to(avgRatingsTopicName);
    return ratingAverage;
  }

  //region buildTopology
  private Topology buildTopology(StreamsBuilder bldr,
                                 Properties envProps) {

    final String ratingTopicName = envProps.getProperty("input.ratings.topic.name");
    final String avgRatingsTopicName = envProps.getProperty("output.rating-averages.topic.name");

    KStream<Long, Rating> ratingStream = bldr.stream(ratingTopicName,
                                                     Consumed.with(Serdes.Long(), getRatingSerde(envProps)));

    getRatingAverageTable(ratingStream, avgRatingsTopicName, getCountAndSumSerde(envProps));

    // finish the topology
    return bldr.build();
  }
  //endregion

  public static SpecificAvroSerde<CountAndSum> getCountAndSumSerde(Properties envProps) {
    SpecificAvroSerde<CountAndSum> serde = new SpecificAvroSerde<>();
    serde.configure(getSerdeConfig(envProps), false);
    return serde;
  }

  public static SpecificAvroSerde<Rating> getRatingSerde(Properties envProps) {
    SpecificAvroSerde<Rating> serde = new SpecificAvroSerde<>();
    serde.configure(getSerdeConfig(envProps), false);
    return serde;
  }

  protected static Map<String, String> getSerdeConfig(Properties config) {
    final HashMap<String, String> map = new HashMap<>();

    final String srUrlConfig = config.getProperty(SCHEMA_REGISTRY_URL_CONFIG);
    map.put(SCHEMA_REGISTRY_URL_CONFIG, ofNullable(srUrlConfig).orElse(""));
    return map;
  }

  private Properties loadEnvProperties() {
    final Config load = ConfigFactory.load();
    final Map<String, Object> map = load.entrySet()
        .stream()
        // ignore java.* and system properties
        .filter(entry -> Stream
            .of("java", "user", "sun", "os", "http", "ftp", "line", "file", "awt", "gopher", "socks", "path")
            .noneMatch(s -> entry.getKey().startsWith(s)))
        .peek(
            filteredEntry -> System.out.println(filteredEntry.getKey() + " : " + filteredEntry.getValue().unwrapped()))
        .collect(toMap(Map.Entry::getKey, y -> y.getValue().unwrapped()));
    Properties props = new Properties();
    props.putAll(map);
    return props;
  }

  public static void main(String[] args) {
    new RunningAverage().run();
  }
}

Please note the code snippet around line 134. To calculate the running average, we need to capture the sum of ratings and counts as part of the same aggregating operation.

Compute count and sum in a single aggregation step and emit <count,sum> tuple as aggregation result values.
final KTable<Long, CountAndSum> ratingCountAndSum =
        ratingsById.aggregate(() -> new CountAndSum(0L, 0.0),
                              (key, value, aggregate) -> {
                                aggregate.setCount(aggregate.getCount() + 1);
                                aggregate.setSum(aggregate.getSum() + value);
                                return aggregate;
                              },
                              Materialized.with(Long(), countAndSumSerde));
Compute average for each tuple.
final KTable<Long, Double> ratingAverage =
        ratingCountAndSum.mapValues(value -> value.getSum() / value.getCount(),
                                    Materialized.as("average-ratings"));

This pattern can also be applied to compute a windowed average or to compose other functions.

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 -Dconfig.file=configuration/dev.properties -jar build/libs/aggregating-average-standalone-0.0.1.jar

7
Consume data from the output topic

Before you start producing ratings, it’s a good idea to set up the consumer on the output topic. This way, as soon as you produce data you can see the results as they are output.

docker exec -it broker /usr/bin/kafka-console-consumer --topic rating-averages --bootstrap-server broker:9092 \
  --property "print.key=true"\
  --property "key.deserializer=org.apache.kafka.common.serialization.LongDeserializer" \
  --property "value.deserializer=org.apache.kafka.common.serialization.DoubleDeserializer" \
  --from-beginning

You won’t see any results until the next step.

8
Produce sample data to the input topic

In a new terminal, run:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic ratings --broker-list broker:9092\
  --property "parse.key=false"\
  --property "key.separator=:"\
  --property value.schema="$(< src/main/avro/rating.avsc)"

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:

{"movie_id":362,"rating":10}
{"movie_id":362,"rating":8}

Test it

1
Create a test configuration file

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

application.id=kafka-films
request.timeout.ms=20000
bootstrap.servers=localhost\:29092
retry.backoff.ms=500
schema.registry.url=http://localhost:8081

default.topic.replication.factor=1
offset.reset.policy=latest

input.ratings.topic.name=ratings
input.ratings.topic.partitions=1
input.ratings.topic.replication.factor=1

# avro output topics
output.rating-averages.topic.name=rating-averages
output.rating-averages.topic.partitions=1
output.rating-averages.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/RunningAverageTest.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 a validateAverageRating() method in RunningAverageTest annotated with @Test. This method actually runs our Streams topology using the TopologyTestDriver and some mocked data that is set up inside the test method.

package io.confluent.developer;

import org.apache.kafka.common.serialization.DoubleDeserializer;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
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.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.state.KeyValueStore;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import io.confluent.demo.CountAndSum;
import io.confluent.demo.Rating;
import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import lombok.extern.slf4j.Slf4j;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

@Slf4j
public class RunningAverageTest {

  private static final String RATINGS_TOPIC_NAME = "ratings";
  private static final String AVERAGE_RATINGS_TOPIC_NAME = "average-ratings";
  private static final Rating LETHAL_WEAPON_RATING_10 = new Rating(362L, 10.0);
  private static final Rating LETHAL_WEAPON_RATING_8 = new Rating(362L, 8.0);

  private TopologyTestDriver testDriver;
  private SpecificAvroSerde<Rating> ratingSpecificAvroSerde;

  @Before
  public void setUp() throws IOException, RestClientException {

    final Properties mockProps = new Properties();
    mockProps.put("application.id", "kafka-movies-test");
    mockProps.put("bootstrap.servers", "DUMMY_KAFKA_CONFLUENT_CLOUD_9092");
    mockProps.put("schema.registry.url", "DUMMY_SR_CONFLUENT_CLOUD_8080");
    mockProps.put("default.topic.replication.factor", "1");
    mockProps.put("offset.reset.policy", "latest");
    mockProps.put("specific.avro.reader", true);

    final RunningAverage streamsApp = new RunningAverage();
    final Properties streamsConfig = streamsApp.buildStreamsProperties(mockProps);

    StreamsBuilder builder = new StreamsBuilder();

    // workaround https://stackoverflow.com/a/50933452/27563
    final String tempDirectory = Files.createTempDirectory("kafka-streams")
        .toAbsolutePath()
        .toString();
    streamsConfig.setProperty(StreamsConfig.STATE_DIR_CONFIG, tempDirectory);

    final Map<String, String> mockSerdeConfig = RunningAverage.getSerdeConfig(streamsConfig);

    SpecificAvroSerde<CountAndSum> countAndSumSerde = new SpecificAvroSerde<>(new MockSchemaRegistryClient());
    countAndSumSerde.configure(mockSerdeConfig, false);

    // MockSchemaRegistryClient doesn't require connection to Schema Registry which is perfect for unit test
    final MockSchemaRegistryClient client = new MockSchemaRegistryClient();
    ratingSpecificAvroSerde = new SpecificAvroSerde<>(client);
    client.register(RATINGS_TOPIC_NAME + "-value", Rating.SCHEMA$);
    ratingSpecificAvroSerde.configure(mockSerdeConfig, false);

    KStream<Long, Rating> ratingStream = builder.stream(RATINGS_TOPIC_NAME,
                                                        Consumed.with(Serdes.Long(), ratingSpecificAvroSerde));

    final KTable<Long, Double> ratingAverageTable = RunningAverage.getRatingAverageTable(ratingStream,
                                                                                         AVERAGE_RATINGS_TOPIC_NAME,
                                                                                         countAndSumSerde);

    final Topology topology = builder.build();
    testDriver = new TopologyTestDriver(topology, streamsConfig);

  }

  @Test
  public void validateIfTestDriverCreated() {
    assertNotNull(testDriver);
  }

  @Test
  public void validateAverageRating() {

    TestInputTopic<Long, Rating> inputTopic = testDriver.createInputTopic(RATINGS_TOPIC_NAME,
                                                                          new LongSerializer(),
                                                                          ratingSpecificAvroSerde.serializer());

    inputTopic.pipeKeyValueList(asList(
        new KeyValue<>(LETHAL_WEAPON_RATING_8.getMovieId(), LETHAL_WEAPON_RATING_8),
        new KeyValue<>(LETHAL_WEAPON_RATING_10.getMovieId(), LETHAL_WEAPON_RATING_10)
    ));

    final TestOutputTopic<Long, Double> outputTopic = testDriver.createOutputTopic(AVERAGE_RATINGS_TOPIC_NAME,
                                                                                   new LongDeserializer(),
                                                                                   new DoubleDeserializer());

    final List<KeyValue<Long, Double>> keyValues = outputTopic.readKeyValuesToList();
    // I sent two records to input topic
    // I expect second record in topic will contain correct result
    final KeyValue<Long, Double> longDoubleKeyValue = keyValues.get(1);
    System.out.println("longDoubleKeyValue = " + longDoubleKeyValue);
    assertThat(longDoubleKeyValue,
               equalTo(new KeyValue<>(362L, 9.0)));

    final KeyValueStore<Long, Double>
        keyValueStore =
        testDriver.getKeyValueStore("average-ratings");
    final Double expected = keyValueStore.get(362L);
    Assert.assertEquals("Message", expected, 9.0, 0.0);
  }

  @After
  public void tearDown() {
    testDriver.close();
  }
}

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=kafka-films
request.timeout.ms=20000
bootstrap.servers=broker:9092
retry.backoff.ms=500
schema.registry.url=http://schema-registry:8081

default.topic.replication.factor=1
offset.reset.policy=latest

input.ratings.topic.name=ratings
input.ratings.topic.partitions=1
input.ratings.topic.replication.factor=1

# avro output topics
output.rating-averages.topic.name=rating-averages
output.rating-averages.topic.partitions=1
output.rating-averages.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/aggregating-average: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:/prod.properties io.confluent.developer/aggregating-average:0.0.1

# run with network
docker run -v $PWD/configuration/prod.properties:/prod.properties --network cp_network io.confluent.developer/aggregating-average:0.0.1