Producers: Writing Data to Kafka

8 min read

Topic 3: Producers - Writing Data to Kafka

Welcome to the Producer module. In the previous sections, we established that Kafka is a distributed event streaming platform. Now, we must examine the origin of these streams.

A Producer is a client application responsible for publishing (writing) events to the Kafka cluster. While the concept seems trivial—sending data from point A to point B—the internal mechanics of the Kafka Producer are sophisticated. They are designed to handle high throughput, ensure data durability, and manage network instability without blocking your application.

This guide explores the lifecycle of a request, how to control where your data lives, and how to configure a producer that balances speed with safety.


1. The Anatomy of a Kafka Message and Producer Architecture

Definition

A Producer Record is the fundamental unit of data sent to Kafka. Before data travels over the network, the producer client library performs several transformation steps to ensure the message is valid, routable, and efficient.

The Problem

Simply sending raw bytes to a server is inefficient and unsafe.

  1. How does the server know how to store the data?
  2. How do we ensure related data stays together?
  3. How do we prevent the network from being overwhelmed by millions of tiny requests?

The Solution: The Producer Architecture

The Kafka Producer is not just a "sender." It is a complex library that manages buffers, threads, and metadata.

A. The Producer Record

When you create a record in code, it consists of the following components:

  • Topic (Required): The category/feed name.
  • Value (Required): The actual data payload (e.g., a JSON string, an Avro object).
  • Key (Optional): Used for partitioning (ordering).
  • Headers (Optional): Metadata key-value pairs (similar to HTTP headers) for tracing or routing.
  • Timestamp (Optional): Creation time or log append time.

B. The Workflow

When you call producer.send(record), the following happens internally before the message leaves your machine:

  1. serialization: The key and value are converted into byte arrays using configured Serializers (e.g., StringSerializer, ByteArraySerializer, KafkaAvroSerializer).
  2. Partitioning: The Partitioner determines which partition of the topic the message will go to. If a partition is specified in the record, it is used. If not, the partitioner calculates it.
  3. Accumulation (Batching): The message is not sent immediately. It is added to a RecordBatch in a memory buffer. Each partition has its own batch.
  4. The Sender Thread: A separate I/O thread runs in the background. It groups batches destined for the same Kafka Broker and sends them via TCP.

🧠 Interesting Fact: In early versions of Kafka, producers were "sync" by default, meaning the code waited for the message to be sent. Modern Kafka producers are asynchronous. When you call .send(), it returns immediately with a Future, and the actual network transmission happens in the background. This allows Kafka to handle millions of writes per second.


2. Message Routing: Keys, Hashes, and Custom Partitioners

Definition

Routing is the process of mapping a specific message to a specific partition ID within a topic.

The Problem

A topic is split into partitions (e.g., Partition 0, 1, 2) to scale storage and processing.

  • If we send all data to Partition 0, we create a "hot partition" and bottleneck the system.
  • If we scatter data randomly, a consumer reading Partition 0 might get "Update B" before "Update A," breaking the order of events.

The Solution: Partitioning Strategies

The decision of "Which partition?" depends entirely on the Key.

Scenario A: The Key is Null

If key=null, the producer distributes messages to balance the load.

  • Legacy Behavior (Round Robin): Message 1 -> P0, Message 2 -> P1, Message 3 -> P2.
  • Modern Behavior (Sticky Partitioner): To improve efficiency, the producer "sticks" to a specific partition for a short period (or until the batch is full), then switches. This results in fewer, larger requests, which reduces CPU load and latency.

Scenario B: The Key is Present

If a key is provided (e.g., user_id=1001), Kafka guarantees that all messages with the same key will go to the same partition.

  • Mechanism: targetPartition = murmur2_hash(key) % numPartitions
  • Why this matters: This guarantees ordering. If you are processing bank transactions, you need the "Debit" event to arrive before the "Credit" event for the same user. By hashing the User ID, both events land in Partition 5 (for example), ensuring they are read in order.

⚠️ Warning: If you change the number of partitions in a topic (e.g., scale from 10 to 20), the hash formula result changes. Old keys might land on new partitions, breaking ordering guarantees for existing data.


3. Acknowledgments (Acks): Balancing Speed and Durability

Definition

Acknowledgments (acks) control how many brokers must confirm receipt of a message before the producer considers the write successful.

The Problem

Distributed systems fail. A leader broker might crash milliseconds after receiving your message but before replicating it to other nodes.

  • If you continue sending, you lose data.
  • If you wait for everyone to confirm, the system becomes slow.

The Solution: The acks Configuration

You configure this setting based on the criticality of your data.

Acks Setting Description Durability Latency Use Case
acks=0 Producer sends and moves on. Does not wait for a response. None (High risk of data loss). Lowest. IoT sensor metrics, non-critical logs.
acks=1 Leader broker writes the record to its local log and responds. Medium (Safe unless Leader crashes immediately). Medium. Standard analytics, general logging.
acks=all (or -1) Leader waits for the full set of In-Sync Replicas (ISR) to acknowledge. Highest (No data loss if one replica survives). Highest. Financial transactions, audit trails.

🧪 Industry Standard: Since Kafka 3.0, the default is acks=all. The community decided that safety should be the default, and users should opt-in to riskier, faster settings if needed.


4. The Safe Producer: Retries, Idempotence, and Batching

Definition

A Safe Producer is a configuration set that ensures data is delivered exactly once and in the correct order, even in the presence of network glitches.

The Problem: The "At Least Once" Trap

Imagine acks=all. The Leader commits the message, but the network acknowledgment fails to reach the Producer.

  1. The Producer thinks the write failed.
  2. The Producer retries (sends the message again).
  3. The Broker receives the message again and writes it.
    Result: Duplicate data.

The Solution: Idempotence

Idempotence means that performing an operation multiple times has the same effect as performing it once.

When enable.idempotence=true:

  1. The Producer is assigned a unique ProducerID (PID) by the broker.
  2. Every message gets a monotonically increasing Sequence Number.
  3. If the Broker receives a message with a Sequence Number it has already committed from that PID, it silently discards the duplicate but returns an "OK" to the producer.

Result: Exactly-once semantics per partition.

Batching Configuration

To optimize the "Safe Producer" for high throughput, we tune how messages are grouped.

  • batch.size: The maximum size (in bytes) of a single batch. (Default: 16KB).
  • linger.ms: How long the producer waits to fill a batch before sending.
    • Analogy: Think of a bus. Does it leave the moment one passenger gets on (linger.ms=0), or does it wait 5 minutes to let the bus fill up (linger.ms=5)? Waiting slightly increases latency but drastically increases throughput and compression efficiency.

5. Hands-on: Implementing a Safe Producer (Java)

Java is the native language of Kafka. Below is a standard, production-grade setup.

Prerequisites

Ensure you have the client library.
Maven:

xml
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>3.7.0</version>
</dependency>

The Code

java
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;

public class HighSafetyProducer {
    public static void main(String[] args) {
        
        // 1. Create Producer Properties
        Properties props = new Properties();
        
        // Bootstrap Servers: Connection string
        props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        
        // Serializers: converting keys/values to bytes
        props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        
        // --- SAFE PRODUCER CONFIGURATION ---
        
        // Acks: Wait for all in-sync replicas
        props.setProperty(ProducerConfig.ACKS_CONFIG, "all");
        
        // Idempotence: Prevent duplicates (Defaults to true in Kafka 3.0+, explicit here for clarity)
        props.setProperty(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
        
        // Retries: Keep trying until delivery timeout
        props.setProperty(ProducerConfig.RETRIES_CONFIG, Integer.toString(Integer.MAX_VALUE));
        
        // --- HIGH THROUGHPUT TUNING ---
        
        // Compression: Snappy is a good balance of CPU vs Ratio
        props.setProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
        
        // Batch Size: Increase to 32KB (default 16KB)
        props.setProperty(ProducerConfig.BATCH_SIZE_CONFIG, Integer.toString(32 * 1024));
        
        // Linger: Wait 20ms to bundle messages
        props.setProperty(ProducerConfig.LINGER_MS_CONFIG, "20");

        // 2. Create the Producer
        KafkaProducer<String, String> producer = new KafkaProducer<>(props);

        // 3. Create a Data Record
        // Topic: "transactions", Key: "id_555", Value: JSON content
        String topic = "transactions";
        String key = "id_555";
        String value = "{ \"amount\": 500, \"currency\": \"USD\" }";
        
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);

        // 4. Send Data (Asynchronous)
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception e) {
                if (e == null) {
                    // Success
                    System.out.println("✅ Received new metadata. \n" +
                            "Topic: " + metadata.topic() + "\n" +
                            "Partition: " + metadata.partition() + "\n" +
                            "Offset: " + metadata.offset() + "\n" +
                            "Timestamp: " + metadata.timestamp());
                } else {
                    // Failure - typically logged for alerting
                    System.err.println("❌ Error while producing: " + e.getMessage());
                }
            }
        });

        // 5. Flush and Close
        // flush() forces all data in memory to be sent immediately
        producer.flush(); 
        
        // close() prevents resource leaks
        producer.close();
    }
}

Summary of Best Practices

  1. Always specify a Key if ordering matters.
  2. Use acks=all for systems where data loss is unacceptable.
  3. Use Compression (snappy or lz4) in production to reduce network load by up to 80%.
  4. Handle Exceptions: Always use the Callback inside .send() to catch authorization errors or non-retriable serialization issues.

📚 References & Further Reading

Challenge

You are designing a Kafka producer for a critical financial payments system. The system has three non-negotiable requirements:

  1. Maximum Durability: No transaction data can be lost, even in the event of a broker failure.
  2. Strict Ordering: All transactions for a single customer account must be processed in the exact order they are received.
  3. Exactly-Once Semantics: Network retries must not result in duplicate transaction processing.

Additionally, the system needs to be optimized for high throughput to handle peak loads.

Your task is to write the necessary code to configure this producer and send three sample transaction records.

Part 1: Producer Configuration

Complete the producerConfig object with the correct values to satisfy the system requirements. Focus on acknowledgments, idempotence, and performance tuning via batching and compression.

Part 2: Sending Records with Callbacks

Complete the producer.send() calls for the three provided transaction records. You must use a key to ensure ordering for transactions belonging to the same account. For each send operation, implement a callback function to handle the outcome. The callback should log an error if one occurs, or log the topic and partition from the metadata upon success.

Expected result

Your final code should contain a complete producerConfig object and three producer.send calls, each with a fully implemented callback function.

For producerConfig:

  • acks should be set to all to guarantee the write is acknowledged by the leader and all in-sync replicas.
  • enable.idempotence should be set to true to prevent duplicates from producer retries.
  • linger.ms should be set to 20 to optimize batching.
  • compression.type should be set to a common, efficient algorithm like snappy or lz4.

For producer.send calls:

  • Each call should correctly pass a transaction object and a callback function.
  • The callback function for each call must contain logic to check for an error object (err).
  • If err is not null, it should log an error message (e.g., console.error('Failed to send record:', err);).
  • If err is null, it should log a success message including the topic and partition from the metadata object (e.g., console.log('Record sent successfully to topic:', metadata.topic, 'partition:', metadata.partition);).
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.