Skip to content

AxonOps — AI-Native Control Plane for Open Source Data Platforms

Kafka Broker Architecture

This section covers the internal architecture of a Kafka broker—the server process that stores messages and serves client requests. Understanding broker internals is essential for capacity planning, performance tuning, and troubleshooting.

A Kafka broker handles a portion of the cluster's data, enabling horizontal scaling and fault tolerance.


Broker responsibilities for produce, storage, replication, and fetchBroker responsibilities for produce, storage, replication, and fetchKafka BrokerReceive produce requestsStore to disk (commit log)Replicate to followersServe fetch requestsProducerConsumerOther Brokers
ResponsibilityDescription
Store messagesPersist records to disk as log segments
Serve producersAccept writes, acknowledge based on acks setting
Serve consumersReturn records from requested offsets
Replicate dataSend records to follower replicas
Receive replicasAccept records from the leader replica
Report metadataRegister with controller, report partition state

Each broker has a unique identity within the cluster:

# Unique broker ID (must be unique across cluster)
node.id=1
# Listeners for client and inter-broker communication
listeners=PLAINTEXT://:9092,CONTROLLER://:9093
advertised.listeners=PLAINTEXT://broker1.example.com:9092
# Data directory
log.dirs=/var/kafka-logs

Controller listener only in combined mode

Include the CONTROLLER listener only when process.roles=broker,controller. Broker-only nodes should not expose a controller listener.

Clients discover brokers through the bootstrap servers, then connect directly to the broker hosting each partition's leader.


Brokers don't own topics—they own partition replicas. Each partition has one leader and zero or more followers:

Partition leader and follower placement across three brokersPartition leader and follower placement across three brokersTopic: orders (3 partitions, RF=3)Broker 1Broker 2Broker 3P0 LeaderP1 FollowerP2 FollowerP0 FollowerP1 LeaderP2 FollowerP0 FollowerP1 FollowerP2 LeaderLeaders (green) handle all reads/writesFollowers (yellow) replicate from leaders
RoleResponsibilities
LeaderHandle all produce and fetch requests for the partition
FollowerFetch records from leader, ready to become leader if needed

A single broker typically hosts hundreds or thousands of partition replicas, some as leader, others as follower.

For replication protocol details, ISR management, and leader election, see Replication.


KRaft (Kafka Raft) is production-ready from Kafka 3.3+ and is the only metadata mode in Kafka 4.0+; ZooKeeper remains supported through 3.9.x.

KRaft controller quorum replicating metadata to brokersKRaft controller quorum replicating metadata to brokersController QuorumController 1(Leader)Controller 2Controller 3Broker 1Broker 2Broker 3Stores cluster metadata in__cluster_metadata logRaft replicationRaft replicationmetadata updatesmetadata updatesmetadata updates
RoleConfigurationDescription
brokerprocess.roles=brokerHandles client requests only
controllerprocess.roles=controllerManages metadata only
combinedprocess.roles=broker,controllerBoth roles in one process
DeploymentBest ForTrade-off
CombinedSmall clusters (≤10 brokers)Simpler, but resource contention
DedicatedLarge clustersMore servers, but better isolation

For complete KRaft documentation, see KRaft: Kafka Raft Consensus.


The network layer handles all client and inter-broker communication using a reactor pattern with distinct thread pools.

Broker network threading model from acceptor to response queueBroker network threading model from acceptor to response queueAcceptor Thread(1 per listener)Network Processors(num.network.threads)Request QueueRequest Handlers(num.io.threads)Response Queue(per processor)new connectionsrequestsdequeueresponsessend
Thread PoolDefaultConfigurationRole
Acceptor1 per listenerFixedAccept new TCP connections
Network Processors3num.network.threadsRead requests, write responses (NIO)
Request Handlers8num.io.threadsExecute request logic
  1. Accept - Acceptor thread accepts TCP connection
  2. Assign - Connection assigned to network processor (round-robin)
  3. Read - Network processor reads request from socket
  4. Queue - Request placed in shared request queue
  5. Handle - Request handler dequeues and executes
  6. Response - Response queued for network processor
  7. Send - Network processor writes response to socket
Cluster Sizenum.network.threadsnum.io.threads
Small (< 10 brokers)38
Medium (10-50 brokers)4-68-16
Large (50+ brokers)8+16-32

For security configuration, see Authentication and Authorization.


The purgatory holds delayed requests waiting for conditions to be satisfied, enabling efficient handling without blocking handler threads.

OperationCompletion ConditionTimeout
DelayedProduceAll ISR replicas acknowledgedrequest.timeout.ms
DelayedFetchmin.bytes data availablefetch.max.wait.ms
DelayedJoinRebalance window ends (join/sync complete or timeout)rebalance.timeout.ms
DelayedHeartbeatSession timeout checksession.timeout.ms
Request purgatory components for delayed operationsRequest purgatory components for delayed operationsPurgatoryDelayedOperationsTimer WheelWatch KeysRequest HandlerWatcheradd delayed optimeout checkcondition checkcompleteresponse
Produce request with acks=all held in purgatory until ISR catches upProducerLeaderPurgatoryFollowerProducerProducerLeaderLeaderPurgatoryPurgatoryFollowerFollowerProduceRequest(acks=all)Append to local logCreate DelayedProduceFetchRequestFetchResponseAppend to logAll ISR caught upComplete DelayedProduceProduceResponse(success)

Kafka uses a hierarchical timing wheel for O(1) timeout management:

Hierarchical timer wheel levels for timeout trackingHierarchical timer wheel levels for timeout trackingLevel 0 (1ms slots)Level 1 (20ms slots)171625Current tickOverflow wheel

Brokers host two coordinator components based on internal topic partition assignment.

Manages consumer group membership, partition assignment, and offset storage.

coordinator_partition = hash(group.id) % offsets.topic.num.partitions
coordinator_broker = leader of __consumer_offsets partition
FunctionDescription
Membership managementTrack group members via heartbeats
Rebalance coordinationOrchestrate JoinGroup/SyncGroup protocol
Offset storagePersist committed offsets to __consumer_offsets

For consumer group protocol and operations, see Consumer Groups.

Manages exactly-once semantics for transactional producers.

coordinator = hash(transactional.id) % transaction.state.log.num.partitions
coordinator_broker = leader of __transaction_state partition
FunctionDescription
PID assignmentAssign producer IDs and epochs
State persistenceStore transaction state in __transaction_state
Commit coordinationWrite transaction markers to partition leaders

For transaction semantics and protocol, see Transactions.

TopicPartitionsPurpose
__consumer_offsetsDefault 50 (configurable)Consumer group offsets
__transaction_stateDefault 50 (configurable)Transaction coordinator state
__cluster_metadata1 (internal log)KRaft metadata log

When a broker starts—especially after a crash—it must recover state before serving requests.

Broker startup sequence from configuration load to serving requestsBroker startup sequence from configuration load to serving requestsLoadConfigLogRecoveryIndexCheckRegisterWithControllerCatchUpActiveSlowest phasebroker startsload server.propertiesscan log directoriesverify/rebuild indexesregister with controllerreplicas catch upserving requests
Shutdown TypeDetectionRecovery Behavior
Clean.kafka_cleanshutdown markerSkip log scanning, fast startup
UncleanNo marker (crash, kill -9)Full log recovery, validate segments

On unclean shutdown, each partition's log is validated:

  1. Scan log directory for segment files
  2. Validate segment CRC checksums
  3. Truncate at corruption point if found
  4. Rebuild indexes if invalid
  5. Truncate incomplete records at end of active segment
Partition SizeRebuild Time
1 GB5-15 seconds
10 GB30-90 seconds
100 GB5-15 minutes

Many Partitions = Slow Startup

A broker with 1000 partitions requiring index rebuild can take 30+ minutes to start.

After leader failure, followers may need to truncate divergent entries:

Follower log truncation after leader failureFollowerNew LeaderFollowerFollowerNew LeaderNew LeaderOffsetsForLeaderEpoch(epoch=5)endOffset=1000Local log has offset 1050 (divergent)Truncate to offset 1000Fetch(offset=1000)Records from 1000
Terminal window
# Graceful shutdown (recommended)
kafka-server-stop.sh
# Or send SIGTERM
kill <broker-pid>

The broker will:

  1. Notify the controller
  2. Transfer leadership to other ISR members
  3. Complete in-flight requests
  4. Write clean shutdown marker

Avoid kill -9

kill -9 causes unclean shutdown, requiring full log recovery.


# Survive 2 broker failures
default.replication.factor=3
# Require 2 replicas to acknowledge writes
min.insync.replicas=2
# Never elect out-of-sync replica as leader
unclean.leader.election.enable=false

For failure scenarios and recovery procedures, see Fault Tolerance.


node.id=1
listeners=PLAINTEXT://:9092
advertised.listeners=PLAINTEXT://broker1.example.com:9092
log.dirs=/var/kafka-logs
log.retention.hours=168
log.segment.bytes=1073741824

For log segment internals, indexes, and compaction, see Storage Engine.

num.network.threads=3
num.io.threads=8
num.replica.fetchers=1
# Request queue
queued.max.requests=500
# Socket settings
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
default.replication.factor=3
min.insync.replicas=2
replica.lag.time.max.ms=30000
# Recovery threads (increase for faster recovery)
num.recovery.threads.per.data.dir=1
# Unclean leader election (data loss risk)
unclean.leader.election.enable=false

For complete configuration reference, see Broker Configuration.


MetricAlert Threshold
kafka.network:type=RequestChannel,name=RequestQueueSize> 100 sustained
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent< 30%
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent< 30%
kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Produce> 1000

TopicDescription
Storage EngineLog segments, indexes, compaction, retention
ReplicationISR, leader election, high watermark
Memory ManagementJVM heap, page cache, zero-copy
KRaftRaft consensus, controller quorum, migration
Fault ToleranceFailure detection and recovery
Cluster ManagementMetadata management and coordination