Skip to content

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

Kafka Topics and Partitions

Topics and partitions form the foundation of Kafka's distributed architecture. A topic is a logical channel for records; partitions provide horizontal scalability and fault tolerance through distributed, replicated logs.


A topic is a named, append-only log that organizes related records. Unlike traditional message queues where messages are deleted after consumption, Kafka topics retain records based on configurable retention policies.

Topic: ordersBroker 1 (host-1)Partition 0 (Leader)Broker 2 (host-2)Partition 1 (Leader)Broker 3 (host-3)Partition 2 (Leader)012301201234Each partition leader resides on a different brokerOffsets are partition-local (start at 0)No ordering guarantees across partitionsReplicas (not shown) exist on other brokers
PropertyDescription
NameUnique identifier within the cluster; immutable after creation
Partition countNumber of partitions; can be increased but not decreased
Replication factorNumber of replicas per partition; set at creation
RetentionHow long records are kept (time or size based)
Cleanup policyDelete old segments or compact by key
ConstraintRule
Length1-249 characters
Characters[a-zA-Z0-9._-] only
Reserved. and .. are not allowed
ReservedNames starting with __ are internal topics
Collision. and _ are interchangeable in metrics; avoid mixing

Internal Topics

Topics prefixed with __ are managed by Kafka internally and must not be modified directly:

  • __consumer_offsets - Consumer group offset storage
  • __transaction_state - Transaction coordinator state
  • __share_group_state - Share group state
  • __cluster_metadata - KRaft metadata (KRaft mode only)

Partitions exist because a single machine has fundamental physical limitations. Understanding these limitations explains why distributed systems like Kafka partition data across multiple nodes.

A Kafka broker running on a single server faces hard limits imposed by hardware:

Disk I/O Throughput

Kafka writes are sequential (append-only), which is optimal for disk performance. However, even sequential I/O has limits:

Storage TypeSequential Write (illustrative)Sequential Read (illustrative)Notes
HDD (7200 RPM)80-160 MB/s80-160 MB/sSeek time negligible for sequential; still limited by rotational speed
SATA SSD400-550 MB/s500-550 MB/sLimited by SATA interface (6 Gbps theoretical max)
NVMe SSD2,000-7,000 MB/s3,000-7,000 MB/sPCIe bandwidth limited; enterprise drives sustain higher throughput
NVMe (RAID 0)10,000+ MB/s15,000+ MB/sMultiple drives; reliability trade-offs

With a replication factor of 3, each produced record must be written to three brokers. The leader writes to its own disk and the followers each write to theirs. Disk I/O on followers can become a bottleneck for ISR advancement.

Network Bandwidth

Network interfaces impose hard ceilings on data transfer:

InterfaceTheoretical MaxPractical Throughput (illustrative)Notes
1 GbE125 MB/s100-110 MB/sCommon in older deployments; often the bottleneck
10 GbE1,250 MB/s1,000-1,100 MB/sStandard for modern Kafka deployments
25 GbE3,125 MB/s2,500-2,800 MB/sHigh-performance deployments
100 GbE12,500 MB/s10,000-11,000 MB/sLarge-scale deployments; requires matching infrastructure

With replication factor 3, producing 100 MB/s to a topic generates approximately:

  • 100 MB/s inbound to the leader (producer writes)
  • 200 MB/s outbound from the leader (two followers fetching)
  • 100 MB/s inbound to each follower
  • Consumer fetch traffic on top of replication

A single 10 GbE interface can become saturated with moderate production rates when accounting for replication overhead and consumer traffic.

CPU Processing

CPU becomes a bottleneck primarily in these scenarios:

OperationCPU CostWhen It Matters
CompressionHighProducer-side compression (LZ4, Snappy, Zstd) reduces network/disk but costs CPU
DecompressionMedium-HighBroker decompresses for validation (if message format conversion needed) or timestamping
TLS encryptionHighTLS 1.3 handshakes and bulk encryption; 20-40% throughput reduction typical
CRC32 checksumsLowEvery record batch verified; hardware-accelerated on modern CPUs
Zero-copy disabledHighTLS prevents zero-copy (transferTo); data copied through userspace

TLS Performance Impact

TLS encryption can reduce Kafka throughput depending on workload and hardware. However, raw encryption speed is not the bottleneck on modern hardware.

Modern CPUs with AES-NI achieve 4-7 GB/s AES-256-GCM throughput per core—far exceeding typical Kafka broker throughput. The actual overhead comes from architectural changes required for encryption:

  • Zero-copy bypass: Without TLS, Kafka uses Linux sendfile() to transfer data directly from page cache to NIC without copying through userspace. TLS requires data to be copied to userspace for encryption, then back to kernel space for transmission. This adds 2-3 memory copies per request.
  • Memory bandwidth pressure: The extra copies consume memory bandwidth that would otherwise be available for actual data transfer.
  • Syscall overhead: More context switches between kernel and userspace for each data transfer.
  • Handshake overhead: TLS session establishment for new connections (mitigated by connection pooling and session resumption).

The solution is not faster CPUs but reducing the copy overhead. Kernel TLS (kTLS, Linux 4.13+) can offload TLS to the kernel, restoring partial zero-copy capability. For latency-sensitive workloads, evaluate network-layer encryption (IPsec, WireGuard, encrypted overlay networks) which preserves application-layer zero-copy.

Memory Constraints

Each partition consumes broker memory for:

ResourcePer-Partition Cost (illustrative)Notes
Page cache utilizationVariableOS caches recent segments; partitions compete for cache space
Index files (mmap)Up to 10 MB per index per segment (default).index and .timeindex mapped into memory
Log segment overhead~1-2 MBBuffers, file handles, metadata structures
Replica fetcher threadsSharedEach source broker requires a fetcher thread

With thousands of partitions per broker, memory overhead becomes significant. Repository guidance is to limit partitions to approximately 4,000 per broker (varies with hardware).

Within a consumer group, Kafka assigns each partition to exactly one consumer. This design provides ordering guarantees but creates a parallelism ceiling:

Topic: events (6 partitions)Consumer Group: processorsP0P1P2P3P4P5Consumer 1Consumer 2Consumer 3Consumer 4 (idle)6 partitions, 4 consumersConsumer 4 is idle (no partitions to assign)Maximum parallelism = partition count

Consumer throughput limits:

BottleneckTypical LimitMitigation
Processing logicVariesOptimize code; async I/O; batch processing
Network fetch100+ MB/sIncrease fetch.max.bytes; tune max.partition.fetch.bytes
DeserializationVariesUse efficient formats (Avro, Protobuf); avoid JSON for high throughput
Downstream writesOften the limitDatabase insertion, API calls often slower than Kafka reads
Commit overheadMinorAsync commits; less frequent commits for higher throughput

If a single consumer can process 50 MB/s but the topic receives 200 MB/s, four partitions (and four consumers) are needed to keep up. The partition count sets the maximum consumer parallelism.

Physical LimitationHow Partitions Help
Disk I/O ceilingEach partition can be on a different broker with its own disks; total throughput = sum of all brokers
Network bandwidth ceilingTraffic distributed across brokers; no single NIC handles all data
CPU ceilingCompression, TLS, and CRC work distributed across brokers
Memory ceilingPartition working sets distributed; page cache pressure spread
Consumer processing ceilingMore partitions = more consumers in parallel
Storage capacityEach broker contributes its disk capacity to the cluster
Single point of failureReplicas on different brokers; partition remains available if one broker fails

Each partition is stored as a directory containing log segments. For complete storage internals including indexes, compaction, and retention, see Storage Engine.

Partition Directory: orders-0/Segment 0 (closed)Segment 1 (closed)Segment 2 (active)00000000000000000000.log00000000000000000000.index00000000000000000000.timeindex00000000000000050000.log00000000000000050000.index00000000000000050000.timeindex00000000000000100000.log00000000000000100000.index00000000000000100000.timeindexActive segment receivesnew writes (append-only) Filename = base offset
File ExtensionPurpose
.logRecord data (keys, values, headers, timestamps)
.indexSparse offset-to-file-position index
.timeindexSparse timestamp-to-offset index
.txnindexTransaction abort index
.snapshotProducer state snapshot for idempotence
leader-epoch-checkpointLeader epoch history

Offsets are 64-bit integers assigned sequentially within each partition:

ConceptDescription
Base offsetFirst offset in a segment (used in filename)
Log End Offset (LEO)Next offset to be assigned (last offset + 1)
High Watermark (HW)Last offset replicated to all ISR; consumers read up to HW
Last Stable Offset (LSO)HW excluding uncommitted transactions
Partition Log01234567High Watermark (HW) = 5Consumers can read 0-4Log End Offset (LEO) = 8Leader has written 0-7

Each partition has one leader and zero or more follower replicas. The leader handles all read and write requests; followers replicate data from the leader.

ResponsibilityDescription
Handle producesAccept and persist records from producers
Handle fetchesServe records to consumers and followers
Maintain ISRTrack which followers are in-sync
Advance HWUpdate high watermark as followers catch up
ResponsibilityDescription
Fetch from leaderContinuously replicate new records
Maintain LEOTrack local log end offset
Report positionInclude LEO in fetch requests for HW calculation
OnlineLeaderFollowerOfflinebroker startsanother replicabecomes leaderelected leaderbroker failsbroker recoversbroker fails

The ISR is the set of replicas that are fully caught up with the leader. Only ISR members are eligible to become leader if the current leader fails.

ConceptDescription
ISR membershipReplicas within replica.lag.time.max.ms of the leader
min.insync.replicasMinimum ISR size required for acks=all produces
ISR shrinkageSlow replicas removed; affects write availability

For detailed ISR mechanics, membership criteria, and configuration, see Replication: In-Sync Replicas.


When a partition leader fails, Kafka elects a new leader from the ISR. The controller (or KRaft quorum) coordinates this process.

Election TypeDescription
Clean electionNew leader chosen from ISR; no data loss
Unclean electionOut-of-sync replica becomes leader; potential data loss
Preferred electionLeadership rebalanced to preferred replica

For the complete leader election protocol, leader epochs, and configuration, see Replication: Leader Election.


The high watermark (HW) is the offset up to which all ISR replicas have replicated. Consumers can only read records up to the HW.

ConceptDescription
High Watermark (HW)Last offset replicated to all ISR members
Log End Offset (LEO)Next offset to be written (leader's latest)
Consumer visibilityConsumers read only up to HW

Read-Your-Writes

A producer may not immediately read its own writes. The record becomes visible only after HW advances (all ISR have replicated).

For high watermark advancement mechanics and the replication protocol, see Replication: High Watermark.


When topics are created or partitions are added, the controller assigns partitions to brokers. For partition reassignment procedures, see Cluster Management.

GoalStrategy
BalanceDistribute partitions evenly across brokers
Rack awarenessPlace replicas in different racks
Minimize movementPrefer keeping existing assignments
Rack ABroker 1Broker 2Rack BBroker 3Broker 4Rack CBroker 5Broker 6P0 LeaderP1 FollowerP2 FollowerP0 FollowerP1 LeaderP2 LeaderP0 FollowerP2 FollowerP1 FollowerRF=3: Each partition has replicasin 3 different racks Survives complete rack failure
ConfigurationDefaultDescription
broker.racknullRack identifier for this broker
default.replication.factor1Default RF for auto-created topics
num.partitions1Default partition count for auto-created topics

Choosing the right partition count requires understanding workload requirements and system constraints.

For throughput requirements:

Partitions needed = Target throughput / Per-partition throughput

Per-partition throughput depends on the bottleneck:

ComponentTypical Per-Partition LimitDetermining Factors
Producer to single partition10-50 MB/sBatch size, linger.ms, compression, network RTT
Consumer from single partition50-100+ MB/sConsumer processing speed, fetch size, downstream latency
Broker disk I/OShared across partitionsTotal broker throughput / partition count

Example calculation:

  • Target throughput: 500 MB/s production
  • Single producer batch throughput to one partition: ~30 MB/s (with compression, acks=all)
  • Minimum partitions for throughput: 500 / 30 ≈ 17 partitions

However, consumer parallelism may require more:

  • Consumer processing rate: 25 MB/s per consumer
  • Consumers needed: 500 / 25 = 20 consumers
  • Partitions needed: at least 20 (one per consumer)

For ordering requirements:

Records with the same key are routed to the same partition. If strict ordering across a key space is required:

Ordering ScopePartition Strategy
Per-entity ordering (e.g., per user)Use entity ID as key; Kafka guarantees order within partition
Global ordering (all records)Single partition only; limits throughput to single-partition maximum
No ordering requirementPartition for throughput; use round-robin or random keys
FactorMore PartitionsFewer Partitions
Maximum throughputHigher (parallel I/O, more consumers)Lower (single-broker ceiling)
Consumer parallelismHigher (one consumer per partition max)Lower
Ordering granularityFiner (per-partition ordering)Coarser (broader ordering scope)
End-to-end latencyCan increase (more batching coordination)Can decrease (simpler path)
Broker memoryHigher (~1-2 MB per partition-replica)Lower
File handlesHigher (3 file handles per segment per partition)Lower
Controller overheadHigher (more metadata, slower elections)Lower
Rebalance timeLonger (more partition movements)Shorter
Recovery timeLonger (more partitions to recover)Shorter
Availability during failuresHigher (smaller blast radius per partition)Lower (more data affected per partition)
Workload CharacteristicsSuggested Approach
Low throughput (<10 MB/s), ordering important3-6 partitions; focus on key distribution
Medium throughput (10-100 MB/s)6-30 partitions; balance throughput and operational overhead
High throughput (100-500 MB/s)30-100 partitions; ensure sufficient consumers
Very high throughput (500+ MB/s)100+ partitions; may require multiple clusters for extreme scale
Strict global ordering1 partition; accept throughput ceiling
Unknown future growthStart with more partitions (can't reduce); 12-30 is often reasonable

Partition Count Cannot Be Decreased

Once a topic is created, the partition count can only be increased, not decreased. Increasing partitions also breaks key-based ordering guarantees for existing keys (keys may hash to different partitions).

Partition Count Upper Bounds (Repository Guidance)

Limit partitions per broker to approximately 4,000 and partitions per cluster to approximately 200,000 (as of Kafka 3.x). These limits relate to:

  • Controller metadata management overhead
  • ZooKeeper/KRaft watch overhead
  • Leader election time during broker failures
  • Memory consumption for indexes and buffers

See KIP-578 for partition limit configuration.


Kafka maintains metadata about topics and partitions in the controller. Clients fetch this metadata to discover partition leaders.

MetadataDescription
Topic listAll topics in cluster
Partition countNumber of partitions per topic
Replica assignmentWhich brokers host each partition
LeaderCurrent leader for each partition
ISRIn-sync replicas for each partition
ControllerCurrent controller broker
TriggerDescription
metadata.max.age.msPeriodic refresh (default: 5 minutes)
NOT_LEADER_OR_FOLLOWER errorImmediate refresh
UNKNOWN_TOPIC_OR_PARTITION errorImmediate refresh
New producer/consumerInitial fetch

Actual throughput varies significantly based on hardware, configuration, and workload. The following provides reference points from common deployment scenarios:

Single-Broker Throughput (Repository Guidance)

Section titled “Single-Broker Throughput (Repository Guidance)”
ConfigurationProduction ThroughputNotes
HDD, 1 GbE, no TLS50-80 MB/sNetwork often the bottleneck
SSD, 10 GbE, no TLS200-400 MB/sDisk and CPU become factors
NVMe, 10 GbE, no TLS300-500 MB/sCPU and network limits
NVMe, 25 GbE, no TLS500-800 MB/sHigh-end configuration
Any config + TLS20-40% reductionTLS overhead; varies with hardware AES support
Any config + compressionCPU-dependentLZ4/Snappy: minor overhead; Zstd: higher CPU, better ratio

These figures assume:

  • Replication factor 3 with acks=all
  • Reasonable batch sizes (16-64 KB)
  • Modern server-class hardware
  • No other significant workloads on the brokers
FactorImpactMitigation
Small messages (<100 bytes)Overhead dominates; lower MB/sBatch more aggressively; consider message aggregation
High partition countMore memory, more file handlesStay within broker limits; balance across cluster
acks=all with slow followersLatency increases; throughput may dropEnsure followers on fast storage; monitor ISR
TLS without AES-NISevere CPU bottleneckUse hardware with AES-NI support
Page cache pressureMore disk readsAdd RAM; reduce partition count per broker
Cross-datacenter replicationRTT affects acks=all latencyUse async replication (MirrorMaker 2) for cross-DC

FeatureMinimum Version
Rack-aware assignment0.10.0
Leader epoch0.11.0
Follower fetching (KIP-392)2.4.0
Tiered storage3.6.0 (early access)
KRaft mode3.3.0 (production)

ConfigurationDefaultDescription
retention.ms604800000 (7d)Time-based retention
retention.bytes-1 (unlimited)Size-based retention per partition
segment.bytes1073741824 (1GB)Log segment size
segment.ms604800000 (7d)Time before rolling segment
cleanup.policydeletedelete, compact, or both
min.insync.replicas1Minimum ISR for acks=all
unclean.leader.election.enablefalseAllow non-ISR leader election
ConfigurationDefaultDescription
num.partitions1Default partitions for new topics
default.replication.factor1Default RF for new topics
replica.lag.time.max.ms30000Max lag before ISR removal
replica.fetch.max.bytes1048576Max bytes per replica fetch
broker.racknullRack identifier