How to build an Apache Kafka ® producer application with callbacks

Question:

How can you use callbacks with a KafkaProducer to handle responses from the broker?

Edit this page

Example use case:

You have an application using an Apache Kafka producer, and you want an automatic way of handling responses after producing records. In this tutorial, you'll learn how to use the Callback interface to automatically handle responses from producing records.

Hands-on code example:

New to Confluent Cloud? Get started here.

Short Answer

Overload the KafkaProducer.send method with an instance of the Callback interface as the second parameter.

producer.send(producerRecord, (recordMetadata, exception) -> {
      if (exception == null) {
          System.out.println("Record written to offset " +
                  recordMetadata.offset() + " timestamp " +
                  recordMetadata.timestamp());
      } else {
          System.err.println("An error occurred");
          exception.printStackTrace(System.err);
      }
});

Run it

Initialize the project

1

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

mkdir kafka-producer-application-callback && cd kafka-producer-application-callback

Next, create a directory for configuration data:

mkdir configuration

Provision your Kafka cluster

2

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.

Take me to Confluent Cloud
  1. After you log in to Confluent Cloud, 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.

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

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

Confluent Cloud

Write the cluster information into a local file

3

From the Confluent Cloud Console, navigate to your Kafka cluster and then select Clients in the lefthand navigation. From the Clients view, create a new client and click Java to get the connection information customized to your cluster.

Create new credentials for your Kafka cluster and Schema Registry, writing in appropriate descriptions so that the keys are easy to find and delete later. The Confluent Cloud Console 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/ccloud.properties file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
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={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.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 set up the Confluent CLI

4

This tutorial has some steps for Kafka topic management and producing and consuming events, for which you can use the Confluent Cloud Console or the Confluent CLI. Follow the instructions here to install the Confluent CLI, and then follow these steps connect the CLI to your Confluent Cloud cluster.

Create a topic

5

In this step we’re going to create a topic for use during this tutorial.

Open a new terminal window and then run this command to create the topic that the producer can write to

confluent kafka topic create output-topic

Keep this terminal window open for later use when you run a console consumer to verify your producer application.

Configure the project

6

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

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

plugins {
    id "java"
    id "idea"
    id "eclipse"
}

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"

dependencies {
    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'
        }
      }
    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.KafkaProducerCallbackApplication"
    )
  }
}

shadowJar {
    archiveBaseName = "kafka-producer-application-callback-standalone"
    archiveClassifier = ''
}

Run the following command to obtain the Gradle wrapper:

gradle wrapper

Add application and producer properties

7

Then create a development file at configuration/dev.properties:

key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
acks=all

#Properties below this line are specific to code in this application
output.topic.name=output-topic

Let’s do a quick walkthrough of some of the producer properties.

key.serializer - The serializer the KafkaProducer will use to serialize the key.

value.serializer - The serializer the KafkaProducer will use to serialize the value.

acks - The KafkaProducer uses the acks configuration to tell the lead broker how many acknowledgment to wait for to consider a produce request complete. Acceptable values for acks are: 0, 1 (the default), -1, or all. Setting acks to -1 is the same as setting it to all.

  • acks=0: "fire and forget", once the producer sends the record batch it is considered successful

  • acks=1: leader broker added the records to its local log but didn’t wait for any acknowledgment from the followers

  • acks=all: highest data durability guarantee, the leader broker persisted the record to its log and received acknowledgment of replication from all in-sync replicas. When using acks=all, it’s strongly recommended to update min.insync.replicas as well.

This is only a small sub-set of producer configuration parameters. The full list of producer configuration parameters can be found in the Apache Kafka documentation.

Update the properties file with Confluent Cloud information

8

Using the command below, append the contents of configuration/ccloud.properties (with your Confluent Cloud configuration) to configuration/dev.properties (with the application properties).

cat configuration/ccloud.properties >> configuration/dev.properties

Create the KafkaProducer application

9

Create a directory for the Java files in this project:

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

Before you create your application file, let’s look at some of the key points of this program:

KafkaProducerCallbackApplication constructor
public class KafkaProducerCallbackApplication {

  private final Producer<String, String> producer;
  final String outTopic;

  public KafkaProducerCallbackApplication(final Producer<String, String> producer,  (1)
                                  final String topic) {                     (2)
    this.producer = producer;
    outTopic = topic;
  }
1 Passing in the Producer instance as a constructor parameter.
2 The topic to write records to

In this tutorial you’ll inject the dependencies in the KafkaProducerCallbackApplication.main() method. Having this thin wrapper class around a Producer is not required, but it does help with making our code easier to test. We’ll go into more details in the testing section of the tutorial.

(In practice you may want to use a dependency injection framework library, such as the Spring Framework).

Next let’s take a look at the KafkaProducerCallbackApplication.produce method

KafkaProducerCallbackApplication.produce
public void produce(final String message) {
    final String[] parts = message.split("-");  (1)
    final String key, value;
    if (parts.length > 1) {
      key = parts[0];
      value = parts[1];
    } else {
      key = "NO-KEY";
      value = parts[0];
    }
    final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(outTopic, key, value);  (2)
    producer.send(producerRecord, (recordMetadata, exception) -> {  (3)
              if (exception == null) {                          (4)
                  System.out.println("Record written to offset " +
                          recordMetadata.offset() + " timestamp " +
                          recordMetadata.timestamp());
              } else {
                  System.err.println("An error occurred"); (5)
                  exception.printStackTrace(System.err);
              }
        });
  }
1 Process the String for sending message
2 Create the ProducerRecord
3 Send the record to the broker specifying a Callback instance as a lambda function
4 If there’s no exceptions print the offset and timestamp of the acknowledged record
5 Error handling portion-in this case printing the stacktrace to System.err

The KafkaProducerCallbackApplication.produce method does some processing on a String, and then sends it as a ProducerRecord. While this code is a trivial example, it’s enough to show the example of using a KafkaProducer.

Notice that this overload of the KafkaProducer.send method accepts a second parameter, an instance of the Callback interface.

The Callback provides a way of handling any actions you want to take on request completion asynchronously. Note that the Callback code executes on the producer’s I/O thread and any time consuming tasks could cause a delay in sending new records, so any code here should be designed to execute quickly.

The KafkaProducer.send method is asynchronous and returns as soon as the provided record is placed in the buffer of records to be sent to the broker. Once the broker acknowledges that the record has been appended to its log, the broker completes the produce request, which the application receives as RecordMetadata—information about the committed message.

In this example, the code in the callback just prints information from each record’s RecordMetadata object, specifically the timestamp and offset.

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

package io.confluent.developer;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

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

public class KafkaProducerCallbackApplication {

    private final Producer<String, String> producer;
    final String outTopic;

    public KafkaProducerCallbackApplication(final Producer<String, String> producer,
                                    final String topic) {
        this.producer = producer;
        outTopic = topic;
    }

    public void produce(final String message) {
        final String[] parts = message.split("-");
        final String key, value;
        if (parts.length > 1) {
            key = parts[0];
            value = parts[1];
        } else {
            key = null;
            value = parts[0];
        }

        final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(outTopic, key, value);
        producer.send(producerRecord, (recordMetadata, exception) -> {
              if (exception == null) {
                  System.out.println("Record written to offset " +
                          recordMetadata.offset() + " timestamp " +
                          recordMetadata.timestamp());
              } else {
                  System.err.println("An error occurred");
                  exception.printStackTrace(System.err);
              }
        });
    }

    public void shutdown() {
        producer.close();
    }

    public static Properties loadProperties(String fileName) throws IOException {
        final Properties envProps = new Properties();
        final FileInputStream input = new FileInputStream(fileName);
        envProps.load(input);
        input.close();

        return envProps;
    }

    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            throw new IllegalArgumentException(
                    "This program takes two arguments: the path to an environment configuration file and" +
                            "the path to the file with records to send");
        }

        final Properties props = KafkaProducerCallbackApplication.loadProperties(args[0]);
        final String topic = props.getProperty("output.topic.name");
        final Producer<String, String> producer = new KafkaProducer<>(props);
        final KafkaProducerCallbackApplication producerApp = new KafkaProducerCallbackApplication(producer, topic);

        String filePath = args[1];
        try {
            List<String> linesToProduce = Files.readAllLines(Paths.get(filePath));
            linesToProduce.stream()
                          .filter(l -> !l.trim().isEmpty())
                          .forEach(producerApp::produce);
        } catch (IOException e) {
            System.err.printf("Error reading file %s due to %s %n", filePath, e);
        } finally {
           producerApp.shutdown();
        }
    }
}

Create data to produce to Kafka

10

Create the following file input.txt in the base directory of the tutorial. The numbers before the - will be the key and the part after will be the value.

1-value
2-words
3-All Streams
4-Lead to
5-Kafka
6-Go to
7-Kafka Summit
8-How can
9-a 10 ounce
10-bird carry a
11-5lb coconut

Compile and run the KafkaProducer application

11

In your terminal, run:

./gradlew shadowJar

Now that you have an uberjar for the KafkaProducerCallbackApplication, you can launch it locally.

java -jar build/libs/kafka-producer-application-callback-standalone-0.0.1.jar configuration/dev.properties input.txt

After you run the previous command, the application will process the file and you should something like this on the console:

Record written to offset 0 timestamp 1597352120029
Record written to offset 1 timestamp 1597352120037
Record written to offset 2 timestamp 1597352120037
Record written to offset 3 timestamp 1597352120037
Record written to offset 4 timestamp 1597352120037
Record written to offset 5 timestamp 1597352120037
Record written to offset 6 timestamp 1597352120037
Record written to offset 7 timestamp 1597352120037
Record written to offset 8 timestamp 1597352120037
Record written to offset 9 timestamp 1597352120037
Record written to offset 10 timestamp 1597352120038

Now you can experiment some by creating your own file in base directory and re-run the above command and substitute your file name for input.txt

Remember any data before the - is the key and data after is the value.

Confirm records sent by consuming from topic

12

Now run a console consumer that will read topics from the output topic to confirm your application published the expected records.

confluent kafka topic consume output-topic --print-key --delimiter " : " --from-beginning

The output from the consumer can vary if you added any of your own records, but it should look something like this:

1 : value
2 : words
3 : All Streams
4 : Lead to
5 : Kafka
6 : Go to
7 : Kafka Summit
8 : How can
9 : a 10 ounce
10 : bird carry a
11 : 5lb coconut

Now close the consumer with Ctrl-C then the broker shell with Ctrl-D.

Teardown Confluent Cloud resources

13

You may try another tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud Console or CLI to destroy all of the resources you created. Verify they are destroyed to avoid unexpected charges.

Test it

Create a test configuration file

1

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

key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
acks=all


#Properties below this line are specific to code in this application
output.topic.name=output-topic

Write a unit test

2

Create a directory for the tests to live in:

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

Next we will see why the thin wrapper class around the KafkaProducer makes testing easier. The KafkaProducerCallbackApplication accepts an instance of the Producer interface. The use of the interface allows us to inject any concrete type we want, including a Mock Producer for testing.

We use a MockProducer because you only want to test your own code. So you really only need to test that the producer receives the expected records and in the expected format. Plus since there is no broker, the tests run very fast, which becomes an important factor as the number of tests increase.

There is only one method in KafkaProducerCallbackApplicationTest annotated with @Test, and that is testProduce(). Before you create the test, let’s go over a few of the key points of the test

final List<String> records = Arrays.asList("foo#bar", "bar#foo", "baz#bar", "great-weather");

records.forEach(producerApp::produce); (1)

final List<KeyValue<String, String>> expectedList = Arrays.asList(KeyValue.pair("foo", "bar"),
            KeyValue.pair("bar", "foo"),
            KeyValue.pair("baz", "bar"),
            KeyValue.pair("NO-KEY","great:weather")); (2)
final List<KeyValue<String, String>> actualList = mockProducer.history().stream().map(this::toKeyValue).collect(Collectors.toList()); (3)
1 Call the produce method
2 Build the expected list of records the producer should receive
3 Use the MockProducer.history() method to get the records sent to the producer so the test can assert the expected records match the actual ones sent

Now create the following file at src/test/java/io/confluent/developer/KafkaProducerCallbackApplicationTest.java.

package io.confluent.developer;


import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.streams.KeyValue;
import org.junit.Test;


public class KafkaProducerCallbackApplicationTest {

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

    @Test
    public void testProduce() throws IOException {
        final StringSerializer stringSerializer = new StringSerializer();
        final MockProducer<String, String> mockProducer = new MockProducer<>(true, stringSerializer, stringSerializer);
        final Properties props = KafkaProducerCallbackApplication.loadProperties(TEST_CONFIG_FILE);
        final String topic = props.getProperty("output.topic.name");
        final KafkaProducerCallbackApplication producerApp = new KafkaProducerCallbackApplication(mockProducer, topic);
        final List<String> records = Arrays.asList("foo-bar", "bar-foo", "baz-bar", "great:weather");

        records.forEach(producerApp::produce);

        final List<KeyValue<String, String>> expectedList = Arrays.asList(KeyValue.pair("foo", "bar"),
            KeyValue.pair("bar", "foo"),
            KeyValue.pair("baz", "bar"),
            KeyValue.pair(null,"great:weather"));

        final List<KeyValue<String, String>> actualList = mockProducer.history().stream().map(this::toKeyValue).collect(Collectors.toList());

        assertThat(actualList, equalTo(expectedList));
        producerApp.shutdown();
    }


    private KeyValue<String, String> toKeyValue(final ProducerRecord<String, String> producerRecord) {
        return KeyValue.pair(producerRecord.key(), producerRecord.value());
    }
}

Invoke the tests

3

Now run the test, which is as simple as:

./gradlew test