How Apache Kafka Partitions Work
- Author
- Prathamesh Patil
- Length
- 2402 words
- Read
- 11 min
Key takeaways
- Apache Kafka is an event streaming platform: producers publish events to topics, brokers store them durably, and consumers read them independently.
- A topic is split into partitions. Partitions are the unit of parallelism, ordering, replication, and failure isolation.
- Events with the same key go to the same partition, so consumers see a stable order for that key. Events without a key are distributed across partitions.
- Replication copies each partition across brokers. One replica is the leader; followers stay in sync. Clients write and read through the leader.
- Consumer groups split partitions among members. Adding consumers only helps until you have one consumer per partition.
Research basis
This teardown is grounded in the official Apache Kafka documentation: the Introduction (concepts and terminology), the Design documentation for topics, partitions, replication, and consumers, and the Producer and Consumer API overviews. Kafka is open source, so the public contract is clearer than for many proprietary systems — but this article still separates documented behavior from reasonable inferences about why the design looks the way it does.
Where internals are not spelled out as a guarantee, the text says so. No request-rate, latency, or durability percentages are invented.
Quick overview
Kafka sits between systems that produce facts and systems that need those facts later, in order, and at their own pace.
An event (also called a record or message) has a key, a value, a timestamp, and optional headers. A topic is a named stream of events. Producers write to topics. Consumers subscribe to topics. Brokers are the servers that store the data.
The scaling trick is that a topic is not one append-only log. It is a set of partitions, and each partition is its own ordered log.
Producers never wait for consumers. That decoupling is intentional: write throughput and read throughput scale on different axes.
Architecture
Think of Kafka as four cooperating pieces.
- Clients. Producers publish events. Consumers pull events. Kafka Streams and Connect sit on top of the same model.
- Brokers. Store partition data, serve produce and fetch requests, and participate in replication.
- Controller. Coordinates which broker leads which partition and reacts when brokers join or leave. Modern Kafka can run this with KRaft; older clusters used ZooKeeper. The public contract for clients is the same either way: they talk to brokers about topics and partitions.
- Partition logs. On disk, each partition is an append-only sequence of segments. Retention decides when old segments are deleted or compacted.
Partitions are the seam that lets all of this scale. Add partitions to increase write and read parallelism. Add brokers to host more partition replicas. The topic name stays stable while the storage fan-out grows.
Request flow: produce and consume
Here is the path of a keyed produce followed by a consumer fetch.
Documented behavior that matters in practice:
- Metadata first. Clients learn which broker currently leads a partition, then send produce and fetch traffic to that leader. If leadership moves, clients refresh metadata and retry.
- Key → partition. The producer uses a partitioner. The default behavior routes events with the same key to the same partition so order is preserved for that key. You can plug in a custom partitioner when the default hash is wrong for your workload; most systems never need one.
- Append, then acknowledge. The leader appends to its local log. Depending on the producer's acknowledgment setting, success may wait for the leader only or for the in-sync replicas as well.
- Offsets. Each record in a partition gets a monotonically increasing offset. Consumers track progress by offset, not by deleting messages from a queue.
- Pull model. Consumers fetch. Brokers do not push into application memory. That keeps backpressure with the consumer.
Inference: treating the partition as an immutable log (instead of a destructive queue) is why multiple independent consumer groups can replay the same topic without coordinating with each other.
How partitioning creates parallelism
Ordering and parallelism pull in opposite directions. Kafka resolves that tension by scoping order to a partition.
| Scope | What Kafka guarantees |
|---|---|
| Single partition | Records are ordered by offset |
| Whole topic | No total order across partitions |
| Same key | Lands on one partition, so that key stays ordered |
| Consumer group | Each partition is read by at most one member at a time |
That table is the whole mental model. If you need a global order for every event in a topic, you need one partition — and you give up horizontal write scale. If you need scale, you pick a key that defines the ordering unit you care about (order id, account id, device id) and accept that different keys may interleave.
Hot keys are the failure mode of this design. A single popular key concentrates traffic on one partition. Spreading load then becomes a data-modeling problem (finer keys, or keyless fan-out where order does not matter), not a broker-tuning problem.
Choosing a partition count in practice:
- Start from expected parallel consumers and key cardinality. If you have many distinct keys and want eight consumers reading side by side, you need at least eight partitions.
- Prefer more partitions than you need on day one when growth is likely, because raising the count later reshuffles key→partition mapping for new records and complicates ordered replay across the change.
- Watch consumer lag, under-replicated partitions, and ISR membership in operations. Lag tells you readers are behind; under-replicated partitions and ISR shrinkage tell you durability headroom is gone even while the topic still accepts writes.
Replication and durability
Kafka replicates at the partition level. A common production choice is a replication factor of three: one leader and two followers. The official docs describe this as the way to stay available when brokers fail or when you take a broker down for maintenance.
Useful distinctions from the public design:
- Leader. Handles produces and consumes for that partition.
- Followers. Pull from the leader and stay caught up.
- In-sync replicas (ISR). The set of replicas that are sufficiently caught up. Acknowledgment policies that wait for ISR give stronger durability than leader-only acks.
- Controller reassignment. If the leader dies, another in-sync replica can become leader so the partition stays writable.
Kafka does not pretend disks never fail. Durability is “enough replicas acknowledged the append,” not “one machine is immortal.”
Consumer groups and rebalancing
A consumer group is a set of consumers that cooperate on a topic. Kafka assigns each partition to exactly one group member. That gives you parallel read without two members double-processing the same partition.
Consequences that show up in real systems:
- Max useful consumers ≈ partition count. A fifth consumer in a four-partition topic sits idle for that topic.
- Rebalances move partitions. When members join or leave, Kafka reassigns partitions. During a rebalance, processing for moved partitions pauses until the new assignment sticks.
- Offsets are per group. Two groups can read the same topic at different speeds. That is how you fan one event stream into analytics, fraud checks, and search indexing without coupling those teams.
Inference: partition count is both a capacity dial and an operational commitment. Raising it later is possible but not free; lowering it is awkward because stored offsets and ordering assumptions are tied to the old layout.
Partition count also interacts with how Kafka stores and expires data. Each partition owns its own log segments on disk. Retention (delete old segments by time or size) and log compaction (keep the latest value per key) run per partition, not once for the whole topic. More partitions mean more segment files, more open file handles, and more independent compaction work — useful parallelism, but also more operational surface. Choosing a partition count is therefore not only about consumer parallelism; it shapes disk layout and retention behavior for the life of the topic.
Failure domains and blast radius
Kafka’s blast radius follows partition and broker boundaries.
- One partition leader. If the leader fails and an in-sync follower can take over, producers and consumers continue after a short leadership change. If no in-sync replica remains, that partition becomes unavailable until recovery — other partitions keep serving.
- One broker. Every partition replica hosted there is affected. With replication factor three and careful placement, most partitions still have a live leader elsewhere.
- One rack or availability zone. Replication factor alone does not guarantee replicas land in different racks. Operators can configure broker rack information (for example
broker.rack) and related replica-placement settings so the cluster spreads replicas across racks. Without that configuration, copies of a partition may still share a single failure domain. - One consumer group member. Its partitions are reassigned to remaining members. Processing stalls for those partitions during the rebalance window.
- One bad key. Hot-key load concentrates on a single partition and can saturate that leader without taking down the whole topic.
- Poison message. A record that crashes a consumer repeatedly blocks that partition for that group until you skip, fix, or dead-letter it. Other partitions in the group continue.
The design assumes partial failure is normal. Availability of the cluster is not the same as availability of every partition.
Data-store tradeoffs
Kafka’s partition log is a specialized data store. The choices below are deliberate and not free.
- Log, not queue. Events stay until retention or compaction removes them. Consumers manage offsets. You gain replay and multiple subscribers; you lose “message disappears when processed” semantics.
- Order per partition, not per topic. Scale requires giving up global order.
- Pull consumers. Consumers control pace; slow consumers do not auto-fail producers. You must monitor lag yourself.
- Partition count is capacity planning. Throughput, consumer parallelism, segment count, and compaction fan-out all depend on it. Guess wrong and you either under-scale or over-fragment.
- Replication factor vs cost. More replicas improve fault tolerance and cost disk and network. The docs’ common setting of three is a starting point, not a universal law.
- Delivery semantics need configuration. Idempotent producers and the transactional APIs can give stronger processing guarantees than a basic produce/consume loop, but only when producers, consumers, and topic settings are wired for that mode. Until you configure and verify that path, treat processing as at-least-once and design consumers to be idempotent.
| Choice | What you gain | What you give up |
|---|---|---|
| More partitions | Parallel produce/consume | More segment files; harder to lower later |
| Replication factor 3 | Survive broker loss | Extra disk and replication traffic |
| Wait for ISR acks | Stronger durability | Higher produce latency under load |
| Leader-only acks | Faster produces | Weaker durability if the leader dies before followers catch up |
| Keyed events | Per-key order | Hot keys can pin load to one partition |
How Kafka compares to other messengers
A short orientation against systems already covered on this blog:
- Amazon SQS is a queue: consumers cooperate by deleting or hiding messages. Kafka is a log: many consumer groups can replay the same partition independently.
- Google Pub/Sub hides much of the shard layout behind subscriptions. Kafka makes partitions an explicit part of the public model you size and monitor.
- Managed stream services in the same family (for example Amazon Kinesis data streams or Apache Pulsar) also split ordered streams across shards or partitions. Kafka’s distinctive public surface is the combination of durable partitioned logs, consumer-group assignment, and ISR-based replication that you operate as first-class concepts.
Use those comparisons to pick an abstraction, not to declare a winner. The right messenger is the one whose failure domains and ordering unit match your product.
What I would steal
If I were designing an event backbone, these are the Kafka ideas I would copy:
- Make the partition the unit of everything. Parallelism, order, replication, and failure isolation share one boundary. That keeps the mental model small.
- Decouple producers from consumers with a durable log. Replay and independent subscriber groups beat destructive queues for analytics and audit.
- Key-based ordering. Let the data model declare what must stay ordered instead of forcing a global lock.
- Pull-based consumption with explicit offsets. Backpressure and replay become application-visible, not magic.
- Replicate partitions, not whole topics as opaque blobs. Failures stay local; leadership moves per partition.
- Treat consumer groups as scale-out readers. Horizontal read scale without rewriting producers.
FAQ
How do Apache Kafka partitions work? A topic is split into partitions. Each partition is an ordered append-only log stored on brokers and optionally replicated. Producers append to a chosen partition; consumers read partitions assigned by their consumer group.
Why does Kafka use partitions instead of one big log per topic? Partitions let many brokers and many consumers work in parallel. One log would serialize all writes and reads for that topic.
How does Kafka keep events with the same key in order? The producer partitioner sends equal keys to the same partition. That partition preserves append order, so a single consumer reading it sees a stable sequence for that key.
What happens when a Kafka broker fails? Partition leaders on that broker move to other in-sync replicas when possible. Partitions that still have a live leader stay available. Partitions that lose all in-sync replicas become unavailable until recovery.
How many consumers should a Kafka consumer group have? Up to the number of partitions you want to read in parallel. Extra members beyond the partition count do not increase parallelism for that topic.
Related reading
- How Amazon SQS works — a queue model compared with Kafka’s log model.
- How Google Pub/Sub works — another managed messaging design with different partition semantics.
- How API rate limiters work — protecting producers and consumers when a hot partition saturates.
- CAP theorem in real production systems — the availability vs consistency tension behind ISR and acks.
- How two-phase commit works — coordination machinery related to transactional produce/consume.
Sources
- Introduction | Apache Kafka
- Documentation | Apache Kafka
- Apache Kafka Design
- Producer API
- Consumer API
- Kafka design: message delivery semantics
- Broker configs including rack awareness
Image credits
- Cover: Custom architecture illustration