Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 48

Kafka Command-Line Fundamentals

This lesson is built with resources from youtube.com, oso.sh and 1 more site.

Introduction

Hello! In our last lesson, we built a highly resilient consumer by implementing non-blocking retries and a Dead Letter Queue (DLQ). This ensures that a single "poison pill" message won't block our entire notification system. We saw in the logs how Spring Kafka automatically created retry topics and a DLQ topic, and how a failing message was eventually routed there.

But how can we be sure a message is in a topic without relying on application logs? What if our producer is misconfigured and sending to the wrong topic, or if our consumer's deserializer is silently failing? To truly debug a distributed messaging system, you need to go to the source of truth: the Kafka cluster itself.

In this lesson, you'll learn to use Kafka's built-in command-line interface (CLI) tools. These tools allow you to interact directly with the Kafka broker to inspect topics, manually produce messages, and consume them, giving you a powerful, low-level view for debugging.

This is the direct equivalent of using a database CLI like psql or mongo to query your data directly, bypassing the application layer. For a backend engineer, mastering these tools is a fundamental skill for troubleshooting production issues.


1. Getting Started with the Kafka CLI

The Kafka software distribution includes a set of shell scripts (usually in a bin/ directory) for administration and debugging. Since we are running Kafka in a Docker container, we need to execute these scripts from within that container.

Action: Access the Kafka Container

  1. Make sure your Docker environment is running with the Kafka container from our docker-compose.yml file.

  2. Open a new terminal and run the following command to get a shell inside the kafka container:

    docker-compose exec kafka bash
    

    Note: Depending on the terminal you use, you might see I have no name!@... as the prompt. This is normal.

  3. The Kafka CLI scripts are located in /opt/bitnami/kafka/bin. Navigate to this directory:

    cd /opt/bitnami/kafka/bin
    

You are now ready to interact with your Kafka cluster. Keep this terminal open, as we'll be using it throughout the lesson.

The following video provides an excellent hands-on tutorial for the commands we are about to use. We'll walk through them step-by-step, but this video is a great reference.

Apache Kafka® & Confluent Kafka CLI hands on tutorial | Producer & Consumer Flow | JavaTechie

This video from Java Techie demonstrates the complete end-to-end flow of using the Kafka CLI, from starting the server to producing and consuming messages. It's a great practical overview of what we'll be doing.

Watch the sections on managing topics (08:29 - 14:59) and the producer/consumer flow (14:59 - 22:40). Pay attention to the syntax of the commands for creating/listing topics and running the console producer and consumer. You can skip the part about starting Zookeeper/Kafka servers as Docker Compose handles that for us.


2. Inspecting Topics with kafka-topics.sh

Your first step when debugging is often to verify the state of your topics. Do they exist? How many partitions do they have?

Action: List and Describe Topics

Inside your Kafka container shell, run these commands:

  1. List all topics:

    ./kafka-topics.sh --bootstrap-server localhost:9092 --list
    

    You should see a list that includes user-registered-events from our auth-service, as well as the topics Spring Kafka automatically created: user-registered-events-retry-0, user-registered-events-retry-1, user-registered-events-retry-2, and user-registered-events-dlt.

  2. Describe a specific topic:

    ./kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic user-registered-events
    

    This command gives you detailed information about the user-registered-events topic. The output shows each partition, the Leader broker for that partition, the Replicas, and the Isr (In-Sync Replicas). In our single-broker setup, these will be simple, but in a multi-broker cluster, this view is critical for diagnosing cluster health.

For a quick reference of these and other commands, this article is a handy cheat sheet.

Apache Kafka CLI – Detailed Course

This DEV Community post provides a concise cheat sheet of the most common Kafka CLI commands. It's a great resource to bookmark.

Review the sections on 'Topic Management', 'Producing Messages', and 'Consuming Messages'. Note the common flags like --bootstrap-server (or --broker-list) and --topic.


3. Producing and Consuming Messages from the Console

Now for the core of debugging: manually sending and receiving messages.

Producing Messages with kafka-console-producer.sh

This tool lets you send messages to a topic directly from your terminal, which is perfect for testing a consumer in isolation without needing to run the producer service.

Action: Manually Trigger the Notification Service

  1. Start only the notifications-service Spring Boot application.

  2. In your Kafka container shell, start the console producer, targeting our main topic:

    ./kafka-console-producer.sh --bootstrap-server localhost:9092 --topic user-registered-events
    
  3. The command will hang, waiting for your input. Type the following JSON string on a single line and press Enter. This simulates the auth-service sending an event.

    {"userId": "cli-user-1", "username": "cli_user", "email": "cli@example.com"}
    
  4. Observe the notifications-service logs. You should see it immediately process this event: Received UserRegisteredEvent for user email: cli@example.com.

  5. Now, let's send a poison pill. In the same producer console, paste this line and press Enter:

    {"userId": "cli-user-2", "username": "poison_user", "email": "cli.failme@example.com"}
    
  6. Observe the logs again. You will see the error and the retry mechanism kick in. You have just triggered complex application logic from a simple command line!

Press Ctrl+C to exit the producer.

Consuming Messages with kafka-console-consumer.sh

This is arguably the most critical debugging tool. It lets you see exactly what's inside a topic, including messages that your application might be failing to process.

Action: Inspecting the Dead Letter Queue

Let's verify that the poison pill we just sent actually ended up in the DLQ.

  1. In your Kafka container shell, start a consumer listening to the DLQ topic. The --from-beginning flag tells it to read all messages in the topic, not just new ones.

    ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic user-registered-events-dlt --from-beginning
    
  2. You should immediately see the JSON payload for cli.failme@example.com printed to your console. This is irrefutable proof that the DLQ mechanism worked as designed.

Kafka Console Producer and Consumer Demonstration
This image shows a `kafka-console-consumer` actively reading messages from a topic, similar to what you are doing now. This is a fundamental technique for real-time message inspection.

4. Advanced Consumption for Deeper Debugging

Sometimes, just seeing the message value isn't enough. You might need to know which partition a message is in (to debug ordering issues) or what its key is. The kafka-console-consumer can be configured to show this.

This next video explains these advanced options clearly.

Kafka Console Consumer on Kafla CLI Tutorial

Stephane Maarek, a well-known Kafka expert, demonstrates how to format the console consumer's output to include valuable metadata like the partition number.

Watch from 03:35 to 06:27. This covers: Using the --from-beginning flag (which we've already used). Using a formatter to print the message key, value, and partition. How this detailed view helps you understand Kafka's per-partition ordering guarantee.

Action: View Message Metadata

Let's try this on our main topic. Run the following command in your Kafka container shell. It's long, so copy-pasting is recommended.

./kafka-console-consumer.sh --bootstrap-server localhost:9092 \
--topic user-registered-events \
--from-beginning \
--formatter kafka.tools.DefaultMessageFormatter \
--property print.partition=true \
--property print.value=true \
--property print.timestamp=true

The output now shows you the value of each message, the partition it belongs to, and its timestamp. This is incredibly useful. For example, if you send two messages for the same user and expect them to be processed in order, you can use this command to verify they both landed in the same partition.


5. Your Debugging Task: The Case of the Missing Message

Imagine this scenario: the auth-service team swears they are publishing a UserRegisteredEvent, but your notifications-service logs show nothing, and the user never gets a welcome email. The message seems to have vanished.

Your task is to use the CLI tools to determine what happened. One common cause of "missing" messages is a deserialization error. If the producer sends a malformed message, the Spring Kafka consumer might fail to convert the raw bytes into a UserRegisteredEvent object. By default, this can be a silent failure that doesn't even trigger our @RetryableTopic logic, because the error happens before our consume() method is even called. The message simply gets skipped.

Let's simulate and debug this.

  1. Start the notifications-service.
  2. Start the Console Producer: In your Kafka container shell, start the producer for the user-registered-events topic.
    ./kafka-console-producer.sh --bootstrap-server localhost:9092 --topic user-registered-events
    
  3. Send a Malformed Message: The UserRegisteredEvent expects a userId field. Let's send a message with a typo: userID (capital D).
    {"userID": "malformed-user-1", "username": "bad_json", "email": "bad@json.com"}
    
  4. Observe the notifications-service logs. You will likely see a DeserializationException error, and crucially, you won't see any of our custom "Poison pill received!" or retry logs. The message was discarded before our business logic was ever invoked.
  5. Confirm with the Console Consumer: How do you prove this message is what caused the problem?
    • Open a second Kafka container shell (docker-compose exec kafka bash).
    • In this new shell, run the console consumer on the user-registered-events topic:
      cd /opt/bitnami/kafka/bin
      ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic user-registered-events --from-beginning
      
    • In the output, you can now find the exact malformed message: {"userID": "malformed-user-1", ...}. You can now go back to the auth-service team with definitive proof of the malformed payload.

This workflow—observing an error, forming a hypothesis, and using the CLI to verify it—is a core part of a backend engineer's debugging toolkit.


6. A Glimpse at Better Tooling: kcat

The default CLI tools are powerful but can be verbose. The Kafka community has built more ergonomic tools. One of the most popular is kcat (formerly kafkacat). Think of it as a super-powered version of the console tools.

kcat makes it much easier to view message headers, which is something the default kafka-console-consumer struggles with. This is vital for inspecting the DLQ, as Spring Kafka adds the exception details into the message headers.

While we won't install it today, it's important to know it exists. If you were debugging our DLQ message, you could use a command like this with kcat:

kcat -C -b localhost:9092 -t user-registered-events-dlt -o beginning -f 'Headers: %h\nPayload: %s\n'

This would print the payload and all the headers, including the stack trace of the exception that caused the failure.

7 Must-Have CLI Tools Every Apache Kafka Engineer Should Know

For a look at the modern landscape of Kafka CLI tools, this article is an excellent guide. It introduces kcat and others that can significantly improve your productivity.

Read the sections on 'Tool #1: kcat – The Swiss Army Knife', the 'Daily Operations Matrix', and 'Tool Combination Strategies'. This will give you a sense of when and why you might reach for a tool like kcat over the default scripts.


Conclusion

In this lesson, you've gained a crucial, hands-on skill: using Kafka's command-line tools to debug the flow of messages directly. This ability to operate at a level below your application code is what separates a junior developer from a senior engineer who can confidently tackle production issues.

Key Takeaways:

  • You can access Kafka's CLI tools by executing a shell inside the running Docker container (docker-compose exec kafka bash).
  • kafka-topics.sh is used to –list and –describe topics, giving you a view of your cluster's structure.
  • kafka-console-producer.sh allows you to send messages manually, which is perfect for isolating and testing consumers.
  • kafka-console-consumer.sh is your primary tool for inspecting the raw contents of a topic, including the DLQ. The --from-beginning flag is essential for viewing historical messages.
  • Advanced formatters allow you to view message metadata like partitions, which is key for debugging ordering issues.
  • Tools like kcat exist to provide a more powerful and user-friendly CLI experience.

Preview of the Next Lesson:
This concludes our deep dive into Kafka and event-driven architecture. You've built a robust, resilient system. Now, we will take a step back and look at the overall architecture. Our application is currently a monolith. In the next module, we will begin the process of refactoring it into a microservices architecture, starting by defining clear service boundaries and introducing an API Gateway to route traffic.