Kafka Cluster Architecture & Internals
8 min read
Kafka Cluster Architecture & Internals
Welcome to the deep dive into the internal mechanics of Apache Kafka. In previous sections, you likely learned how to produce and consume messages. Now, we must understand the engine itself.
To operate Kafka effectively in production, one must look beyond the API and understand the distributed systems theory that powers it. We will examine how brokers communicate, how data is replicated, and how the cluster maintains consensus.
1. Cluster Architecture: How Brokers Work Together
Definition
A Kafka Broker is a single Kafka server. It receives messages from producers, assigns them offsets, and commits them to storage on disk. It also services fetch requests from consumers.
A Kafka Cluster is a group of brokers working together to provide scalability, fault tolerance, and parallelism.
The Problem: The Single Server Limit
Imagine running a massive streaming platform on a single server.
- Storage Limit: You are bound by the hard drive space of one machine.
- Throughput Limit: You are bound by the Network Interface Card (NIC) and RAM speed of one machine.
- Single Point of Failure (SPOF): If that motherboard fails, your entire business stops.
The Solution: Distributed Coordination
Kafka solves this by distributing data (partitions) across multiple brokers. If a topic has 3 partitions and you have 3 brokers, Kafka distributes the load so each broker handles one partition.
Broker Identification
Every broker in a cluster is identified by a unique integer ID.
Configuration: server.properties
broker.id=1If you do not specify this, Kafka will generate a reserved, automatic broker ID. In production, it is best practice to assign them manually (e.g., 101, 102, 103) to align with your hostname numbering.
The Bootstrap Concept
You may wonder: How does a client know about the whole cluster if it only connects to one server?
Kafka clients (Producers/Consumers) only need to connect to one broker to discover the entire cluster. This broker is called a Bootstrap Server.
- Client connects to
broker-1. - Client requests metadata ("Where are the leaders for Topic A?").
broker-1returns the list of all active brokers and their endpoints.- Client disconnects and reconnects to the specific brokers hosting the required data.
Interesting Fact: LinkedIn developed Kafka to handle activity stream data. At their scale, they process over 7 trillion messages per day. Imagine the chaos if they tried to do this with a single monolithic server. The name "Kafka" was chosen by creator Jay Kreps because it is a system optimized for writing, and he liked the author Franz Kafka (though the author's work is famously nightmarish, the software aims to be the opposite).
2. Metadata Management: Zookeeper vs. The New KRaft Mode
The Problem: Distributed Consensus
In a cluster of 100 brokers, who decides which broker is alive? Who stores the configuration of topics? Who prevents two brokers from trying to lead the same partition simultaneously? This is the problem of Distributed Consensus.
Legacy Solution: Apache Zookeeper
Historically, Kafka utilized an external system called Apache Zookeeper to store metadata.
- Zookeeper stored the list of brokers.
- Zookeeper performed leader elections.
- Zookeeper notified Kafka when changes occurred.
Drawbacks:
- Operational Complexity: You have to manage two different distributed systems (Kafka and Zookeeper).
- Scalability Bottleneck: In massive clusters, Zookeeper became a bottleneck for metadata updates.
- Dual Security Models: You had to secure Zookeeper and Kafka separately.
The Modern Solution: KRaft (Kafka Raft Metadata Mode)
Starting with Kafka 2.8 and declared production-ready in 3.3, Kafka is removing the Zookeeper dependency. This is known as KIP-500.
In KRaft mode, metadata is stored inside Kafka itself.
- There is a special internal topic called
__cluster_metadata. - The brokers form a Raft Quorum (a consensus algorithm) to manage this log.
- The metadata is replicated just like normal data.
Comparison: Zookeeper vs. KRaft
| Feature | Zookeeper Mode (Legacy) | KRaft Mode (Modern) |
|---|---|---|
| External Dependency | Yes (Zookeeper Cluster) | No (Self-contained) |
| Controller Recovery | Slow (seconds to minutes) | Fast (milliseconds) |
| Metadata Storage | Znodes in Zookeeper | Internal Kafka Topic |
| Max Partitions | ~200,000 | Millions |
Hands-on: Formatting Storage for KRaft
Unlike Zookeeper mode, KRaft requires you to format the storage directory with a unique Cluster ID before starting the server.
# 1. Generate a UUID
$ ./bin/kafka-storage.sh random-uuid
> MKUv8b7cT6q... (Your UUID)
# 2. Format the Log Directories
$ ./bin/kafka-storage.sh format -t MKUv8b7cT6q... -c ./config/kraft/server.properties
# 3. Start Kafka
$ ./bin/kafka-server-start.sh ./config/kraft/server.propertiesIndustry Standard: If you are building a new Kafka cluster today, use KRaft. Zookeeper is marked for deprecation and will be removed in Kafka 4.0.
3. Leader Election and In-Sync Replicas (ISR)
Definition
To ensure data is not lost when a broker fails, Kafka uses Replication. However, we cannot simply write to all brokers at once without a hierarchy.
- Leader: For a specific partition, ONE broker is designated as the Leader. All reads and writes go to the Leader.
- Follower: Other brokers containing replicas of that partition are Followers. They passively fetch data from the Leader to stay up to date.
The Problem: The Lagging Follower
Network glitches occur. Disks become slow. What happens if a Follower falls behind the Leader? If the Leader crashes, can we promote the slow Follower? If we do, we lose data.
The Solution: In-Sync Replicas (ISR)
Kafka maintains a dynamic list called the ISR (In-Sync Replicas).
- The ISR is the set of all replicas that are "caught up" with the leader.
- The Leader itself is always part of the ISR.
- If a Follower lags behind by more than
replica.lag.time.max.ms(default 30 seconds), it is kicked out of the ISR.
Visualizing the Flow
Producer -> Writes to Broker 1 (Leader)
|
+-> Replicates to Broker 2 (Follower - In ISR)
+-> Replicates to Broker 3 (Follower - In ISR)If Broker 2 stops responding:
- Leader removes Broker 2 from ISR.
- ISR List:
[1, 3]. - Broker 2 restarts and catches up.
- Leader adds Broker 2 back to ISR.
Leader Election
If the Leader (Broker 1) crashes:
- The Controller (see next section) detects the failure.
- The Controller selects a new Leader from the current ISR.
- Since all members of the ISR have the data, no committed data is lost.
Important Configuration: min.insync.replicas
This is a critical setting for data durability. It defines how many ISR members must acknowledge a write for it to be considered successful (when acks=all).
- Scenario: Replication Factor = 3,
min.insync.replicas= 2. - Event: 2 brokers fail. Only 1 remains in ISR.
- Result: Producers with
acks=allwill receive an exception:NOT_ENOUGH_REPLICAS. The cluster refuses to accept writes rather than risk data that cannot be safely replicated.
Caution: Do not confuse
min.insync.replicaswithreplication.factor. The factor is how many copies exist;min.insync.replicasis the policy for write acceptance.
4. The Controller Broker: The Brain of the Operations
Definition
In a Kafka cluster, one broker acts as the Controller. It is responsible for state management. While all brokers store data, the Controller manages the metadata state.
The Problem: Split Brain
If multiple brokers thought they were in charge of assigning partitions, the cluster state would become corrupted. There must be a single source of truth for partition assignment.
Responsibilities of the Controller
- Broker Monitoring: It watches for brokers joining or leaving the cluster (via Zookeeper or KRaft heartbeats).
- Leader Election: As discussed above, when a broker fails, the Controller decides which Follower becomes the new Leader for affected partitions.
- ISR Updates: It broadcasts the new ISR list to all other brokers.
Architecture: The Epoch
To prevent "Zombie Controllers" (a controller that is disconnected but thinks it is still the leader), Kafka uses an Epoch number (essentially a version counter).
- If the Controller is
ID: 1withEpoch: 5. - Broker 1 hangs. A new Controller is elected (
ID: 2,Epoch: 6). - Broker 1 wakes up and tries to send a command with
Epoch: 5. - The cluster rejects it because the Epoch is old.
KRaft Quorum Controller
In the new KRaft architecture, the "Controller" is not just one broker randomly elected. It is a defined set of brokers acting as a consensus quorum.
- You designate specific brokers as Voters.
- Usually 3 or 5 brokers are Voters (to allow for majority consensus).
- One of them is the Active Controller; the others are Standby Controllers.
- Because the Standby Controllers already have the metadata log loaded in memory, failover is almost instantaneous.
Summary of Best Practices
- Use KRaft: For all new deployments, avoid Zookeeper.
- Odd Numbers: For Quorum/Ensembles (Zookeeper or KRaft voters), use odd numbers (3 or 5) to avoid split-vote scenarios.
- Rack Awareness: Configure
broker.rackif you are in AWS/Cloud. Kafka can distribute replicas across different Availability Zones (AZs) to survive a full data center outage. - Network Configuration: Pay close attention to
advertised.listenersinserver.properties. This is the #1 reason users cannot connect to Kafka remotely. It tells the broker what IP address to send back to the client.
References & Further Reading
- Official Documentation: Kafka Documentation - Design
- KIP-500 (KRaft): Apache Kafka KIP-500
- Configuration: Broker Configs
- Whitepaper: Kafka: a Distributed Messaging System for Log Processing
Challenge
You are a systems engineer responsible for deploying a new, fault-tolerant Apache Kafka cluster using the modern KRaft protocol. Your first task is to write the server.properties configuration file for the first broker of the cluster.
Follow these requirements precisely:
- The node must be configured to run in KRaft mode, acting as both a broker and a controller.
- This broker must have a unique
node.idof1. - The cluster will have a three-node controller quorum. The voters are identified as
1@kafka1:9093,2@kafka2:9093, and3@kafka3:9093. - The broker must listen for client traffic on port
9092from any network interface. For external clients to connect, it must advertise its address askafka1.example.com:9092. - To guarantee high data durability for topics with a replication factor of 3, you must ensure that a write is acknowledged by at least 2 replicas in the In-Sync Replica (ISR) list before it is considered committed.
Complete the configuration template below by filling in the values for the specified properties.
Expected result
Your configuration should correctly set the properties to match the requirements for a KRaft-based broker with specific networking and durability settings.
Here is a correct implementation:
# Apache Kafka Broker Configuration for kafka1
# Section 1: KRaft and Node Identification
process.roles=broker,controller
node.id=1
controller.quorum.voters=1@kafka1:9093,2@kafka2:9093,3@kafka3:9093
# Section 2: Network Listeners
listeners=PLAINTEXT://0.0.0.0:9092
advertised.listeners=PLAINTEXT://kafka1.example.com:9092
# Section 3: Data Durability
min.insync.replicas=2
# Section 4: Log Storage (pre-configured)
log.dirs=/var/lib/kafka/dataExplanation:
process.roles=broker,controller: This configures the node to participate in the KRaft quorum as a voter (controller) and also to store topic partition data (broker), eliminating the need for Zookeeper.node.id=1: Assigns a unique, static ID to this broker within the cluster.controller.quorum.voters: Lists all nodes that form the Raft consensus group. The format isnode.id@hostname:port.listeners=PLAINTEXT://0.0.0.0:9092: Tells the broker to bind to port 9092 on all available network interfaces.advertised.listeners=PLAINTEXT://kafka1.example.com:9092: This is the crucial address that the broker returns to clients. It ensures that clients, especially those outside the broker's immediate network (e.g., in Docker or a different cloud VPC), can resolve the hostname and connect correctly.min.insync.replicas=2: This enforces strong durability. For any write request withacks=all, the leader broker must wait until it receives an acknowledgement from itself and at least one other follower replica before confirming the write to the producer. This prevents data loss if the leader fails before the data is fully replicated.