How to build your first Apache KafkaProducer application

Question:

How do you get started building your first Kafka producer application?

Edit this page

Example use case:

You'd like to integrate a KafkaProducer into your event-driven application, but you're not sure where to start. In this tutorial, you'll build a small application that uses a KafkaProducer to write records to Kafka.

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

Make a local directory anywhere you’d like for this project:

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

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

Create a topic

4

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 open a shell on the broker docker container

docker exec broker bash

Next, create the topic that the producer can write to

kafka-topics --create --topic output-topic --bootstrap-server broker:9092 --replication-factor 1 --partitions 1

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

Configure the project

5

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-clients: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.KafkaProducerApplication"
    )
  }
}

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

Run the following command to obtain the Gradle wrapper:

gradle wrapper

Next, create a directory for configuration data:

mkdir configuration

Add application and producer properties

6

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

bootstrap.servers=localhost:29092

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
input.topic.name=input-topic
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 acknowledgments 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.

Create the KafkaProducer application

7

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:

KafkaProducerApplication constructor
public class KafkaProducerApplication {

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

  public KafkaProducerApplication(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 KafkaProducerApplication.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 KafkaProducerApplication.produce method

KafkaProducerApplication.produce
public Future<RecordMetadata> 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)
    return producer.send(producerRecord);                 (3)
  }
1 Process the String for sending message
2 Create the ProducerRecord
3 Send the record to the broker

The KafkaProducerApplication.produce method does some processing on a String, and then sends the ProducerRecord. While this code is a trivial example, it’s enough to show the example of using a KafkaProducer. Notice that KafkaProducer.send returns a Future with a type of RecordMetadata.

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. This tutorial prints the timestamp and offset for each record sent using the RecordMetadata object. Note that calling Future.get() for any record will block until the produce request completes.

Now go ahead and create the following file at src/main/java/io/confluent/developer/KafkaProducerApplication.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 org.apache.kafka.clients.producer.RecordMetadata;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class KafkaProducerApplication {

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

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

    public Future<RecordMetadata> 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);
        return producer.send(producerRecord);
    }

    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 void printMetadata(final Collection<Future<RecordMetadata>> metadata,
                              final String fileName) {
        System.out.println("Offsets and timestamps committed in batch from " + fileName);
        metadata.forEach(m -> {
            try {
                final RecordMetadata recordMetadata = m.get();
                System.out.println("Record written to offset " + recordMetadata.offset() + " timestamp " + recordMetadata.timestamp());
            } catch (InterruptedException | ExecutionException e) {
                if (e instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }
            }
        });
    }

    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 = KafkaProducerApplication.loadProperties(args[0]);
        final String topic = props.getProperty("output.topic.name");
        final Producer<String, String> producer = new KafkaProducer<>(props);
        final KafkaProducerApplication producerApp = new KafkaProducerApplication(producer, topic);

        String filePath = args[1];
        try {
            List<String> linesToProduce = Files.readAllLines(Paths.get(filePath));
            List<Future<RecordMetadata>> metadata = linesToProduce.stream()
                    .filter(l -> !l.trim().isEmpty())
                    .map(producerApp::produce)
                    .collect(Collectors.toList());
            producerApp.printMetadata(metadata, filePath);

        } 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

8

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

9

In your terminal, run:

./gradlew shadowJar

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

java -jar build/libs/kafka-producer-application-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:

Offsets and timestamps committed in batch from input.txt
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

10

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

kafka-console-consumer --topic output-topic \
 --bootstrap-server broker:9092 \
 --from-beginning \
 --property print.key=true \
 --property key.separator=" : "

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.

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
input.topic.name=input-topic
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 KafkaProducerApplication 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 KafkaProducerApplicationTest 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/KafkaProducerApplicationTest.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 KafkaProducerApplicationTest {

    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 = KafkaProducerApplication.loadProperties(TEST_CONFIG_FILE);
        final String topic = props.getProperty("output.topic.name");
        final KafkaProducerApplication producerApp = new KafkaProducerApplication(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

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.