Kafka: partitions and consumer groups
How Kafka orders, replicates and distributes records, and how to choose keys, replication settings and a partition count in a design.
The problem
Around 2010, LinkedIn had two kinds of data moving between its systems. Activity data, such as page views, searches and clicks, fed recommendations, search ranking and security monitoring. Operational data, such as metrics and logs, fed dashboards and alerts. Each source was wired to each destination by its own pipeline, so every new system meant several new integrations.
The existing tools did not fit. Log aggregation systems of the time were built to load data into a warehouse or Hadoop for offline analysis, not to feed live consumers. Traditional message brokers tracked the delivery state of every message and were designed on the assumption that queues stay short. A consumer that fell a day behind, or a batch job that wanted to read everything, was outside what they were built for.
Jay Kreps, Neha Narkhede and Jun Rao treated it as a storage problem. Their system, Kafka, open-sourced in 2011, appends records to files in order, lets each consumer remember its own position, and batches at every step. Sequential disk writes and the operating system’s page cache made it fast, and keeping data after it had been read let many unrelated consumers share one feed. This lesson builds on Queues vs logs.
Topics, partitions and offsets
A topic is a named stream of records, such as orders. It is split into partitions, and each partition is an ordered, append-only log on a broker’s disk. Every record in a partition has an offset, a number that rises by one per record. A record is a key, a value, a timestamp and optional headers.
The partition is the unit of ordering, of replication and of parallelism. A topic with 12 partitions is 12 independent logs that share a name.
Keys and ordering
The producer decides which partition a record goes to. With a key, the default partitioner hashes the key and takes the result modulo the partition count, so the same key always lands on the same partition. Without a key, records are spread across partitions a batch at a time.
That gives Kafka’s ordering guarantee and its limit: records are ordered within a partition, and there is no order across partitions. If every event for account 42 carries the key 42, a consumer sees them in the order they were written. Events for accounts 42 and 43 have no defined order relative to each other.
Two consequences come up in interviews:
- Choose the key to match the ordering you need. Use the order ID for an order’s lifecycle, or the account ID for a ledger. A key that is too coarse, such as country, creates a hot partition. No key at all gives up ordering.
- Changing the partition count moves keys.
hash(key) mod 12andhash(key) mod 16disagree for most keys, which is the problem described in consistent hashing. New records for a key go to a different partition from its old ones, so per-key order breaks across the change. Partitions can be added but never removed.
Replication
Each partition has a replication factor, normally 3. One replica is the leader and takes every write. The others are followers that fetch from it. The in-sync replicas (ISR) are the leader plus the followers that are caught up. A record is committed once every in-sync replica has it, and consumers only ever see committed records.
Step 1 of 8
Partition 0 has replication factor 3. Broker 1 is the leader and takes every write. Brokers 2 and 3 are followers, and all three are in the in-sync replica set, the ISR. The topic sets min.insync.replicas to 2.
Read the steps as text
- Partition 0 has replication factor 3. Broker 1 is the leader and takes every write. Brokers 2 and 3 are followers, and all three are in the in-sync replica set, the ISR. The topic sets min.insync.replicas to 2.
- The producer sends a record with acks=all. The leader appends it to its own log at offset 7. It does not acknowledge yet, because the followers do not have the record.
- Followers pull from the leader with fetch requests, much as consumers do. Both copy offset 7 into their own logs.
- Every in-sync replica now has the record, so the leader advances the high watermark past it and acknowledges the producer. Consumers can read only up to the high watermark, so they never see a record that could still be lost.
- Broker 3 slows down, perhaps because a disk is failing. Once it has not caught up for replica.lag.time.max.ms, which is 30 seconds by default, the leader removes it from the ISR. Writes carry on with two in-sync replicas, which still meets the minimum of 2.
- Now broker 1 crashes. The controller chooses a new leader from the ISR only. Broker 2 holds every acknowledged record, so it takes over and nothing acknowledged is lost. Producers and consumers refresh their metadata and switch to it.
- The ISR is now broker 2 alone, which is below min.insync.replicas. Produce requests with acks=all are rejected with a NotEnoughReplicas error. Kafka refuses writes it cannot protect, while consumers can still read.
- Broker 3 recovers, fetches from the new leader until it has caught up, and rejoins the ISR. Writes are accepted again. Replication factor 3 with min.insync.replicas 2 and acks=all survives the loss of one broker with no lost data and no write outage.
The producer’s acks setting chooses how long it waits:
acks |
Producer waits for | A write can be lost when |
|---|---|---|
0 |
Nothing | Anything fails, silently |
1 |
The leader’s own write | The leader dies before a follower copies it |
all |
Every in-sync replica | Every in-sync replica is lost |
acks=all is not enough by itself, because the ISR can shrink to the leader alone. The setting min.insync.replicas closes that gap: when it is 2, a write with acks=all is rejected unless at least two replicas are in sync. The standard durable configuration is replication factor 3, min.insync.replicas=2 and acks=all, with unclean leader election left off so that an out-of-date replica can never become leader. It survives one broker failure without losing data or refusing writes. On a second failure it stops accepting writes, which is choosing consistency over availability in the terms of CAP.
Since Kafka 3.0 the producer defaults to acks=all with idempotence enabled. Older clients defaulted to acks=1. min.insync.replicas still defaults to 1, so set it yourself.
Consumer groups and rebalancing
A consumer group is a set of consumers that share a group ID. Kafka assigns each partition to exactly one consumer in the group, so the group as a whole reads every record once, in parallel. Different groups are independent, and each receives everything.
A consumer commits its offset for each partition to an internal topic, __consumer_offsets. After a crash, whichever consumer takes over the partition resumes from the last committed offset. Whether you commit before or after processing decides whether a crash loses work or repeats it, which is covered in delivery semantics.
Because a partition has one reader per group, the partition count caps a group’s parallelism. A seventh consumer on a six-partition topic sits idle.
A rebalance redistributes partitions when a consumer joins, leaves or is judged dead, or when partitions are added. A consumer is judged dead when it misses heartbeats for session.timeout.ms, or when it goes longer than max.poll.interval.ms (5 minutes by default) between calls to poll(). The second rule catches people out: a slow batch looks like a dead consumer, its partitions move, the work is repeated elsewhere, and the group can thrash.
The original “eager” protocol made every consumer give up every partition during a rebalance, which paused the whole group. Cooperative rebalancing (Kafka 2.4) moves only the partitions that need to move. Static membership lets a restarting consumer keep its assignment through a rolling deploy. Kafka 4.0 made a new protocol generally available in which the broker computes assignments and rebalances are incremental.
In the simulator, produce several messages with the same key and check that they land on one partition, then add consumers until there are more consumers than partitions and see what the extra one receives.
Retention and compaction
Kafka deletes by policy, never because a record was read. There are two policies:
- Delete, the default. Old log segments are removed once they pass a time limit (7 days by default) or a size limit.
- Compact. Kafka keeps at least the latest record for each key and discards older ones in the background. A record with a null value, called a tombstone, deletes the key. A compacted topic is a durable table of current state, used for changelogs and for Kafka’s own offsets topic.
Choosing a partition count
Work from throughput. If the topic must carry 50 MB/s and one consumer instance can process 5 MB/s, you need at least 10 partitions for the consumers to keep up. Add headroom and choose 12 or 16. Then check the hottest key, since a single key cannot be spread.
More is not free. Each partition costs file handles, memory and replication work, lengthens recovery after a broker failure, and splits the same traffic into smaller, less efficient batches. Because adding partitions later breaks key ordering, teams usually over-provision moderately at the start.
KRaft replaced ZooKeeper
Kafka originally kept cluster metadata (brokers, topics, partition leaders) in Apache ZooKeeper, a separate coordination service that had to be deployed and operated alongside it. KRaft moves the metadata into Kafka itself: a small quorum of controller nodes replicates a metadata log with a Raft-based protocol, the approach described in consensus. KRaft was declared production-ready for new clusters in Kafka 3.3 (2022), and Kafka 4.0 (2025) removed ZooKeeper mode. The practical gains are one system to run, faster controller failover and room for more partitions per cluster.
When Kafka is the wrong tool
Choose Kafka for ordered event streams with several consumers, replay and high throughput. Do not choose it for a plain job queue with long or uneven tasks, per-message retries, delays or priorities, where a queue is simpler. It is heavy for small workloads. And it is not a database: you can read it by partition and offset, and not by any other query.
In the interview
Whenever you draw Kafka, say three things without being asked: the partition key and the ordering it gives you, the replication settings (factor 3, min.insync.replicas=2, acks=all), and how consumers scale (one group per consuming service, parallelism capped by partitions). Then note that delivery is at least once, so consumers must be idempotent. If you are asked for a partition count, calculate it from throughput and say why you cannot casually change it later.
Key takeaways
- A topic is a set of partitions, and each partition is an ordered, append-only log. Order is guaranteed within a partition only.
- The record key picks the partition, so choose the key to match the ordering you need and watch for hot keys.
- Replication factor 3, min.insync.replicas=2 and acks=all survive one broker failure without losing acknowledged writes or refusing new ones.
- Within a consumer group each partition has one reader, so the partition count caps parallelism and extra consumers sit idle.
- Rebalances move partitions when group membership changes. Slow processing that exceeds max.poll.interval.ms is a common self-inflicted cause.
- Retention deletes by time or size; compaction keeps the latest record per key. Neither depends on whether anyone has read the data.
- KRaft replaced ZooKeeper for cluster metadata; ZooKeeper mode was removed in Kafka 4.0.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What ordering does Kafka guarantee?
Records in one partition are read in the order they were appended. There is no ordering across partitions, so per-entity order needs a per-entity key.
What is the ISR?
The in-sync replicas: the leader plus the followers that are caught up with it. A record is committed, and visible to consumers, once every in-sync replica has it.
What is the standard configuration for not losing acknowledged writes?
Replication factor 3, min.insync.replicas=2, producer acks=all, unclean leader election disabled. It tolerates one broker failure with no loss and no write outage.
What caps the parallelism of a consumer group?
The number of partitions. Each partition is assigned to exactly one consumer in the group, so consumers beyond that number are idle.
What triggers a consumer group rebalance?
A consumer joining, leaving, missing heartbeats for session.timeout.ms, or exceeding max.poll.interval.ms between polls. Adding partitions or changing subscriptions also triggers one.
How does log compaction differ from retention by time?
Time retention deletes whole old segments regardless of content. Compaction keeps at least the newest record for each key, and a null-value tombstone removes the key.
Interview questions on this
- How would you guarantee that events for the same account are processed in order?
- How would you configure Kafka so that an acknowledged write is never lost, and what does that cost?
- Consumer lag on a topic has been growing for an hour. How do you investigate and fix it?
- A consumer group rebalances every few minutes and throughput has collapsed. What is going on, and how do you fix it?