Learn Apache Kafka Β· 4/12

Consumers: Reading Data from Kafka

8 min read

Course: Apache Kafka

Topic: Consumers: Reading Data from Kafka

Welcome back, Kafka Engineer! πŸŽ“

In the previous modules, we learned how to act like a rockstar producer, blasting data into the Kafka universe. But data sitting in a broker is like an unread book on a shelfβ€”potential energy waiting to become kinetic.

Now, we switch sides. We are going to build Consumers. These are the applications that actually do something with the data (analytics, alerting, saving to DBs, or triggering emails).

Buckle up. We are about to enter the world of the Polling Loop. 🎒


1. Consumer Basics: The Polling Loop in Action

πŸ“ Definition & The Problem

Definition: A Kafka Consumer is a client application that subscribes to one or more topics and reads records (messages) from the Kafka brokers.

The Problem: In many messaging systems (like RabbitMQ or traditional JMS), the broker "pushes" messages to the client. If the client is slow or overwhelmed, the broker pushes harder, potentially crashing the client.

The Concept: Pull-Based Model
Kafka solves this by inverting control. Kafka is Pull-based. The broker is passive regarding data delivery; it just stores logs. The Consumer requests (polls) data when it is ready.

This prevents the "firehose" problem. If your consumer is processing heavy video files, it can poll, process for 10 seconds, and then poll again. It controls its own speed.

βš™οΈ The Mechanics: poll()

The heart of every consumer is the poll() loop. It's an infinite loop that constantly asks the broker: "Got anything new for me since offset X?"

πŸ‘¨β€πŸ’» Hands-On: The Basic Boilerplate (Java)

Here is the industry-standard setup using the Java client.

Prerequisites:
You need key.deserializer and value.deserializer. Since Kafka stores bytes, the consumer needs to know how to turn those bytes back into Objects (Strings, Integers, Avro, etc.).

java
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class SimpleConsumer {
    public static void main(String[] args) {
        // 1. Create Consumer Properties
        Properties properties = new Properties();
        properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "my-first-application");
        properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // "earliest" = read from beginning if no history exists

        // 2. Create the Consumer
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        // 3. Subscribe to a topic
        consumer.subscribe(Collections.singletonList("demo_topic"));

        // 4. The Polling Loop
        try {
            while (true) {
                // Poll for new data. Wait up to 100ms if no data is present immediately.
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));

                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("Key: " + record.key() + ", Value: " + record.value());
                    System.out.println("Partition: " + record.partition() + ", Offset: " + record.offset());
                }
            }
        } catch (Exception e) {
            // Handle logical errors
        } finally {
            consumer.close(); // Very important! Closes network connections and joins.
        }
    }
}

πŸ’‘ Industry Tip: The poll() method does two things:

  1. It fetches data.
  2. It sends a "heartbeat" to the broker, effectively saying, "I am still alive! Don't kill me!" If you take too long to process records between polls, the broker will assume you died.

2. Consumer Groups: Scaling Out Your Reads

πŸ“ Definition & The Problem

Definition: A Consumer Group is a set of consumers acting as a single logical unit to consume a topic. They share a group.id.

The Problem: Imagine you have a topic receiving 1,000,000 messages per second. Your single consumer (from step 1) takes 1ms to process a message. That consumer can only handle 1,000 messages/sec. You will lag behind hopelessly. You need to parallelize.

The Concept: Partition Assignment
This is the magic of Kafka scaling.

  • If a topic has 3 Partitions.
  • And you launch 3 Consumers in the same Group (group.id=my-app).
  • Kafka will automatically assign 1 Partition to 1 Consumer.

Each consumer reads a slice of the data in parallel. πŸš€

🧩 Scenarios (The Rules of Math)

Let's say we have Topic A with 3 Partitions.

  1. 1 Consumer in Group: It reads from Partitions 0, 1, and 2. (High load).
  2. 2 Consumers in Group: Consumer 1 gets Partitions 0, 1. Consumer 2 gets Partition 2. (Load shared).
  3. 3 Consumers in Group: Each gets exactly 1 partition. (Max efficiency).
  4. 4 Consumers in Group: 3 Consumers work. 1 Consumer is IDLE. πŸ›‘

Funny Fact: That 4th consumer is literally doing nothing. It’s the backup player sitting on the bench waiting for someone to get injured (crash). Kafka does not split one partition across multiple consumers in the same group.

Real Life Analogy:
Think of a checkout counter at a supermarket (The Topic). The lanes are Partitions. The Cashiers are Consumers.
If you have 3 lanes open, you can have 3 cashiers working simultaneously. If you hire a 4th cashier, they just stand there watching because there isn't a 4th lane.


3. Committing Offsets: Delivery Guarantees

πŸ“ Definition & The Problem

Definition: An Offset is a unique integer ID assigned to every message in a partition. Committing is the act of a consumer telling Kafka, "I have successfully processed up to offset 42. Next time I start, give me 43."

The Problem: Computers crash. If your consumer reads 10 messages, processes 5, and then the power goes out, what happens when it restarts? Does it re-read the 5 it finished? Does it skip the 5 it didn't finish?

The Concept: __consumer_offsets
Kafka stores committed offsets in a special internal topic called __consumer_offsets. It's like a bookmark.

βš”οΈ Delivery Semantics (The Big Debate)

There are two main ways to handle this, determining your reliability.

1. At-Most-Once (The Daredevil)

  • Behavior: You commit the offset as soon as you fetch the message, before you process it.
  • Risk: If your code crashes while processing, that message is lost forever. The bookmark says you read it.
  • Use Case: IoT sensor metrics where missing one temperature reading is okay. High speed, low reliability.

2. At-Least-Once (The Industry Standard)

  • Behavior: You read the message, process it (save to DB, send email), and then commit the offset.
  • Risk: If your code crashes after saving to the DB but before committing, you will restart and read that message again.
  • Result: You might process the same message twice (Duplicate).
  • Solution: Make your processing Idempotent (handling the same data twice doesn't break things).

πŸ›  Practical Implementation: Auto vs. Manual

A. Auto-Commit (Default, Easy, Dangerous)
By default enable.auto.commit=true.
Kafka commits for you every 5 seconds.

  • Danger: If you pull 100 records, process 10, and crash, Kafka might have already "auto-committed" all 100 because the timer went off. You lost 90 records.

B. Manual Commit (Pro Move)
Disable auto-commit and commit explicitly.

java
properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); // Turn off auto pilot

while (true) {
    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
    
    for (ConsumerRecord<String, String> record : records) {
        processRecord(record); // Your logic here
    }
    
    // Commit only after the batch is done
    try {
        consumer.commitSync(); 
    } catch (CommitFailedException e) {
        // Handle error
    }
}

4. Rebalances: Handling Join and Leave Events

πŸ“ Definition & The Problem

Definition: Rebalancing is the process where Kafka redistributes the partitions among the available consumers in a group.

The Problem: In a distributed system, things change.

  • You spin up a new container (Auto-scaling).
  • A container crashes (OOM Error).
  • A network glitch makes a consumer unreachable.

When this happens, partition ownership must change.

βš–οΈ The Concept: The Group Coordinator

One of the Kafka Brokers acts as the Group Coordinator. It monitors "Heartbeats". If a consumer stops heartbeating (default 3 seconds), the Coordinator declares it dead and triggers a Rebalance.

The "Stop-The-World" Effect (Eager Rebalancing):
Traditionally, when a rebalance starts, all consumers stop reading. They give up their partitions. The Coordinator reshuffles the deck and deals the partitions out again.

  • Impact: During this time, your application is completely paused. This is known as a "rebalance storm."

(Note: Newer Kafka versions use "Cooperative Sticky Assignors" to minimize this, but the concept of moving partitions remains).

πŸ›‘ Graceful Shutdown (Industry Best Practice)

You cannot just Ctrl+C a consumer in production. If you kill it abruptly, the Coordinator waits for the timeout (e.g., 10 seconds) before realizing it's gone. That's 10 seconds of processing lag.

You must handle the WakeupException.

The Pattern:

  1. Run the consumer in a separate thread.
  2. Use a Shutdown Hook to call consumer.wakeup().
  3. wakeup() causes the poll() loop to throw an exception immediately, allowing you to close cleanly.
java
// Shutdown Hook logic
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        consumer.wakeup(); // Trigger the exception
        try {
            mainThread.join(); // Wait for main thread to finish
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
});

try {
    while (true) {
        consumer.poll(Duration.ofMillis(100));
        // ... processing
    }
} catch (WakeupException e) {
    // Expected exception on shutdown. Ignore.
    System.out.println("Time to go home!");
} finally {
    consumer.close(); // Tells broker "I am leaving" IMMEDIATELY. No timeout needed.
    System.out.println("Consumer closed gracefully.");
}

Summary Checklist πŸ“

  1. Poll Loop: Kafka pushes nothing. You must pull (poll).
  2. Consumer Groups: 1 Partition = 1 Consumer. Add instances to scale, but never exceed partition count.
  3. Offsets: Use enable.auto.commit=false and commitSync() for data safety (At-Least-Once).
  4. Rebalances: Handle WakeupException to leave the group politely without freezing the system.

πŸ“š References & Further Reading

Now, go subscribe to some topics! But remember, with great power comes great responsibility (and occasional rebalances). πŸ•·οΈ

Challenge

Challenge: Implement a Robust Kafka Consumer with Manual Commits and Graceful Shutdown

You are tasked with building a Kafka consumer application in Java. This consumer must be robust, ensuring that data is processed reliably with at-least-once semantics and that it can shut down gracefully without causing unnecessary delays in the consumer group.

Your task is to complete the RobustKafkaConsumer class with the following requirements:

  1. Configure Consumer Properties:

    • Set the necessary properties: bootstrap.servers, group.id, key.deserializer, and value.deserializer.
    • Crucially, disable auto-committing by setting enable.auto.commit to false to take control of offset management.
  2. Implement the Polling Loop:

    • Subscribe the consumer to the topic named "important_events".
    • Create an infinite while (true) loop to continuously poll for records from Kafka.
    • Inside the loop, call consumer.poll() with a Duration of 1 second.
    • Iterate through the ConsumerRecords returned by poll() and for each record, log its key, value, partition, and offset. This simulates message processing.
  3. Ensure At-Least-Once Semantics:

    • After the inner loop that processes all records from a single poll, perform a synchronous manual commit by calling consumer.commitSync().
  4. Implement Graceful Shutdown:

    • Get a reference to the main thread before starting the consumer logic.
    • Register a JVM shutdown hook (Runtime.getRuntime().addShutdownHook).
    • Inside the shutdown hook, call consumer.wakeup(). This method is thread-safe and will throw a WakeupException from the poll() method, allowing the consumer to exit its loop cleanly.
    • Enclose the entire subscription and polling loop logic within a try...catch...finally block.
    • The catch block should specifically catch WakeupException to handle the shutdown signal. You can log a message here, but no other action is needed.
    • The finally block must call consumer.close() to ensure the consumer properly leaves the group and releases all resources, regardless of whether shutdown was normal or due to an error.

Expected result

The final code should be a single Java class named RobustKafkaConsumer that correctly implements a Kafka consumer. The solution must contain:

  1. A Properties object populated with the following configurations:

    • ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG set to "127.0.0.1:9092".
    • ConsumerConfig.GROUP_ID_CONFIG set to "my-robust-app".
    • ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG set to StringDeserializer.class.getName().
    • ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG set to StringDeserializer.class.getName().
    • ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG set to "false".
  2. A call to consumer.subscribe() with the specified topic.

  3. A Runtime.getRuntime().addShutdownHook block that creates a new Thread which calls consumer.wakeup().

  4. A while(true) loop containing:

    • A call to consumer.poll(Duration.ofMillis(1000)).
    • A for loop to iterate over the ConsumerRecords.
    • A System.out.println or logging statement inside the for loop to display record details.
    • A call to consumer.commitSync() after the for loop.
  5. A complete try...catch(WakeupException)...finally block where the finally clause contains a call to consumer.close().

java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.