Advanced Operations & Best Practices

6 min read

Advanced Operations & Best Practices

Course: Apache Kafka
Topic ID: 12


👋 Introduction

Welcome. We have journeyed through the fundamentals of producers, consumers, and internal architecture. Now, we arrive at the operational capabilities required to run Apache Kafka in a production environment.

In a development environment, a single broker on a laptop suffices. In production, where data integrity and uptime are paramount, we must apply rigorous engineering standards. We will discuss sizing a cluster, handling catastrophic message failures, replicating data across the world, and the modern architecture of removing ZooKeeper.

Let us proceed with discipline and focus.


🧱 1. Capacity Planning: Sizing Your Kafka Cluster

The Definition & Problem

Capacity planning is the mathematical process of determining the hardware resources required to support your projected data load.
The Problem: If you underestimate storage, brokers crash when disks fill up. If you underestimate network bandwidth, latency spikes, and producers inadvertently block or time out. If you underestimate CPU, encryption and compression tasks stall the system.

The Concept: Throughput, Storage, and Replication

To size a cluster, you must isolate three variables: Ingest Rate (Write), Egress Rate (Read), and Retention Period.

1. Storage Calculation
Kafka persists data to disk. The formula is not simply "Data In." You must account for the Replication Factor (RF).

Total Storage=Daily Ingest×Retention Days×Replication Factor\text{Total Storage} = \text{Daily Ingest} \times \text{Retention Days} \times \text{Replication Factor}
  • Example: You ingest 1 TB/day. You want to keep data for 7 days. Your RF is 3 (standard high availability).1 TB×7×3=21 TB1 \text{ TB} \times 7 \times 3 = 21 \text{ TB}
  • Industry Practice: Always add a 20-30% buffer for rebalancing overhead and log compaction. Do not fill disks beyond 80%.

2. Throughput (Network & IOPS)
Kafka is I/O bound.

  • Network: If you write 100 MB/s, and you have 3 consumers reading that data, your total network load is:100 MB/s (Write)+(100 MB/s×3 Consumers)+Replication Traffic100 \text{ MB/s (Write)} + (100 \text{ MB/s} \times 3 \text{ Consumers}) + \text{Replication Traffic}
  • IOPS (Input/Output Operations Per Second): Modern Kafka relies heavily on the OS Page Cache. However, during "catch-up" reads (when a consumer is hours behind), Kafka must read from the disk, not the RAM. High-performance SSDs (NVMe) are recommended over HDDs for low-latency clusters.

🧠 Fact

LinkedIn, where Kafka was invented, handles over 7 trillion messages per day. If they hadn't calculated their capacity correctly, the professional networking world would likely come to a halt.


☠️ 2. Error Handling: Dead Letter Queues (DLQ) and Poison Pills

The Definition & Problem

In a perfect stream, every message is valid JSON/Avro/Protobuf. In reality, producers send corrupt data.
The Problem: A consumer attempts to deserialize a message. The deserializer crashes (throws an Exception). The consumer offset is not committed. The consumer restarts, reads the same message, and crashes again. This infinite loop is called a Poison Pill. It blocks all valid messages behind it.

The Concept: Dead Letter Queue (DLQ)

A Dead Letter Queue is a dedicated Kafka topic where "failed" messages are sent so that the main consumer processing can continue.

Mechanism:

  1. Consumer reads message A.
  2. Processing fails (deserialization error or business logic validation failure).
  3. Retry logic activates (optional).
  4. If retries are exhausted, the consumer publishes message A to the DLQ Topic (e.g., orders-dlq).
  5. Consumer commits the offset for message A in the original topic and moves to message B.

Implementation Strategy

You generally do not write this raw logic in try-catch blocks inside your business code. You use library support (like Spring Kafka or Kafka Streams).

Pattern: Non-Blocking Retries

  1. Main Topic: orders
  2. Retry Topic: orders-retry-1 (Consumer reads here with a delay).
  3. DLQ Topic: orders-dlt (Dead Letter Topic).

Example Configuration Concept (Spring Boot style):

yaml
spring:
  kafka:
    consumer:
      enable-auto-commit: false
    listener:
      # If processing fails, retry 3 times, then move to DLQ
      type: single
      ack-mode: record 

In the background, the DefaultErrorHandler catches the exception and uses a DeadLetterPublishingRecoverer to move the data.


🪞 3. Cross-Cluster Replication with MirrorMaker 2

The Definition & Problem

Enterprises often run Kafka clusters in multiple regions (e.g., AWS us-east-1 and AWS eu-west-1).
The Problem: If us-east-1 goes down due to a natural disaster, your data is lost or inaccessible. Alternatively, you may need to aggregate data from edge locations to a central analytics cluster. Standard consumers cannot easily sync entire clusters while preserving offsets.

The Concept: Geo-Replication

This is the process of mirroring data, topics, and configuration from a Source Cluster to a Target Cluster.

The Tool: MirrorMaker 2 (MM2)

The original MirrorMaker was a simple producer-consumer script with many flaws (rebalancing storms, lost offsets). MirrorMaker 2, built on the Kafka Connect framework, solves this.

Key Features of MM2:

  1. Active/Active replication: Both clusters can accept writes, and MM2 syncs them bidirectionally.
  2. Offset Sync: It translates offsets so that if a consumer moves from Source to Target, it resumes exactly where it left off.
  3. Topic Renaming: It creates topics like us-east.topicA in the target cluster to avoid cyclic loops.

Hands-on: Basic MM2 Configuration

MM2 runs as a Kafka Connect cluster. You create a configuration file mm2.properties.

properties
# Define clusters
clusters = source, target

# Connection details
source.bootstrap.servers = source-kafka:9092
target.bootstrap.servers = target-kafka:9092

# Enable replication flow
source->target.enabled = true
source->target.topics = .*  # Replicate all topics
target->source.enabled = true # Active-Active
target->source.topics = .*

# Do not replicate internal topics
source->target.topics.exclude = .*[\-\.]internal, .*\.replica, __consumer_offsets

Running MM2:

bash
./bin/connect-mirror-maker.sh mm2.properties

🚀 4. KRaft Migration: Moving Away from ZooKeeper

The Definition & Problem

Since its inception, Kafka relied on an external system called ZooKeeper to store metadata (who is the leader? which brokers are alive?).
The Problem:

  1. Complexity: You have to manage two distributed systems (Kafka + ZooKeeper).
  2. Scalability limits: ZooKeeper becomes a bottleneck when you have millions of partitions.
  3. Dual-Brain: Sometimes ZooKeeper thinks a broker is up, but the Kafka Controller thinks it is down.

The Concept: KRaft (Kafka Raft Metadata)

KRaft is the removal of ZooKeeper. Kafka now manages its own metadata using an internal Raft consensus algorithm.

  • Old Way: One broker is the "Controller" and talks to ZooKeeper.
  • New Way: A subset of brokers are designated as Voters (Controllers). They form a quorum. The metadata is stored in an internal topic called __cluster_metadata.

Hands-on: Setting up a KRaft Cluster (Latest Standard)

Note: As of Kafka 3.3+, KRaft is production-ready. ZooKeeper is deprecated.

Step 1: Generate a Cluster ID
You need a unique UUID for the cluster.

bash
./bin/kafka-storage.sh random-uuid
# Output example: 7C1-L300T_C4nn0t_B3_R34l

Step 2: Format Storage Directories
Instead of just starting the server, you must format the log directories with the ID (similar to formatting a hard drive).

bash
./bin/kafka-storage.sh format -t 7C1-L300T_C4nn0t_B3_R34l -c config/kraft/server.properties

Step 3: Start the Server
Point to the KRaft configuration, not the ZooKeeper one.

bash
./bin/kafka-server-start.sh config/kraft/server.properties

Configuration (server.properties snippet):

properties
process.roles=broker,controller
node.id=1
controller.quorum.voters=1@localhost:9093
  • process.roles: Defines if this node acts as a data broker, a metadata controller, or both (combined mode for dev/small clusters).

🧐 Fact

Moving to KRaft allows Kafka to support partitions in the millions per cluster, whereas ZooKeeper struggled around 200,000. It is one of the most significant architectural changes in Kafka's history.


📚 Further Reading & References

To deepen your operational expertise, please consult the following official resources:

  1. Ops Guide & Hardware: Apache Kafka Operations
  2. KRaft Architecture (KIP-500): Confluent - Kafka without ZooKeeper
  3. MirrorMaker 2 Guide: KIP-382 MirrorMaker 2.0
  4. Error Handling Patterns: Spring for Kafka - Error Handling

End of Topic 12. Proceed to the next module to verify your knowledge.

Challenge

You are a DevOps engineer responsible for setting up a cross-datacenter replication for Kafka using MirrorMaker 2. The goal is to establish an active-passive disaster recovery (DR) setup. You must create the complete mm2.properties configuration file based on the following requirements.

Scenario Details:

  • Primary Cluster (US):
    • Alias to be used in config: us-cluster
    • Bootstrap Servers: kafka-us-1:9092,kafka-us-2:9092
  • Disaster Recovery Cluster (EU):
    • Alias to be used in config: eu-cluster
    • Bootstrap Servers: kafka-eu-1:9092,kafka-eu-2:9092

Configuration Requirements:

  1. Define the connection properties for both the us-cluster and eu-cluster.
  2. Enable a one-way replication flow from us-cluster to eu-cluster.
  3. Ensure replication from eu-cluster back to us-cluster is disabled.
  4. The replication must include all topics that start with sales_ or inventory_.
  5. Explicitly exclude the topic sales_internal_testing from replication.
  6. Rely on MirrorMaker's default topic-renaming strategy (prefixing with the source cluster alias).

Expected result

The submitted configuration should be a syntactically correct .properties file that correctly configures MirrorMaker 2 for the specified scenario. A correct solution must include:

  • A clusters property defining both us-cluster and eu-cluster.
  • Correct bootstrap.servers configuration for both us-cluster and eu-cluster.
  • The property us-cluster->eu-cluster.enabled set to true.
  • A regex-based topics property for the us-cluster->eu-cluster flow that includes topics starting with sales_ or inventory_. For example: topics = "sales_.*|inventory_.*".
  • An topics.exclude property for the us-cluster->eu-cluster flow that explicitly blacklists the sales_internal_testing topic. For example: topics.exclude = "sales_internal_testing".
  • The replication flow eu-cluster->us-cluster.enabled should either be omitted (as false is the default) or explicitly set to false.
ini

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.