How to find the min/max in a stream of events

Question:

How can you get the minimum or maximum value of a field from all records in a Kafka topic?

Edit this page

Example use case:

Suppose you have a topic with events that represent ticket sales of movies. In this tutorial, we'll write a program that calculates the maximum and minimum revenue of movies by year.

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 aggregate-minmax && cd aggregate-minmax

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: '2'
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
  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

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 "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"
}

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
version = "0.0.1"

repositories {
    mavenCentral()

    maven {
        url "https://packages.confluent.io/maven"
    }
}

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

mainClassName = "io.confluent.developer.AggregatingMinMax"

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"
    testImplementation "org.apache.kafka:kafka-streams-test-utils:3.4.0"
    testImplementation "junit:junit:4.13.2"
    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.AggregatingMinMax"
    )
  }
}

shadowJar {
    archiveBaseName = "kstreams-aggregating-minmax-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=aggregating-minmax-app
bootstrap.servers=127.0.0.1:29092
schema.registry.url=http://127.0.0.1:8081

input.topic.name=movie-ticket-sales
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=movie-figures-by-year
output.topic.partitions=1
output.topic.replication.factor=1

Create schemas for the events

5

Create a directory for the schemas that represent the events in the streaming topology:

mkdir -p src/main/avro

Then create the following Avro schema file at src/main/avro/movie-ticket-sales.avsc for the ticket sale events:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "MovieTicketSales",
  "fields": [
    {"name": "title", "type": "string"},
    {"name": "release_year", "type": "int"},
    {"name": "total_sales", "type": "int"}
  ]
}

Then create the following Avro schema file at src/main/avro/yearly-movie-figures.avsc for the movie box office figures events:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "YearlyMovieFigures",
  "fields": [
    {"name": "release_year", "type": "int"},
    {"name": "min_total_sales", "type": "int"},
    {"name": "max_total_sales", "type": "int"}
  ]
}

Because the Avro schemas are used in the Java code, we needs to compile them. Run the following:

./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/AggregatingMinMax.java.

package io.confluent.developer;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import io.confluent.developer.avro.MovieTicketSales;
import io.confluent.developer.avro.YearlyMovieFigures;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

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

public class AggregatingMinMax {

  public static Properties loadPropertiesFromConfigFile(String fileName) throws IOException {
    Properties envProps = new Properties();
    try (FileInputStream fileStream = new FileInputStream(fileName)) {
      envProps.load(fileStream);
    }
    return envProps;
  }

  public static 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(SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
    props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);

    return props;
  }

  public static SpecificAvroSerde<MovieTicketSales> ticketSaleSerde(final Properties envProps) {
    final SpecificAvroSerde<MovieTicketSales> serde = new SpecificAvroSerde<>();
    serde.configure(Collections.singletonMap(
        SCHEMA_REGISTRY_URL_CONFIG,
        envProps.getProperty("schema.registry.url")), false);
    return serde;
  }

  public static SpecificAvroSerde<YearlyMovieFigures> movieFiguresSerde(final Properties envProps) {
    final SpecificAvroSerde<YearlyMovieFigures> serde = new SpecificAvroSerde<>();
    serde.configure(Collections.singletonMap(
        SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url")
    ), false);
    return serde;
  }

  private static void createKafkaTopicsInCluster(final AdminClient adminClient, final Properties envProps) {
    adminClient.createTopics(Arrays.asList(
        new NewTopic(
            envProps.getProperty("input.topic.name"),
            Integer.parseInt(envProps.getProperty("input.topic.partitions")),
            Short.parseShort(envProps.getProperty("input.topic.replication.factor"))),
        new NewTopic(
            envProps.getProperty("output.topic.name"),
            Integer.parseInt(envProps.getProperty("output.topic.partitions")),
            Short.parseShort(envProps.getProperty("output.topic.replication.factor")))));
  }

  public static void runRecipe(final String configPath) throws IOException {

    Properties envProps = AggregatingMinMax.loadPropertiesFromConfigFile(configPath);

    try (AdminClient client = AdminClient.create(
        Collections.singletonMap("bootstrap.servers", envProps.getProperty("bootstrap.servers")))) {
      createKafkaTopicsInCluster(client, envProps);
    }

    Topology topology = AggregatingMinMax.buildTopology(
        new StreamsBuilder(),
        envProps,
        AggregatingMinMax.ticketSaleSerde(envProps),
        AggregatingMinMax.movieFiguresSerde(envProps));

    final KafkaStreams streams = new KafkaStreams(
        topology,
        AggregatingMinMax.buildStreamsProperties(envProps));
    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);

  }

  public static Topology buildTopology(final StreamsBuilder builder,
                                       final Properties envProps,
                                       final SpecificAvroSerde<MovieTicketSales> ticketSaleSerde,
                                       final SpecificAvroSerde<YearlyMovieFigures> movieFiguresSerde) {

    final String inputTopic = envProps.getProperty("input.topic.name");
    final String outputTopic = envProps.getProperty("output.topic.name");

    builder.stream(inputTopic, Consumed.with(Serdes.String(), ticketSaleSerde))
        .groupBy(
            (k, v) -> v.getReleaseYear(),
            Grouped.with(Serdes.Integer(), ticketSaleSerde))
        .aggregate(
            () -> new YearlyMovieFigures(0, Integer.MAX_VALUE, Integer.MIN_VALUE),
            ((key, value, aggregate) ->
                 new YearlyMovieFigures(key,
                                        Math.min(value.getTotalSales(), aggregate.getMinTotalSales()),
                                        Math.max(value.getTotalSales(), aggregate.getMaxTotalSales()))),
            Materialized.with(Serdes.Integer(), movieFiguresSerde))
        .toStream()
        .to(outputTopic, Produced.with(Serdes.Integer(), movieFiguresSerde));

    return builder.build();
  }

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

    runRecipe(args[0]);
  }

}

Let’s take a close look at the buildTopology() function, which uses the Kafka Streams DSL.

Using the StreamsBuilder parameter, which is the helper object that lets us build our topology, we can apply the following sequence of stages:

  1. Call the stream() function which creates a KStream<String, MovieTicketSales> object based on the stream of records from the inputTopic Kafka topic.

  2. Our use case requires we calculate minimum and maximum movie revenue by year. The groupBy function creates a KGroupedStream object. KGroupedStream represents a 'grouped record stream' which allows us to apply aggregations over the records, grouped by a the key. Here, we are specifying the movie’s year of release as the record value on which to group. Because you are changing the key, Kafka Streams automatically re-partitions the data.

  3. Next we apply the aggregate function which allows us to combine record values over time as well as change the type of the result records from the type of the input records. In our example we are aggregating MovieTicketSales records into the YearlyMovieFigures type by calculating a minimum and maximum value, grouped by release_year. The first parameter given to aggregate is an Initializer which is used for creating the initial value used in the first aggregation invocation. In our case, we are providing an instance of YearlyMovieFigures initialized with values that will make calculating minimum and maximums easy. The second parameter to the function is the aggregation logic. Here we calculate new minimum and maximums by comparing the incoming new MovieTicketSales record with the most recent aggregate value and we return a YearlyMovieFigures instance. This YearlyMovieFigures instance is the new aggregated value which will propagate downstream as well as be the value returned to us in the next invocation of aggregate. The final parameter to aggregate is a Materialized object which contains the Serdes required for (de)serializing records for the state store backing the aggregation.

  4. Finally the chain of functions, toStream().to(…​), produces the aggregated results to the specified output topic.

Compile and run the Kafka Streams program

7

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

Produce events to the input topic

8

In a new terminal, run:

docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic movie-ticket-sales --bootstrap-server broker:9092 --property value.schema="$(< src/main/avro/movie-ticket-sales.avsc)"

When the console producer starts, it may log some messages, and then pause waiting for your input. The input records below each represent an event. You can paste or type in one line at a time then press enter to send it. To send all of the events, paste all of the rows into the prompt and press enter:

{"title":"Avengers: Endgame","release_year":2019,"total_sales":856980506}
{"title":"Captain Marvel","release_year":2019,"total_sales":426829839}
{"title":"Toy Story 4","release_year":2019,"total_sales":401486230}
{"title":"The Lion King","release_year":2019,"total_sales":385082142}
{"title":"Black Panther","release_year":2018,"total_sales":700059566}
{"title":"Avengers: Infinity War","release_year":2018,"total_sales":678815482}
{"title":"Deadpool 2","release_year":2018,"total_sales":324512774}
{"title":"Beauty and the Beast","release_year":2017,"total_sales":517218368}
{"title":"Wonder Woman","release_year":2017,"total_sales":412563408}
{"title":"Star Wars Ep. VIII: The Last Jedi","release_year":2017,"total_sales":517218368}

Consume aggregated results from the output topic

9

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

docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic movie-figures-by-year --bootstrap-server broker:9092 --property schema.registry.url=http://schema-registry:8081 --from-beginning

After the consumer starts, you should see the following messages. Note that for every input record an output record is emitted. Each record represents an update to the aggregated values 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.

{"release_year":2019,"min_total_sales":856980506,"max_total_sales":856980506}
{"release_year":2019,"min_total_sales":426829839,"max_total_sales":856980506}
{"release_year":2019,"min_total_sales":401486230,"max_total_sales":856980506}
{"release_year":2019,"min_total_sales":385082142,"max_total_sales":856980506}
{"release_year":2018,"min_total_sales":700059566,"max_total_sales":700059566}
{"release_year":2018,"min_total_sales":678815482,"max_total_sales":700059566}
{"release_year":2018,"min_total_sales":324512774,"max_total_sales":700059566}
{"release_year":2017,"min_total_sales":517218368,"max_total_sales":517218368}
{"release_year":2017,"min_total_sales":412563408,"max_total_sales":517218368}
{"release_year":2017,"min_total_sales":412563408,"max_total_sales":517218368}

Test it

Create a test configuration file

1

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

application.id=aggregating-minmax-app
bootstrap.servers=127.0.0.1:29092
schema.registry.url=mock://127.0.0.1:8081

input.topic.name=movie-ticket-sales
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=movie-figures-by-year
output.topic.partitions=1
output.topic.replication.factor=1

Write a test

2

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/AggregatingMinMaxTest.java:

package io.confluent.developer;

import io.confluent.developer.avro.MovieTicketSales;
import io.confluent.developer.avro.YearlyMovieFigures;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.junit.Test;
import java.io.IOException;
import java.util.*;

import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertTrue;

public class AggregatingMinMaxTest {

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

  private static SpecificAvroSerde<MovieTicketSales> makeMovieTicketSalesSerializer(
          Properties envProps, SchemaRegistryClient srClient) {

    SpecificAvroSerde<MovieTicketSales> serde = new SpecificAvroSerde<>(srClient);
    serde.configure(Collections.singletonMap(
            "schema.registry.url", envProps.getProperty("schema.registry.url")), false);
    return serde;
  }
  private static SpecificAvroSerde<YearlyMovieFigures> makeYearlyMovieFiguresSerializer(
          Properties envProps, SchemaRegistryClient srClient) {

    SpecificAvroSerde<YearlyMovieFigures> serde = new SpecificAvroSerde<>(srClient);
    serde.configure(Collections.singletonMap(
            "schema.registry.url", envProps.getProperty("schema.registry.url")), false);
    return serde;
  }

  @Test
  public void shouldCountTicketSales() throws IOException {

    Properties envProps = AggregatingMinMax.loadPropertiesFromConfigFile(TEST_CONFIG_FILE);
    Properties streamProps = AggregatingMinMax.buildStreamsProperties(envProps);

    final MockSchemaRegistryClient srClient = new MockSchemaRegistryClient();

    String inputTopic = envProps.getProperty("input.topic.name");
    String outputTopic = envProps.getProperty("output.topic.name");

    final SpecificAvroSerde<MovieTicketSales> movieTicketSerdes =
            makeMovieTicketSalesSerializer(envProps, srClient);
    final SpecificAvroSerde<YearlyMovieFigures> yearlyFiguresSerdes =
            makeYearlyMovieFiguresSerializer(envProps, srClient);

    final StreamsBuilder builder = new StreamsBuilder();
    Topology topology = AggregatingMinMax.buildTopology(builder, envProps, movieTicketSerdes, yearlyFiguresSerdes);

    try (TopologyTestDriver testDriver = new TopologyTestDriver(topology, streamProps)) {

      TestInputTopic<String, MovieTicketSales> movieTicketSalesTestInputTopic = testDriver.createInputTopic(
              inputTopic, Serdes.String().serializer(), movieTicketSerdes.serializer());
      TestOutputTopic<Integer, YearlyMovieFigures> movieFiguresTestOutputTopic = testDriver.createOutputTopic(
              outputTopic, Serdes.Integer().deserializer(), yearlyFiguresSerdes.deserializer());

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Avengers: Endgame", 2019, 856980506));
      assertThat(
              movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2019, 856980506, 856980506))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Captain Marvel", 2019, 426829839));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2019, 426829839, 856980506))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Toy Story 4", 2019, 401486230));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2019, 401486230, 856980506))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("The Lion King", 2019, 385082142));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2019, 385082142, 856980506))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Black Panther", 2018, 700059566));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2018, 700059566,700059566))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Avengers: Infinity War", 2018, 678815482));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2018,678815482,700059566))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Deadpool 2", 2018,324512774));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2018,324512774,700059566))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Beauty and the Beast", 2017,517218368));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2017,517218368,517218368))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Wonder Woman", 2017,412563408));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2017,412563408,517218368))));

      movieTicketSalesTestInputTopic.pipeInput(
              new MovieTicketSales("Star Wars Ep. VIII: The Last Jedi", 2017,517218368));
      assertThat(movieFiguresTestOutputTopic.readValue(),
              is(equalTo(new YearlyMovieFigures(2017,412563408,517218368))));

      assertTrue(movieFiguresTestOutputTopic.isEmpty());
    }
  }
}

This test file uses the TestInputTopic and TestOutputTopic testing features introduced in Kafka 2.4. These features simplify testing including the ability to test inputs and outputs 'record-by-record', for example:

movieTicketSalesTestInputTopic.pipeInput(
  new MovieTicketSales("Avengers: Endgame", 2019, 856980506));
assertThat(
  movieFiguresTestOutputTopic.readValue(),
  is(equalTo(new YearlyMovieFigures(2019, 856980506, 856980506))));

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.