How to sum a stream of events


How can I calculate the sum of one or more fields from all records in a Kafka topic?

Edit this page

Example use case:

Suppose you have a topic with events that represent ticket sales for movies. Each event contains the movie that the ticket was purchased for as well as its price. In this tutorial, we'll write a program that calculates the sum of all ticket sales per movie.

Hands-on code example:

New to Confluent Cloud? Sign up and run this tutorial for free.

Short Answer

Use the reduce() method to apply the sum aggregation, see below., Consumed.with(Serdes.String(), ticketSaleSerde))
        // Set key to title and value to ticket value
        .map((k, v) -> new KeyValue<>((String) v.getTitle(), v.getTicketTotalValue()))
        // Group by title
        .groupByKey(Grouped.with(Serdes.String(), Serdes.Integer()))
        // Apply SUM aggregation
        // Write to stream specified by outputTopic
        .toStream().mapValues(v -> v.toString() + " total sales").to(outputTopic, Produced.with(Serdes.String(), Serdes.String()));

Run it

Initialize the project

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

mkdir aggregate-sum && cd aggregate-sum

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. First, sign up for 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. 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 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.

The CLI clients for Confluent Cloud (ccloud) and Confluent Platform (confluent v1.0) have been unified into a single client Confluent CLI confluent v2.0. This tutorial uses the unified Confluent CLI confluent v2.0 (ccloud client will continue to work until sunset on May 9, 2022, and you can read the migration instructions to the unified confluent CLI at

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.8.1"
    implementation "io.confluent:kafka-streams-avro-serde:6.2.1"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:2.8.1"
    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.AggregatingSum"

shadowJar {
    archiveBaseName = "kstreams-aggregating-sum-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/ticket-sale.avsc for the ticket sale events:

  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "TicketSale",
  "fields": [
    {"name": "title", "type": "string"},
    {"name": "sale_ts", "type": "string"},
    {"name": "ticket_total_value", "type": "int"}

Because this Avro schema is used in the Java code, it needs 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/ Let’s take a close look at the buildTopology() method, which uses the Kafka Streams DSL.

The first thing the method does is create an instance of StreamsBuilder, which is the helper object that lets us build our topology. With our builder in hand, we can apply the following methods:

  1. Call the stream() method to create a KStream<String, TicketSale> object.

  2. Since we can’t make any assumptions about the key of this stream, we have to repartition it explicitly. We use the map() method for that, creating a new KeyValue instance for each record, using the movie title as the new key.

  3. Group the events by that new key by calling the groupByKey() method. This returns a KGroupedStream object.

  4. Use the reduce() method to apply the sum aggregation.

  5. Use the toStream() method to produce the sum results to the specified output topic.

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.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.Grouped;
import org.apache.kafka.streams.kstream.Produced;

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.time.Duration;

import io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.TicketSale;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

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

public class AggregatingSum {

  private SpecificAvroSerde<TicketSale> ticketSaleSerde(final Properties allProps) {
    final SpecificAvroSerde<TicketSale> serde = new SpecificAvroSerde<>();
    Map<String, String> config = (Map)allProps;
    serde.configure(config, false);
    return serde;

  public Topology buildTopology(Properties allProps,
                                final SpecificAvroSerde<TicketSale> ticketSaleSerde) {
    final StreamsBuilder builder = new StreamsBuilder();

    final String inputTopic = allProps.getProperty("");
    final String outputTopic = allProps.getProperty("");, Consumed.with(Serdes.String(), ticketSaleSerde))
        // Set key to title and value to ticket value
        .map((k, v) -> new KeyValue<>((String) v.getTitle(), v.getTicketTotalValue()))
        // Group by title
        .groupByKey(Grouped.with(Serdes.String(), Serdes.Integer()))
        // Apply SUM aggregation
        // Write to stream specified by outputTopic
        .toStream().mapValues(v -> v.toString() + " total sales").to(outputTopic, Produced.with(Serdes.String(), Serdes.String()));


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

    List<NewTopic> topics = new ArrayList<>();
    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 IOException {
    if (args.length < 1) {
      throw new IllegalArgumentException(
          "This program takes one argument: the path to an environment configuration file.");

    new AggregatingSum().runRecipe(args[0]);

  private void runRecipe(final String configPath) throws IOException {
    final Properties allProps = new Properties();
    try (InputStream inputStream = new FileInputStream(configPath)) {
    allProps.put(StreamsConfig.APPLICATION_ID_CONFIG, allProps.getProperty(""));
    allProps.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath());
    allProps.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);

    Topology topology = this.buildTopology(allProps, this.ticketSaleSerde(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-aggregating-sum-standalone-0.0.1.jar configuration/

Produce events to the input topic

In a new terminal window, run the following command to start a Confluent CLI producer:

confluent kafka topic produce movie-ticket-sales \
  --parse-key \
  --delimiter ":" \
  --value-format avro \
  --schema src/main/avro/ticket-sale.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:

"Die Hard":{"title":"Die Hard","sale_ts":"2019-07-18T10:00:00Z","ticket_total_value":12}
"Die Hard":{"title":"Die Hard","sale_ts":"2019-07-18T10:01:00Z","ticket_total_value":12}
"The Godfather":{"title":"The Godfather","sale_ts":"2019-07-18T10:01:31Z","ticket_total_value":12}
"Die Hard":{"title":"Die Hard","sale_ts":"2019-07-18T10:01:36Z","ticket_total_value":24}
"The Godfather":{"title":"The Godfather","sale_ts":"2019-07-18T10:02:00Z","ticket_total_value":18}
"The Big Lebowski":{"title":"The Big Lebowski","sale_ts":"2019-07-18T11:03:21Z","ticket_total_value":12}
"The Big Lebowski":{"title":"The Big Lebowski","sale_ts":"2019-07-18T11:03:50Z","ticket_total_value":12}
"The Godfather":{"title":"The Godfather","sale_ts":"2019-07-18T11:40:00Z","ticket_total_value":36}
"The Godfather":{"title":"The Godfather","sale_ts":"2019-07-18T11:40:09Z","ticket_total_value":18}

Enter Ctrl+C to exit.

Consume aggregated sum from the output topic

Leaving your original terminal running, open another to consume the events that have been filtered by your application:

confluent kafka topic consume movie-revenue -b --print-key

After the consumer starts, you should see the following messages. Note that for every key (movie), a sequence of output records (sum) is emitted. Each record represents an update to the sum, which is sent on every movie event specifically because caching is disabled in the code with StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG set to 0. Read more on Record caches in the DSL.

The consumer 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.

Die Hard	12 total sales
Die Hard	24 total sales
The Godfather	12 total sales
Die Hard	48 total sales
The Godfather	30 total sales
The Big Lebowski	12 total sales
The Big Lebowski	24 total sales
The Godfather	66 total sales
The Godfather	84 total sales

Enter Ctrl+C to exit.

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

import static java.util.Arrays.asList;

public class AggregatingSumTest {

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

  private SpecificAvroSerde<TicketSale> makeSerializer(Properties allProps) {
    SpecificAvroSerde<TicketSale> serde = new SpecificAvroSerde<>();

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

    return serde;

  public void shouldSumTicketSales() throws IOException {
    AggregatingSum aggSum = new AggregatingSum();
    Properties allProps = aggSum.loadEnvProperties(TEST_CONFIG_FILE);

    String inputTopic = allProps.getProperty("");
    String outputTopic = allProps.getProperty("");

    final SpecificAvroSerde<TicketSale> ticketSaleSpecificAvroSerde = makeSerializer(allProps);

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

    Serializer<String> keySerializer = Serdes.String().serializer();
    Deserializer<String> keyDeserializer = Serdes.String().deserializer();

    final TestInputTopic<String, TicketSale>
        testDriverInputTopic =
        testDriver.createInputTopic(inputTopic, keySerializer, ticketSaleSpecificAvroSerde.serializer());

    final List<TicketSale>
        input = asList(
                  new TicketSale("Die Hard", "2019-07-18T10:00:00Z", 12),
                  new TicketSale("Die Hard", "2019-07-18T10:01:00Z", 12),
                  new TicketSale("The Godfather", "2019-07-18T10:01:31Z", 12),
                  new TicketSale("Die Hard", "2019-07-18T10:01:36Z", 24),
                  new TicketSale("The Godfather", "2019-07-18T10:02:00Z", 18),
                  new TicketSale("The Big Lebowski", "2019-07-18T11:03:21Z", 12),
                  new TicketSale("The Big Lebowski", "2019-07-18T11:03:50Z", 12),
                  new TicketSale("The Godfather", "2019-07-18T11:40:00Z", 36),
                  new TicketSale("The Godfather", "2019-07-18T11:40:09Z", 18)

    List<String> expectedOutput = new ArrayList<>(Arrays.asList("12 total sales", "24 total sales", "12 total sales", "48 total sales", "30 total sales", "12 total sales", "24 total sales", "66 total sales", "84 total sales"));

    for (TicketSale ticketSale : input) {
      testDriverInputTopic.pipeInput("", ticketSale);

    List<String> actualOutput =
            .createOutputTopic(outputTopic, keyDeserializer, Serdes.String().deserializer())
            .map(record -> record.value.toString())

    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.topic.partitions=<< FILL ME IN >>
input.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:

gradle jibDockerBuild --image=io.confluent.developer/kstreams-aggregating-sum: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-aggregating-sum:0.0.1