Compute an average aggregation

Question:

How can you implement an average aggregation that implements incremental functions, namely `count()` and `sum()`?

Edit this page

Example use case:

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()`. Consider a topic with events that represent movie ratings. In this tutorial, we'll write a program that calculates and maintains a running average rating for each movie.

Hands-on code example:

Run it

Prerequisites

1

This tutorial installs Confluent Platform using Docker. Before proceeding:

  • • Install Docker Desktop (version 4.0.0 or later) or Docker Engine (version 19.03.0 or later) if you don’t already have it

  • • Install the Docker Compose plugin if you don’t already have it. This isn’t necessary if you have Docker Desktop since it includes Docker Compose.

  • • Start Docker if it’s not already running, either by starting Docker Desktop or, if you manage Docker Engine with systemd, via systemctl

  • • Verify that Docker is set up properly by ensuring no errors are output when you run docker info and docker compose version on the command line

Initialize the project

2

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

mkdir aggregating-average && cd aggregating-average

Get Confluent Platform

3

Next, create the following docker-compose.yml file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud):

version: '3.5'
services:
  broker:
    image: confluentinc/cp-kafka:7.4.1
    hostname: broker
    container_name: broker
    ports:
    - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER: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_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_NODE_ID: 1
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
      KAFKA_LISTENERS: PLAINTEXT://broker:9092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:29092
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
    networks:
    - cp
  schema-registry:
    image: confluentinc/cp-schema-registry:7.3.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
    networks:
    - cp
networks:
  cp:
    name: cp_network

And launch it by running:

docker compose up -d

Configure the project

4

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

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "gradle.plugin.com.github.jengelman.gradle.plugins:shadow:7.0.0"
  }
}

plugins {
  id "java"
  id "application"
  id "idea"
  id "eclipse"
  id "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"
}

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

repositories {
  mavenCentral()
  maven { url 'https://packages.confluent.io/maven/' }
}

apply plugin: "com.github.johnrengelman.shadow"

dependencies {
  implementation "org.apache.avro:avro:1.11.1"
  implementation "org.slf4j:slf4j-simple:2.0.7"
  implementation 'org.apache.kafka:kafka-streams:3.4.0'
  implementation ('org.apache.kafka:kafka-clients') {
    version {
        strictly '3.4.0'
    }
  }
  implementation "io.confluent:kafka-streams-avro-serde:7.3.0"
  implementation "com.typesafe:config:1.4.2"

  testImplementation "org.apache.kafka:kafka-streams-test-utils:3.4.0"
  testImplementation "junit:junit:4.13.2"
  testImplementation 'org.hamcrest:hamcrest:2.2'

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

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

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

shadowJar {
  archiveBaseName = "aggregating-average-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=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

Create a schema for the model object

5

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

Create the Kafka Streams topology

6

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.streams.serdes.avro.SpecificAvroSerde;

import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.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(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.STATESTORE_CACHE_MAX_BYTES_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;
  }

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

Compile and run the Kafka Streams program

7

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

Consume data from the output topic

8

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.

Produce sample data to the input topic

9

In a new terminal, run:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic ratings --bootstrap-server 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

Create a test configuration file

1

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=mock://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

Write a test

2

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.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.state.KeyValueStore;
import org.hamcrest.MatcherAssert;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Properties;

import io.confluent.demo.CountAndSum;
import io.confluent.demo.Rating;
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;

@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() {

    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", "mock://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();

    SpecificAvroSerde<CountAndSum> countAndSumSerde = RunningAverage.getCountAndSumSerde(mockProps);
    ratingSpecificAvroSerde = RunningAverage.getRatingSerde(mockProps);

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

    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);
    MatcherAssert.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();
  }
}

Invoke the tests

3

Now run the test, which is as simple as:

./gradlew test

Deploy on Confluent Cloud

Run your app with Confluent Cloud

1

Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully managed Apache Kafka service.

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

  2. After you log in to Confluent Cloud Console, click Environments in the lefthand navigation, 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). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.

  4. Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.

Confluent Cloud

Next, from the Confluent Cloud Console, click on Clients 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. In the case of this tutorial, add the following properties to the client application’s input properties file, substituting all curly braces with your Confluent Cloud values.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BROKER_ENDPOINT }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips

# Best practice for Kafka producer to prevent data loss
acks=all

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url=https://{{ SR_ENDPOINT }}
basic.auth.credentials.source=USER_INFO
schema.registry.basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}

Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.