Kafka Internals: Partitions, Replicas, ISR, Controller
Difficulty: Expert | Asked at: Google, LinkedIn, Confluent, Uber
βΉοΈInterview Context
This question tests your understanding of Kafka's core architecture. Senior and Staff-level candidates are expected to explain partition leadership, the ISR mechanism, and controller failover with confidence.
The Question
Explain the internal architecture of Apache Kafka. How do partitions, replicas, the ISR (In-Sync Replicas) set, and the controller interact? Describe what happens when a broker fails and how the system maintains data consistency.
Core Architecture Overview
Kafka's architecture is built on a distributed log abstraction. At the highest level:
Producer β Broker Cluster β Consumer Group
β
Controller (one broker)
β
Partition Leaders + Follows
Partition Model
Each topic is divided into P partitions. Partition assignment follows:
For a topic with replication factor , each partition has replicas spread across different brokers. One replica is the leader and are followers.
β οΈKey Insight
All reads and writes go through the partition leader. Followers exist purely for fault tolerance and read scaling (when configured).
In-Sync Replicas (ISR)
The ISR is the set of replicas that are fully caught up with the leader. Formally:
Where lag is measured as the time difference between the leader's last write and the follower's replication offset.
Key properties of ISR:
- Every replica starts in the ISR
- A replica is removed if it falls behind by
replica.lag.time.max.ms(default 30s) - A replica is re-added once it catches up
- The ISR must be acknowledged for
acks=all
ISR Shrinking and Expansion Events
# Pseudocode for ISR management
class ISRManager:
def __init__(self, leader, replicas, lag_threshold_ms=30000):
self.leader = leader
self.replicas = replicas
self.isr = set(replicas)
self.lag_threshold = lag_threshold_ms
def check_isr(self, current_time_ms):
"""Called periodically by the leader"""
new_isr = set()
for replica in self.replicas:
last_caught_up = replica.last_fetch_time_ms
if current_time_ms - last_caught_up <= self.lag_threshold:
new_isr.add(replica)
removed = self.isr - new_isr
added = new_isr - self.isr
if removed:
log.warn(f"ISR shrinking: removed {removed}")
if added:
log.info(f"ISR expanding: added {added}")
self.isr = new_isr
return self.isr
Controller Election
The controller is a single broker responsible for:
- Partition leader election
- Topic creation/deletion
- Broker registration/deregistration
- ISR management coordination
Controller Election Protocol
1. All brokers watch /controller in ZooKeeper
2. When controller dies:
a. ZooKeeper ephemeral node /controller deleted
b. All brokers receive watch notification
c. Each broker attempts sequential write to /controller
d. First successful writer becomes controller
3. New controller:
a. Reads all partition metadata
b. For each partition where leader was dead:
- Selects new leader from ISR
- Updates /brokers/topics/<topic>/partitions/<p>/state
c. Broadcasts leadership changes
β οΈZooKeeper vs KRaft
In KRaft mode (Kafka 3.4+), the controller quorum replaces ZooKeeper entirely. The metadata log is replicated across controller nodes using Raft consensus, eliminating the single-point-of-failure concern of ZK.
Leader Election Process
When a partition leader fails, the controller initiates election:
class LeaderElection:
def __init__(self, partition, isr_list, preferred_replicas):
self.partition = partition
self.isr = isr_list
self.preferred = preferred_replicas
def elect_leader(self):
"""Offline leader election"""
# Priority: preferred replica order within ISR
for replica in self.preferred:
if replica in self.isr and replica.is_alive():
return replica
# Fallback: any live ISR member
for replica in self.isr:
if replica.is_alive():
return replica
# No available replica
raise NoAvailableLeader(self.partition)
def elect_with_unclean_leader(self):
"""Unclean leader election (dangerous)"""
# Allows non-ISR replica to become leader
# Risk: data loss
for replica in self.partition.replicas:
if replica.is_alive():
return replica
raise NoAvailableLeader(self.partition)
Leader Election Timeline
T+0ms: Leader broker (B1) crashes
T+0-50ms: ZooKeeper session timeout / heartbeat failure
T+50ms: Controller notified via Watcher
T+50-100ms: Controller reads partition state from ZK
T+100-150ms: Controller selects new leader from ISR
T+150-200ms: Controller writes new state to ZK
T+200-250ms: New leader begins serving requests
T+250ms: Producers/consumers updated via metadata refresh
Replication Protocol
Followers pull data from the leader using a fetch-based protocol:
class ReplicationFetcher:
def __init__(self, leader, follower, max_fetch_bytes=1048576):
self.leader = leader
self.follower = follower
self.max_fetch_bytes = max_fetch_bytes
self.fetch_offset = follower.log_end_offset
def fetch_loop(self):
while self.follower.is_running():
# Request batch from leader
fetch_request = FetchRequest(
topic=self.partition.topic,
partition=self.partition.id,
offset=self.fetch_offset,
max_bytes=self.max_fetch_bytes
)
response = self.leader.fetch(fetch_request)
if response.has_data():
# Append to local log
bytes_written = self.follower.append(
response.records,
response.offset
)
# Update high watermark
if response.high_watermark > self.follower.high_watermark:
self.follower.high_watermark = response.high_watermark
self.fetch_offset = response.high_watermark
time.sleep(0.1) # Backoff if no data
High Watermark and Data Consistency
The high watermark (HW) is the offset of the last committed message that all ISR members have replicated:
βΉοΈRead Visibility
Consumers with isolation.level=read_committed only see messages up to the high watermark. This prevents reading uncommitted or partially replicated data.
What the broker actually writes to disk
Each partition lives in its own directory under log.dirs, named topic-partition, for example user-events-3. Inside that directory the broker keeps one active segment plus the segments already rolled, each paired with an offset index and a time index so a fetch at a known offset resolves through a binary search instead of a sequential scan. The active segment accepts appends until it reaches log.segment.bytes, which is 1 GB by default, then it is closed and a new one opens. Segment rolling is what makes retention cheap: expired data is removed a whole segment at a time by the log manager, driven by log.retention.ms (7 days by default) or log.retention.bytes (unlimited by default), never record by record. Topics using cleanup.policy=compact swap deletion for compaction, where the log cleaner keeps the newest value per key and discards older copies. That is why changelog topics backing Streams state stores always run in compact mode: replay must rebuild the same state, not a truncated history.
Reading ISR shrink and expand as signals
An ISR shrink is rarely an incident by itself, but the rate tells you what the cluster is struggling with. A replica leaves the ISR when the leader has not seen a fetch from it within replica.lag.time.max.ms, 30,000 ms by default, and rejoins as soon as a fetch succeeds. Since Kafka removed the count-based replica.lag.max.messages threshold, only elapsed time matters, so a follower that stays 25 seconds behind remains in the ISR while one that stalls for 31 seconds drops out even if it is a single record behind. Compare IsrShrinksPerSec with IsrExpandsPerSec: repeated shrink-expand cycles point at a follower with an unstable disk or a broker garbage collection problem, while a steady shrink with no matching expansion means a broker is gone. UnderReplicatedPartitions should sit at zero on a healthy cluster, because any nonzero value means some partition has fewer live copies than its replication factor.
Failure timelines to quote under pressure
Interviewers like concrete numbers, because they show you have watched a real incident rather than read a diagram. With ZooKeeper, a hard-killed broker is usually noticed when its session expires after zookeeper.session.timeout.ms (10 s by default), then the controller writes the new leader into the partition state node, brokers receive a metadata refresh, and producers retry against the new leader. That typically lands between 5 and 15 seconds of reduced availability, and no data is lost as long as the new leader came from the ISR. A controlled shutdown is faster and safer: the broker transfers leadership for every partition it leads to another ISR member first, then exits, so the window is measured in hundreds of milliseconds. Under KRaft the controller quorum notices the broker failure through its own heartbeat and runs the same leader election without the ZooKeeper session step at all.
Sizing replication factor and min.insync.replicas
Replication factor 3 is the default answer for almost every topic because it survives the loss of one broker with a copy still in the ISR, and it costs exactly two extra copies of every write. Moving to 5 protects against two simultaneous failures but doubles replication traffic for a failure mode that is rare outside rack-level events, so most teams reserve it for topics that cannot be rebuilt from a source system. Pair the factor with min.insync.replicas: with factor 3 and min.insync.replicas=2, acks=all still succeeds while one follower is slow, and the cluster tolerates a full broker loss without failing writes. Setting min.insync.replicas equal to the replication factor gives the strongest durability, but then any single slow follower turns into producer errors, which is why that setting belongs only on data you cannot afford to re-ingest.
Complete Example: Producer-Acks-Broker Flow
from kafka import KafkaProducer
from kafka.errors import NotEnoughReplicas, NotEnoughReplicasAfterAppend
import time
def produce_with_acks():
producer = KafkaProducer(
bootstrap_servers='localhost:9092',
acks='all', # Wait for all ISR
retries=5,
max_in_flight_requests_per_connection=1, # Ordering
enable_idempotence=True, # Exactly-once
linger_ms=5, # Batch for 5ms
batch_size=16384, # 16KB batches
compression_type='snappy',
request_timeout_ms=30000
)
for i in range(1000):
message = f"event-{i}"
future = producer.send(
topic='user-events',
key=f"user-{i % 100}".encode(),
value=message.encode(),
headers=[('source', b'web-app')]
)
try:
record_metadata = future.get(timeout=30)
print(f"Sent to partition {record_metadata.partition} "
f"offset {record_metadata.offset}")
except NotEnoughReplicas:
print("Not enough replicas available")
except NotEnoughReplicasAfterAppend:
print("Not enough replicas after append")
except Exception as e:
print(f"Produce failed: {e}")
producer.flush()
producer.close()
# Critical Kafka metrics for architecture health
metrics_to_watch = {
# ISR metrics
"kafka.server:type=ReplicaManager,name=IsrShrinksPerSec": "ISR shrink rate",
"kafka.server:type=ReplicaManager,name=IsrExpandsPerSec": "ISR expand rate",
"kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions": "Under-replicated count",
# Controller metrics
"kafka.controller:type=KafkaController,name=ActiveControllerCount": "Controller active",
"kafka.controller:type=KafkaController,name=OfflinePartitionsCount": "Offline partitions",
"kafka.controller:type=ControllerChannelManager,name=QueueSize": "Controller queue",
# Partition metrics
"kafka.server:type=ReplicaManager,name=PartitionCount": "Total partitions",
"kafka.log:type=Log,name=Size": "Log size per partition"
}
Common Follow-Up Questions
-
Why does Kafka use pull-based replication instead of push?
- Pull allows followers to control fetch rate
- Avoids overwhelming slow followers
- Enables natural backpressure
- Simplifies leader logic (stateless replication)
-
What happens during a controlled shutdown?
- Broker moves leadership of its partitions to other ISR members first
- Then shuts down cleanly
- No data loss, minimal unavailability window
-
How does rack awareness work?
- Brokers configured with
broker.rackproperty - Controller ensures replicas span different racks
- Protects against rack-level failures
- Brokers configured with
β οΈCritical Concept
The ISR mechanism is what makes Kafka's acks=all both safe and performant. If ISR always contained all replicas, it would be equivalent to synchronous replication. The ISR allows Kafka to be flexibleβsometimes synchronous (all replicas in sync), sometimes asynchronous (some replicas lagging).
Common Mistakes
Treating an ISR shrink as if data was already lost
Fix: Check UnderReplicatedPartitions and OfflinePartitionsCount first; a shrink only narrows the acks quorum until the follower catches up again
Setting min.insync.replicas equal to the replication factor on every topic
Fix: Leave one replica of headroom, typically factor 3 with min.insync.replicas 2, so one slow follower does not fail acks=all writes
Describing replication as the leader pushing records to followers
Fix: Replication is fetch-based: followers pull from the leader, which is why a slow follower degrades only its own copy
Key Takeaways
- All reads and writes go through the partition leader; followers exist only for fault tolerance and are updated by pulling fetches from that leader
- A replica leaves the ISR after replica.lag.time.max.ms of missed fetches, 30 seconds by default, and acks=all is acknowledged by whichever replicas remain
- The controller is the single broker that elects leaders, coordinates ISR changes, and handles topic and broker lifecycle events
- Durable producer settings combine acks=all with min.insync.replicas so availability survives one lagging replica while durability still needs two live copies