"Design Kafka" usually gets a box diagram back. Producers on the left, brokers in the middle, consumers on the right and ZooKeeper underneath. Each box is right. None of them says what lets one broker take hundreds of thousands of messages a second.
The first Kafka paper, published by LinkedIn's engineers in 2011, explains it. It compared Kafka with ActiveMQ and RabbitMQ. One Kafka consumer read 22,000 messages a second, more than 4 times either of the others.
The paper puts the gap down to bookkeeping. One of ActiveMQ's busiest threads spent most of the producer test in a B-tree that held each message's state, and both other brokers kept the delivery state of every message. Kafka's broker kept no state for any message. A consumer's progress was one number, and the consumer kept it.
A broker that scales keeps no state per message. It keeps a few numbers per partition, per producer and per reader, and leaves the rest to the disk and the network.
Every hard part of this design is a feature that seems to need state for each message. Finding a message seems to need an index entry for it. Knowing it was copied seems to need a flag on it. Dropping a retried send seems to need a record of every message that arrived, and a consumer's progress seems to need a mark on each one. The design turns each of these into a few numbers that don't grow with the message count.
One feature can't become a number: the per-message acknowledgement that a work queue needs. For that one, the design keeps state only for the messages in flight.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
A distributed message queue is a cluster of servers, called brokers, that accepts messages from producers, keeps them on disk and hands them to consumers. A producer sends "order 4471 placed" and returns to its own work. Later, any number of consumers read it.
Three kinds of system go by this name, and each one is built differently.
- A work queue, such as Amazon SQS or a RabbitMQ queue. The broker tracks each message until one consumer acknowledges it, and then deletes it.
- A partitioned log, such as Kafka, Amazon Kinesis or Redpanda. The broker appends messages and keeps them. Each reader keeps its own position.
- Something beside a broker, such as a fanout service like Amazon SNS, a task library like Celery, or a stream processor like Flink.
We're building the second one, and offering the first one's per-message acknowledgement as a mode on top of it. Message queues vs event streams covers which of the two an application should use. This page builds the broker underneath both.
Functional requirements
Core:
- Publish to a topic. A producer sends messages to a named topic. Messages that share a key are read in the order they were sent.
- An acknowledgement is a promise. Once a producer is told a message is written, losing a broker or a whole availability zone doesn't lose it. A retried send isn't written twice.
- Read in groups, and replay. Each consumer group reads every message in a topic, and shares the work among its members. A group can rewind to any message that's still kept.
- Queue-style delivery for work. A group can instead take messages one at a time, acknowledge each one, and get it again after a timeout. After a number of failed attempts, a message stops being delivered and goes to a dead-letter topic. This mode gives up order.
- Retention. A topic keeps messages for a set time or size. A compacted topic keeps the latest message for each key, with no time limit.
Out of scope, deliberately:
- Choosing a queue or a log for an application. Message queues vs event streams covers it.
- Delayed and scheduled delivery, such as "send this at 9 am". That's the distributed job scheduler.
- Stream processing: joins, windows and counts computed from the log.
- Pushing messages to HTTP endpoints or phones. Push notification delivery covers phones.
- Schemas, authentication and quotas per tenant.
Non-functional requirements
- Scale. 500 MB a second of messages on average, at about 1 KB each, so 500,000 messages a second. At the course's peak of 5 times the average, 2.5 GB and 2.5 million messages a second. Three consumer groups read each message, on average. These are assumptions, for a cluster that a whole company shares.
- Durability. An acknowledged message survives the loss of any one broker or any one zone.
- Latency. A p99 under 50 ms from a send to a caught-up consumer receiving it, inside one region. The p99 is the latency that 99 percent of messages beat.
- Availability. Losing a broker or a zone doesn't stop producers or consumers.
- Retention. 7 days by default, which is also Kafka's default. Compacted topics keep their latest values with no time limit.
For a sense of scale, LinkedIn reported 7 trillion messages a day on more than 4,000 brokers in 2019. In 2025 it reported more than 32 trillion records and 17 PB a day, on more than 10,000 machines.
Non-functional requirements 1 and 5 carry the design together. Seven days at 500,000 messages a second is 302 billion messages, and any state the broker keeps for each one is multiplied by that count.
The question is whether the broker can afford to keep anything for each message. 1 KB messages, kept 7 days, read by 3 groups. Messages kept 500,000/s × 604,800 s ≈ 302B State for each message and group, 32 bytes, assumed 302B × 3 groups × 32 B ≈ 29 TB Random writes to keep that state, at peak per message: insert, 3 deliveries, 3 acknowledgements, 1 delete = 8 2.5M/s × 8 = 20M/s NVMe drives, course figure 100,000 to 200,000 random writes/s, so take 150,000 20M / 150,000 ≈ 133 The log instead, at peak 2.5 GB/s × 3 copies = 7.5 GB/s NVMe drives, course figure 3 GB/s sequential 7.5 / 3 = 2.5 ───────────────────────────────────────────────────────── Per-message state needs about 50 times the drives, before it is copied to a second zone. So the broker appends, and everything it tracks has to be counted per partition, per producer or per reader, never per message.
The set up
Core entities
- Topic. A named stream of messages, such as
orders. - Partition. One ordered, append-only log that holds part of a topic, kept on three brokers. The partition is the only interesting entity. It's the unit of order, of parallel reading, of copying and of placement, and its count is hard to change.
- Record batch. The messages, called records, that a producer sends together for one partition, compressed together. The broker stores and serves the batch still compressed.
- Offset. A record's position in its partition: 0, 1, 2 and up. A consumer group's progress is one committed offset for each partition.
- Producer session. A producer ID and an epoch, a number that goes up each time the producer restarts, plus a sequence number for each partition it writes to.
How do clients talk to the brokers?
Three options, from the simplest to the one Kafka uses.
An HTTP request per message. It's easy to call from anything. At peak that's 2.5 million requests a second, each with its own headers and round trip, and the producer waits on every one.
The broker pushes to consumers. The broker sends each message as it arrives. Kafka's design documentation names the problem: the broker then sets the rate, so a consumer that falls behind gets overwhelmed instead of catching up later.
Consumers pull, over long-lived connections, in batches. A consumer asks for "everything from offset 8,812,000, up to 1 MB, and wait up to 500 ms if there's nothing yet". The wait is a long poll, so an idle consumer doesn't spin. A pull carries its starting offset, so rewinding means asking for an older one, which the 2011 paper notes is much easier to support with pull than with push.
Take the third. It costs a thick client library, which has to know the binary protocol, find each partition's leader and build batches. Producers use the same connections and batching.
System interface
Produce topic=orders partition=7 acks=all
producer_id=4071 producer_epoch=3 base_sequence=1200
batch: 50 records, zstd, 31 KB
→ ok base_offset=8812040
→ error NOT_ENOUGH_REPLICAS -- retryable
→ error OUT_OF_ORDER_SEQUENCE
Fetch topic=orders partition=7 offset=8812000
max_bytes=1 MB max_wait=500 ms
→ ok high_watermark=8812090
the batches holding offsets 8811990 to 8812089
OffsetCommit group=billing orders/7 → 8812090
ShareFetch group=email-sender topic=orders
→ ok records 8812040 to 8812089, locked for 30 s,
delivery_count=1
ShareAcknowledge group=email-sender
8812040 to 8812061 ACCEPT
8812062 RELEASE
8812063 REJECT
Three things to note.
The batch is the unit. The producer ID, epoch and sequence number are on the batch, not on each message. The broker gives the batch a range of offsets and stores it still compressed.
A fetch stops at the high watermark. Section 2 defines it. A consumer never reads past it, so it never reads a record that a failover could take back. The fetch returns whole batches, so the consumer drops the records before the offset it asked for.
Only queue mode acknowledges single records. A consumer group commits one number for each partition. A share group, the queue mode from requirement 4, accepts, releases or rejects records one by one. That's the only per-message call in the protocol, and section 4 limits what it costs.
All of that is the data plane. The control plane creates topics, places partitions on brokers, and decides which copy of each partition leads. A small group of controller nodes owns that metadata, and every broker keeps a copy of it in memory. If the controllers are down, produce and fetch carry on with the leaders they have. But a failed leader can't be replaced, and an in-sync set can't shrink, so acks=all writes stall on any partition whose follower dies meanwhile.
High-level design
1. Publish: where does a message go, and how is it stored?
A producer has a record and a topic. It needs a partition, and then a broker.
The producer picks the partition itself. A record with a key goes to the partition the key's hash points to, so every record for order 4471 lands in one partition, in order. A record with no key goes to a "sticky" partition, which the producer switches only after it has filled a batch for it. Then the producer sends the batch straight to that partition's leader. Any broker can tell it which broker leads which partition, so there's no routing tier.
Batching sets the throughput. Kafka's producer collects up to 16 KB for a partition, or waits up to 5 ms, whichever comes first, and then sends. In the 2011 paper, batches of 50 messages took one producer from 50,000 to 400,000 messages a second, and nearly filled its 1 Gb link.
Which data store, and what actually forces it
The broker now has a batch for partition 7 and must keep it for 7 days. The first worksheet rules out per-message state, so the question is how to store a partition without any.
A database table with a row per message
It's tempting because it works on day one. Postgres can be a queue: a row per message, a status column, and SELECT ... FOR UPDATE SKIP LOCKED to hand rows to workers. An index finds any message, and a delete removes it.
At this scale it fails on writes. Each message costs an insert, a status update for each group, and a delete, which the first worksheet priced at 133 drives before a second copy. The deletes add their own cost: LSM trees vs B-trees shows a job queue in Cassandra failing on tombstones minutes after launch.
An append-only log, split into segment files
Each partition is a directory of files called segments. The broker appends every batch to the end of the newest segment, and nothing is ever written in the middle. Once a segment reaches 1 GB, the broker closes it and starts a new one. Closed segments never change.
Each segment is named after the offset of its first record. The broker keeps the list of names in memory, so finding the segment that holds an offset is a binary search. Inside a segment, a sparse index file holds one entry for about every 4 KB of records, mapping an offset to a byte position. A read finds the last index entry at or before the offset, and scans forward from there to the batch that holds it. The 2011 paper chose offsets over message IDs for the same reason: to avoid an index with one entry per message.
Writes are sequential, which a disk does at its full speed. Reads of recent data come from the operating system's page cache, the memory it uses to hold recently used parts of files. Consumers that are caught up read what producers just wrote, so the design documentation says they cause no disk reads at all.
What it costs. There's no lookup by message ID or by key, only by offset, or by time through a second index file that maps timestamps to offsets. And a single message can't be deleted. Old data leaves a segment at a time, which section 5 uses.
Store the producer's batch, and send it unchanged
Question the premise that the broker has to handle messages one at a time. The producer already compressed a batch. Kafka's design documentation says the broker decompresses it to validate it, for example to check that the record count matches the header. Then it writes the batch to disk still compressed, filling in only the header's base offset and leader epoch, and sends those same bytes to consumers. With the default compression.type, it never re-encodes a message on the hot path.
That makes zero-copy possible. Sending part of a file to a socket the ordinary way takes four steps. The kernel reads it into the page cache, copies it into the program, copies it back into a socket buffer, and sends it. The 2011 paper counts four copies and two system calls. Linux's sendfile call sends bytes from the page cache to the socket directly, which the paper says removes two of the copies and one of the calls.
What you give up. The broker can't filter or route single messages, because it serves byte ranges with sendfile instead of reading records out one by one. A consumer that wants a tenth of a topic still receives all of it. The largest message is set by the largest batch, about 1 MB by default. And reading old data pulls it into the same page cache, so a consumer replaying last week can push out the recent data that caught-up consumers were reading from memory.
So the partition log is the main data store. A few more hold the rest of the state, and none of them keeps an entry for every message.
| data store | what goes in it | what forces it |
|---|---|---|
| partition logs, segment files on each broker | record batches in offset order, with sparse offset and time indexes | 7.5 GB a second of copied writes at peak, and 907 TB kept, counting copies |
| metadata log, copied by Raft across 3 controllers | topics, partitions, leaders, in-sync sets, brokers | two answers to "who leads partition 7" would let two brokers accept writes |
__consumer_offsets, a compacted topic | each group's committed offset for each partition | one number per partition and group, written often and read after a restart |
__share_group_state, an internal topic | per-record state for share groups, for the records in flight | requirement 4, kept to the in-flight window |
| object storage, such as S3 | closed segments, for the days past local retention | 907 TB on broker disks would set the broker count (deep dive 2) |
The files on disk
/data/orders-7/
00000000000006697390.log -- batches, append-only, closed at 1 GB
00000000000006697390.index -- offset → byte position, every ~4 KB
00000000000006697390.timeindex -- timestamp → offset, for "rewind to Tuesday"
00000000000008388640.log -- the active segment, the only one written
00000000000008388640.index
00000000000008388640.timeindex
leader-epoch-checkpoint -- each leader epoch and its first offset
RecordBatch, the fields this design uses
baseOffset int64 -- offset of the first record, set by the broker
partitionLeaderEpoch int32 -- epoch of the leader that wrote it, set by the broker
producerId int64
producerEpoch int16
baseSequence int32
records [Record] -- compressed together
Three things to note.
A segment's name is its first offset. The list of names is the only index of segments, and it fits in memory. A record doesn't store its full offset, only its distance from the batch's base offset, in a byte or two.
The producer's identity is in the batch header. producerId, producerEpoch and baseSequence let the broker drop a retried batch without a table of message IDs. Deep dive 5 uses them.
Every batch records its leader's epoch. partitionLeaderEpoch and the leader-epoch-checkpoint file let a broker that comes back from a failure find exactly where its log stopped matching the leader's. Deep dive 3 uses them.
The operations that carry the product
-- 1. Produce, at the partition leader
append(batch):
if batch.producerEpoch < producers[batch.producerId].epoch:
return FENCED -- an older copy of this producer
if batch.baseSequence matches one of that producer's last 5 batches:
return that batch's base offset -- a retry, so append nothing
if batch.baseSequence != last sequence + 1:
return OUT_OF_ORDER_SEQUENCE
if acks = all and in-sync replicas < min.insync.replicas:
return NOT_ENOUGH_REPLICAS
give the batch offsets log_end to log_end + count − 1
write it to the active segment -- page cache, no fsync
add an index entry for each ~4 KB written
if acks = all: wait until every in-sync replica has fetched past it
return base offset
-- 2. Fetch, at the leader, or a follower in the consumer's zone
fetch(offset, max_bytes, max_wait):
segment = last segment whose name ≤ offset -- binary search
position = last index entry ≤ offset, then scan to its batch
if offset = high watermark: wait up to max_wait for new data
sendfile(segment, position, up to max_bytes, ending at the high watermark)
-- 3. Commit, at the group's coordinator
commit(group, partition, offset):
append (group, partition) → offset to __consumer_offsets
wait until every replica of that partition has it
update the coordinator's table in memory
Operation 2 runs most often. Every byte written is fetched by two followers and three consumer groups, so fetches move five times the bytes that produces do. Operation 1 is the one an interviewer pushes on, usually by asking what happens if the leader dies after the append and before the acknowledgement. Section 2 and deep dive 5 answer that.
2. When is a message safe to acknowledge?
Requirement 2 promises that an acknowledged message survives losing a broker or a zone. The leader just wrote it to its page cache without a flush to disk, so on its own the leader promises nothing. Kafka accepts that on purpose. Write-ahead logs explains why: the design documentation says requiring an fsync on every write could cut performance by two to three orders of magnitude, so durability comes from copies on other brokers instead.
The copying works like reading. Each follower fetches from the leader exactly as a consumer does, starting from the end of its own log. Each fetch therefore tells the leader how far that follower has got. The leader tracks which followers are in sync: caught up to the end of its log within the last 30 seconds, the default for replica.lag.time.max.ms. These replicas, the leader included, form the in-sync replica set, or ISR.
The producer's acks setting picks how long the leader waits before it answers. So the question is how many copies make a message safe, and which ones.
Acknowledge when the leader has it
With acks=1 the leader answers as soon as the batch is in its page cache. It's the fastest option. The 2011 paper's producer didn't wait at all, and the paper accepts the risk for log data where losing a few messages is fine.
For requirement 2 it fails when the leader dies. Any follower in the ISR can become leader, and a follower can be up to 30 seconds behind and still count as in sync. With the 12 brokers that deep dive 2 arrives at, each leading a twelfth of the partitions, a broker leads partitions taking about 208,000 messages a second at peak. A follower 1.5 ms behind loses about 300 acknowledged messages in a crash. One that is 30 seconds behind loses about 6 million.
A majority of three copies, as in Raft
Treat each partition as a Raft group of three replicas, as the key-value store does. A write is acknowledged once two of the three have it, and a new leader is elected by majority vote. The leader waits for the faster of its two followers, so one slow follower doesn't slow writes.
The cost is copies. A majority of 2f + 1 replicas survives f failures, as replication and leader election works out. Kafka's documentation says this directly: tolerating one failure takes three copies, and tolerating two takes five. Five copies of 7 days of this traffic would be 1.5 PB of disk instead of 907 TB.
Wait for the in-sync set, and vote only on who is in it
Question the premise that each write needs a majority vote. The vote decides who may lead after a failure. The data only needs to be on every replica that could become leader.
So the leader waits for every member of the ISR, not a majority of all replicas. With acks=all, the batch is acknowledged when every in-sync replica has fetched it. Only ISR members can be elected, and each one holds every acknowledged message, so f + 1 in-sync replicas survive f failures. While all three are in sync, three copies survive two failures with no loss. The ISR itself still needs agreement, so every change to it is written to the metadata log, which the controllers copy by majority vote (deep dive 6).
A shrinking ISR needs a floor. min.insync.replicas=2 makes the leader refuse an acks=all write when fewer than two replicas are in sync. With three replicas in three zones, every acknowledged message is then in at least two zones.
The floor is the part that's guaranteed. A message acknowledged while the ISR is down to two sits on two copies, the same as in a Raft group of three, so the floor guarantees surviving one failure. The third copy adds a second only while it keeps up. Kafka's documentation makes the same point: to tolerate f failures, both designs wait for the same number of acknowledgements.
The high watermark is where this shows. It is the offset just past the last record that every ISR member holds. The leader moves it forward as follower fetches arrive, sends it to the followers, and serves consumers only below it.
What you give up. Every acknowledgement waits for the slowest in-sync follower, not the fastest. A follower that slows down but keeps up within 30 seconds holds back every write to its partitions until it recovers or drops out.
The question is whether waiting for the followers is expensive enough to skip. The course's figure for a round trip between zones is 1.5 ms. producer waits to fill a batch, linger.ms up to 5 ms producer to leader, maybe another zone 0.75 ms leader appends to its page cache ~0 ms followers fetch the batch and ask for more 1.5 ms leader to producer 0.75 ms ───────────────────────────────────────────────────────── acks=all about 3 ms + linger acks=1 about 1.5 ms + linger Waiting for both followers adds one round trip between zones, 1.5 ms. acks=1 saves that and can lose up to 30 seconds of acknowledged messages, so take acks=all.
3. Read in groups: who reads which partition, and where is progress kept?
A consumer group shares a topic's partitions among its members, one member per partition. One broker acts as the group's coordinator. It tracks the members, decides when the assignment must change, and stores the group's progress.
Progress is one number per partition, the offset of the next record to read. In the 2011 paper, consumers wrote it to ZooKeeper. Today the coordinator appends each commit to __consumer_offsets, an internal compacted topic, and confirms it only after every replica of that topic's partition has it. Compaction keeps only the latest commit for each group and partition. The coordinator also holds the latest offsets in memory, so a restarted consumer gets its position without reading the topic.
Replay needs nothing extra. A group that resets its offset to an earlier one reads the same records again, and the time index turns "Tuesday at 09:00" into an offset.
The hard part is changing who reads what. Members join, leave and crash, and each change moves partitions. A rolling deploy shows the cost. Take a group of 100 consumers reading 1,000 partitions, 10 each, restarted one at a time. Each restart triggers two rebalances, one as the consumer leaves and one as it rejoins.
Eager: everyone gives up everything, then the group reassigns
This was the original protocol, and it's simple to reason about. On any change, every member stops, gives up all its partitions, and rejoins. The coordinator picks one member to compute a new assignment, and everyone starts again.
Each rebalance stops all 1,000 partitions. A deploy of 100 consumers runs 200 rebalances, so 200,000 partition hand-overs, and the whole group stops reading 200 times.
Cooperative: give up only what has to move
Incremental cooperative rebalancing, from KIP-429, keeps every partition that isn't moving. A KIP is a Kafka Improvement Proposal, the design document behind a major change to Kafka. A member gives up only the partitions the new assignment takes from it, and the rest keep being read. A restart now moves about 10 partitions as the consumer leaves and 10 as it rejoins. The deploy moves about 2,000 partitions instead of 200,000.
The cost is that the group still waits together. KIP-848 lists the problems that remain. The protocol relies on a barrier the whole group must reach, so one misbehaving consumer can disrupt the whole group. And offsets can't be committed while a member waits at the barrier. The assignment is still computed in a client.
The coordinator assigns, and each member moves on its own
Question the premise that the group has to agree together. KIP-848 moves the assignment onto the coordinator, inside the broker. Each member heartbeats, and the heartbeat's reply tells it which partitions to give up and which to take. Members converge independently. A member whose assignment doesn't change isn't affected at all, and keeps reading and committing.
The deploy now moves the same 2,000 partitions, with no group-wide pause and no blocked commits. Epochs keep it safe: the group's epoch goes up with every change, and each member carries the epoch of the assignment it's working from, so a stale member is fenced. It became generally available in Kafka 4.0, in March 2025, and consumers opt in with group.protocol=consumer.
What you give up. The assignment logic now lives in the broker, so a custom assignor written for clients needs rework. A partition still moves, so its new owner restarts from the last committed offset and re-reads whatever the old owner had processed but not committed.
A deploy can also avoid most of these rebalances. With static membership, from KIP-345, each consumer sets a group.instance.id, and the coordinator removes it only when its session times out. A consumer that restarts and rejoins within that time causes no rebalance at all.
A rebalance that never ends is a different failure. A handler slower than max.poll.interval.ms is declared dead mid-batch, and its replacement does the same, which message queues vs event streams works through.
4. Queue-style delivery: per-message acknowledgement on a log
A consumer group commits a position, so it can't acknowledge record 501 while record 500 is still failing. Message queues vs event streams prices the first effect for the user: one slow record delays everything behind it. It also shows the second: a group can't use more consumers than there are partitions.
Requirement 4 asks for the opposite: each record handed to one worker, a lock that runs out, a count of attempts, and a place for records that keep failing. That's per-message state, the one thing the thesis rules out. So the question is how much of it to keep, and where.
A status for every message
Add a state to every record: available, delivered, acknowledged. It answers everything, including "show me every message that failed last week".
The first worksheet priced it for the whole cluster. For one topic of 5,000 messages a second kept 7 days, it's a state for each of 3 billion records, rewritten on every delivery and acknowledgement.
The consumer builds retries and a dead-letter topic
Leave the broker alone. A consumer that can't process a record copies it to a retry topic, commits past it, and carries on. A separate consumer reads the retry topic after a delay and tries again. After a set number of tries, the record goes to a dead-letter topic for a person to look at.
It needs no change to the broker, so it works on any Kafka cluster, and the broker keeps no per-message state. The cost is that each consumer team rebuilds a queue's features. A retried record leaves its key's order. Every retry is a full produce and a full fetch. And there's still no lock that runs out: a consumer that crashes mid-record leaves it for the next owner of the partition, which starts from the last commit.
Per-message state only for the records in flight
Question the premise that per-message state has to cover the whole log. A record needs a state only while a worker holds it. Before that, it's "not reached yet", and after it, it's "done". Neither needs a row.
Kafka's share groups, from KIP-932, do this. They have been production-ready since Kafka 4.2, in February 2026. For each partition, the broker that leads it keeps a start offset and an end offset. Everything below the start offset is done. Everything above the end hasn't been handed out. Only the records between them, the in-flight records, have a state: available, acquired, acknowledged or archived. A broker setting caps how many records a partition can have in flight.
A record handed to a worker is acquired, under a lock that lasts 30 seconds by default. The worker accepts it, releases it for another try, or rejects it. After 5 delivery attempts by default, the record is archived and never delivered again. Since Kafka 4.4, in October 2026, a rejected or archived record can also be written to a dead-letter topic, as a record that names it; copying its contents is a separate setting. Before that, it was skipped.
The state is small because the window is short. The partition's leader sends each change to a share coordinator, which writes it to the internal topic __share_group_state as a partial update rather than the whole state. KIP-932 notes that rewriting the whole state on every change would be a bottleneck.
What you give up. Records in a share group can arrive out of order, so this mode is for work where order doesn't matter. Each acknowledgement is an extra request, and a share group always reads from the partition leader, never a follower. And a group with every record locked by slow workers stops receiving new ones until locks are released.
The question is whether per-message state for the window is small enough to keep on the broker. An email-sending share group reads 5,000 messages a second, and holds each for at most the 30 s lock. 24 bytes of state per record: offset, state, attempt count and lock deadline, assumed. In flight at most 5,000/s × 30 s = 150,000 150,000 × 24 B ≈ 3.6 MB The same state for every message kept 5,000/s × 604,800 s ≈ 3.0B 3.0B × 24 B ≈ 73 GB ───────────────────────────────────────────────────────── The window is 20,000 times smaller than the backlog. Per- message state is affordable as long as it covers only what workers are holding.
Amazon SQS limits the same thing. A standard queue allows about 120,000 in-flight messages, and returns OverLimit beyond that. The cap is on messages being worked on, not on messages waiting, which is the same line share groups draw. RabbitMQ's documentation points anyone with a backlog over 5 million messages from its queues to its log, RabbitMQ streams.
5. Retention and compaction: how do messages leave?
Messages leave a whole segment at a time. A segment is deleted when its newest record is older than the retention time, 7 days by default, or when the partition is over its size limit. Deleting 1 GB costs one file deletion, and the broker doesn't look at a single message to do it.
A compacted topic keeps the latest record for each key instead. Background cleaner threads work on the partitions with the most uncleaned data, called the head. A cleaner builds a summary of the last offset for each key in the head. It then copies the older segments, dropping any record whose key appears later. Offsets never change and order is kept.
A record with a null value is a tombstone. It marks a key as deleted, and it stays for 1 day by default so that consumers see it before it goes. A consumer more than a day behind can miss a delete. Message queues vs event streams covers when a topic should be compacted.
Compaction is the one background job that reads every record's key and rewrites segments. Its memory is a summary with one entry per key in the head, not one per message.
Deep dives
Deep dives 1, 3 and 4 come up in most versions of this interview.
1. How many brokers, and what actually needs scaling?
Brokers have three limits: network, disk bandwidth and disk space. Size each one.
The question is what sets the broker count. Each broker has a 25 Gbps network card, planned at 60% busy, and a 16 TB EBS gp3 volume filled to 75%. Peak is 2.5 GB/s in. card, each way 25 Gbps / 8 bits ≈ 3.1 GB/s planned at 60% 3.1 × 0.6 ≈ 1.9 GB/s usable disk 16 TB × 0.75 = 12 TB Network, at peak in, producers + copies 2.5 + 2 × 2.5 = 7.5 GB/s out to followers 2 × 2.5 GB/s = 5.0 GB/s out to 3 groups 3 × 2.5 GB/s = 7.5 GB/s out in total = 12.5 GB/s brokers, out binds 12.5 / 1.9 ≈ 7 Disk space, 7 days a day 500 MB/s × 86,400 s ≈ 43.2 TB 7 days, 3 copies 43.2 × 7 × 3 ≈ 907 TB brokers 907 / 12 ≈ 76 Disk bandwidth, at peak, on 76 brokers written 2.5 GB/s × 3 copies = 7.5 GB/s per broker 7.5 GB/s / 76 ≈ 100 MB/s a gp3 volume includes 125 MiB/s, about 131 MB/s fits ───────────────────────────────────────────────────────── The network needs 7 brokers and the disks need 76. Space sets the size of the cluster, ten times over.
The 60 percent plan matches capacity planning: if one zone of three fails, the other two carry its load at 90 percent. The disks are EBS gp3 volumes, as in the course's cost example, and at 76 brokers each volume's 100 MB/s of writes fits inside the 125 MiB/s gp3 includes.
LinkedIn's numbers point the same way. 7 trillion messages a day on 4,000 brokers is about 20,000 messages a second per broker, on average. 17 PB a day on 10,000 machines in 2025 is about 20 MB a second each, under 1 percent of the 25 Gbps card assumed here.
The other cost is bytes between zones. Every partition has a copy in each of three zones, so most bytes cross a zone boundary at least once.
The question is whether the zone traffic matters next to the disks. The course's price is $0.01 a GB out plus $0.01 in, so $0.02 a GB. Producers, leaders and consumers are spread evenly over 3 zones. Produced a month 500 MB/s × 2.63M s ≈ 1,315,000 GB Bytes between zones, per GB produced producer to leader, 2 times in 3 0.67 GB leader to its 2 followers 2.00 GB 3 groups reading the leader, 2 times in 3 each 2.00 GB total 4.67 GB a month 1,315,000 × 4.67 × $0.02 ≈ $123,000 Consumers reading a replica in their own zone total 0.67 + 2.00 = 2.67 GB a month 1,315,000 × 2.67 × $0.02 ≈ $70,000 ───────────────────────────────────────────────────────── Reads in the consumer's own zone save $53,000 a month. Copying to followers costs about $53,000 a month too, and that part stays: it is the price of surviving a zone.
KIP-392 is the fix. A consumer names its zone in client.rack, and the brokers set replica.selector.class to pick a replica by zone, since the default always picks the leader. Followers serve only records below the high watermark, so a consumer reading a follower sees the same records, a little later. The cost page works the same sum for a smaller pipeline, and finds the zone traffic at 73 percent of the bill.
Share groups can't fetch from a follower, because their per-record state lives with the partition leader. So the $70,000 assumes all three groups are consumer groups. Each share group reading this traffic adds back 0.67 GB per GB produced.
2. Retention past the broker's disk
907 TB on broker disks sets the cluster at 76 brokers, ten times what the network needs. And most of those bytes are days old, read only when a group replays. So where should the retained bytes live?
Buy the disks
Run 76 brokers, or fewer brokers with bigger disks. It needs no new parts.
76 brokers cost 76 machines' worth of CPU and memory that the traffic doesn't use. Fewer, bigger brokers make recovery slow. KIP-405 notes that recovering or rebalancing a broker takes time in proportion to the data it holds. At 9 brokers, each holds about 100 TB, and copying that onto a new broker at an assumed 500 MB a second takes 56 hours.
Short retention, plus an archive job
Keep 1 day in Kafka, and run a sink job, such as a Kafka Connect connector, that copies each topic to object storage. The ad click aggregator archives its events this way.
It's cheap and it's common. The cost is that the archive is a second system. A group that needs to replay three days must read files in S3 through a different API, with no offsets, and run a second version of its consumer to do it.
Tiered storage: the log continues in object storage
Question the premise that the broker's disk holds the retention. With tiered storage, from KIP-405, the broker copies each segment to object storage once it closes, with its indexes. The local copy stays for a short local retention, set by local.retention.ms, and the topic's normal retention covers both tiers. A fetch for an old offset still goes to the broker, which reads it from object storage. Offsets, the API and the consumer don't change.
Segments are what make this work. Closed segments never change, so each one is uploaded once, as a 1 GB object. The request charges stay small, which wouldn't be true of objects the size of single messages. S3 keeps its own copies across zones, so the remote tier holds one copy.
What you give up. A replay from S3 is slower than a read from local disk. Tiered storage doesn't support compacted topics. And it was only marked production-ready in Kafka 3.9.
The question is what tiering saves. gp3 is the course's
$0.08 per GB-month, billed on the 16 TB each broker
provisions, not on the bytes used. S3 is $0.023. Local
retention is 1 day.
All local
provisioned 76 × 16 TB = 1,216 TB
a month 1,216 TB × $0.08 ≈ $97,300
brokers, by disk = 76
Tiered
local, 1 day 43.2 TB × 3 copies ≈ 129.6 TB
brokers, by disk 129.6 / 12 ≈ 11
brokers, by network, with S3 uploads
(12.5 + 2.5) / 1.9 ≈ 8
brokers, 4 in each of 3 zones = 12
gp3 a month 12 × 16 TB × $0.08 ≈ $15,400
S3 a month 302.4 TB × $0.023 ≈ $7,000
total ≈ $22,300
disk writes per broker 7.5 GB/s / 12 ≈ 625 MB/s
─────────────────────────────────────────────────────────
Tiering cuts the storage bill by more than three quarters
and the cluster from 76 brokers to 12. Each gp3 volume now
needs extra throughput provisioned, under its 2,000 MiB/s
limit. The zone traffic, at $70,000 a month, is now the
larger bill.3. What happens when a broker dies?
Take the tiered cluster: 12 brokers, 4 in each zone, each leading a twelfth of the partitions.
The controllers notice first. Each broker heartbeats to them, and one that stops is fenced: the active controller removes it from the brokers that may lead partitions. For each partition it led, the controller picks a new leader from the ISR and writes the change to the metadata log.
Brokers pull the change, and clients that get an error refresh their metadata and retry. The ISR of each affected partition shrinks to two, which still meets min.insync.replicas=2, so writes carry on.
A second failure, in another zone, can leave some partitions with one in-sync replica. Those partitions refuse acks=all writes and keep serving reads. Nothing acknowledged is lost, because the last in-sync replica holds all of it.
That holds until the last one crashes too. It may have held the newest records only in its page cache, so it can restart without them and still be elected leader, and the other replicas then truncate to match it. KIP-966's eligible leader replicas close this gap, and they are on by default for clusters created on Kafka 4.1 or later.
If every in-sync replica is gone, there are two choices. Wait for one to come back, with the partition unavailable until then. Or elect a replica that wasn't in sync, which brings the partition back and throws away every acknowledged message that replica never received. Kafka's documentation calls this a trade between availability and consistency, and has waited for an in-sync replica by default since version 0.11.
A broker that comes back has to cut its log back to where it last matched the leader. It asks the leader where its last leader epoch ended, using the epochs stored in every batch and in leader-epoch-checkpoint, and truncates to that offset. Then it fetches from there, and rejoins the ISR once it catches up. Kafka used the high watermark for this cut until KIP-101 found it could lose or mismatch data after some failovers.
If a broker's machine dies but its gp3 volume survives, a new machine attaches the volume and only catches up. If the volume is lost too, the new broker copies its local data, about 10.8 TB here, from the other replicas of each partition. At an assumed 500 MB a second that's 6 hours. The copies come from many brokers at once, so no single broker carries the load.
4. How many partitions?
A topic's partition count sets three things: how many consumers in a group can work at once, how fast one key can go, and how much the cluster has to track. Jun Rao, one of Kafka's original authors, gave the starting formula in 2015. Divide the topic's target rate by what one partition can do for producers, then by what it can do for consumers, and take the larger answer.
Take an orders topic with a peak of 100 MB a second. One partition takes tens of MB a second from producers, according to that post, so assume 10. Each consumer writes every record to a database and handles 2,000 records of 1 KB a second, so 2 MB a second. That gives 100 / 10 = 10 partitions for producers and 100 / 2 = 50 for consumers. Take 50, then plan for the topic's life: three times the traffic means 150.
Plan it now, because the count can only go up, and going up moves keys. The producer picks a partition from the key's hash and the partition count. Going from 4 partitions to 6, a hash modulo 4 and modulo 6 agree for only 4 values in every 12, so two keys in three change partition. A moved key's old records stay in the old partition while new ones go to the new one, so a consumer can read them out of order.
Consistent hashing would move a third of the keys instead of two thirds, but any key that moves can be read out of order, so it doesn't remove the problem. Partitioning and sharding gives the general answer: choose a large count once, and never change it.
Too many partitions cost something too. Each one means open files on three brokers, a share of every follower's fetch requests, and entries in the metadata. In 2019, LinkedIn reported slow controllers and controller failures from memory pressure on clusters with more than 140 brokers and 1 million replicas.
One key can't use more than one partition, because its records have to stay in order. A key that needs more than one partition's rate has to be split by the producer, for example by account and day. The consumer then gets order only within each part.
5. Producers: retries, duplicates and transactions
A producer sends a batch, the leader appends it, and the acknowledgement is lost on the way back. The producer retries. Without help, the batch is now in the log twice.
The idempotent producer fixes this with per-producer state. The broker gives each producer an ID and an epoch, and the producer numbers its batches for each partition. The leader remembers the last five batches from each producer for each partition. A batch whose sequence matches one of those is a retry, so the leader returns the original offset and appends nothing.
A batch that skips a number is refused, so retries can't reorder records. That's why idempotence allows at most five requests in flight per connection. Kafka's producer turns it on by default.
The leader can also die after the append and before the acknowledgement. The sequence numbers travel in the batch headers that followers copy, so a new leader rebuilds the same per-producer state from its own log. A retry that reaches it after the failover is still recognised.
Its limit is the session. A producer that restarts gets a new ID, so it can't recognise its own earlier sends. Deduplication across restarts needs an ID the application chooses, which idempotency and exactly-once delivery covers.
Transactions extend this to several partitions. A producer with a transactional.id writes to several partitions, and can commit the consumer offsets of what it read, all in one transaction. Consumers set to read_committed see none of it until the commit.
The transactional.id survives a restart, and a restart raises the epoch, so the broker aborts the old instance's open transaction and refuses its writes. Confluent measured the cost in 2017, with 100 ms transactions of 1 KB messages. Throughput was 3 percent lower than a producer using acks=all with one request in flight, and 20 percent lower than one using acks=1.
The guarantee stops at Kafka. A consumer that writes to a database is outside the transaction, so message queues vs event streams and idempotency and exactly-once delivery both send it to idempotent writes, an outbox or change data capture.
6. Where does the metadata live? ZooKeeper against KRaft
The metadata is small and per partition: topics, partitions, which brokers hold each one, the leader, the ISR and its epoch. It has to be agreed, because two answers to "who leads partition 7" would let two brokers accept writes.
In the 2011 paper, ZooKeeper held it, along with consumer offsets and which consumer owned which partition. Later, one broker was elected controller. It held the metadata in memory, kept it in ZooKeeper, and pushed changes to the other brokers. KIP-500 lists what went wrong. A newly elected controller loaded all the metadata from ZooKeeper before it could act, so failover took longer as partition counts grew. And the state in ZooKeeper often didn't match the controller's memory.
KRaft replaced it. Three or five controller nodes form a Raft group over a metadata log, as quorums, Raft and Paxos describes, and the leader of that log is the active controller. Standby controllers already hold the log, so a new active controller doesn't reload anything.
Brokers fetch new entries from the log instead of having them pushed. Separately, each broker sends a BrokerHeartbeat request to the active controller, which grants it a time-limited lease, and a broker whose lease runs out is fenced. KRaft has been production-ready since Kafka 3.3, and Kafka 4.0, in March 2025, removed ZooKeeper.
The thesis applies here too. The metadata is per partition, never per message, so one Raft group can hold it. Its limit is the partition count. LinkedIn's 2025 post on Northguard, its newer log storage system, names Kafka's single controller and single replicated state machine as the bottleneck, under strain at millions of partition replicas. Northguard splits the metadata itself across many Raft groups.
7. Multi-region: mirror, don't stretch
Some topics need a copy in a second region. There are two ways to get one.
Stretch one cluster across regions. Put a replica of each partition in each region. Every acks=all write then waits for a round trip between regions, under 30 ms to a nearby one and about 70 ms across the US, according to latency numbers. That's 10 to 50 times the 1.5 ms the requirements were built on, on every write.
Run a cluster in each region and mirror between them. Each region's producers write to their own cluster. A mirroring process, such as Kafka's MirrorMaker 2, consumes from the other region and produces locally. Kafka's documentation recommends running it beside its target cluster, because consumers cope with a slow, unreliable link better than producers do.
Take the second. A mirrored topic gets a prefix with its source region, so orders from us-west becomes us-west.orders in us-east. Two regions can then mirror each other without copying a record back.
Offsets don't carry over, because the target assigns its own. MirrorMaker 2 writes checkpoints that map a group's committed offset in the source to an offset in the target. Checkpoints are written now and then, and only offsets the mirror recorded can be translated. So a group that moves regions resumes at or a little before where it was, and reads a few records again.
So a mirrored topic is a full copy in each region, not a split. Writes land in the producer's own region.
The first cost is cross-region transfer, at the course's $0.02 a GB: mirroring 100 MB a second is about 263 TB a month, or about $5,300. The second is data. A region that fails loses whatever the mirror hadn't copied yet. So the recovery point is the mirror's lag at that moment, as multi-region and disaster recovery explains for any asynchronous copy.
8. How do you know it is working?
During an incident you need four answers quickly: are writes being refused, is any partition short of copies, are consumers keeping up, and is one broker or partition running hot.
- Partitions under their minimum in-sync count, and offline partitions. Both mean refused writes. Under-replicated partitions, with fewer in-sync copies than replicas, are the warning that comes before.
- Produce latency at p99, and
NOT_ENOUGH_REPLICASerrors. A rise in latency with no errors usually means one slow follower holding back its partitions. - Consumer lag per group, in seconds. Lag in records means nothing without a rate, as message queues vs event streams argues.
- Bytes in and out per partition, and disk reads per broker. Caught-up consumers cause no disk reads, so a jump usually means a group replaying old data and pushing recent data out of the page cache.
- Archived records per share group. Those are the messages that failed five times.
Label metrics by topic, partition and group, never by key or producer ID. A label value is a time series of its own, and a key can have millions of values, which observability warns against.
Final design
One message, end to end:
- The producer finds the partition from the key's hash, adds the record to a batch, and compresses the batch when it reaches 16 KB or 5 ms. Any broker tells it which broker leads that partition.
- The producer sends the batch to the leader with
acks=all, its producer ID, epoch and sequence number. The leader drops a retry by its sequence and refuses the write if fewer than two replicas are in sync. Otherwise it appends the batch to the active segment in its page cache. - Followers in the other two zones fetch the batch and ask for the next offset. When every in-sync replica has it, the leader moves the high watermark past it and acknowledges the producer.
- A consumer in group
billinglong-polls a follower in its own zone and gets bytes up to the high watermark, sent from the page cache withsendfile. - The consumer processes the records and commits its offset to the group's coordinator, which appends it to
__consumer_offsets. - A worker in share group
email-senderfetches from the partition's leader, which locks the same record for 30 seconds. The worker accepts it, and the leader sends the change to the share coordinator, which writes it to__share_group_state. A record that fails five times is archived, and can go to a dead-letter topic. - At 1 GB the segment closes and is copied to S3. The broker deletes its local copy after a day, and retention deletes the S3 copy after 7 days.
- If a broker stops heartbeating, the controller quorum fences it, picks new leaders from each ISR and writes them to the metadata log. MirrorMaker 2 copies chosen topics to the second region.
The numbers behind the shape: 500 MB a second on average, kept 7 days and copied three times, needs 907 TB. So space sets the cluster at 76 brokers, until tiered storage cuts it to 12. Acknowledging in two zones costs about 1.5 ms. Bytes between zones, $70,000 a month with consumer groups reading in their own zone, cost about three times the $22,300 of storage. And the only per-message state in the design is the in-flight window of the share groups, a few megabytes.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
Breadth matters more than depth at this level, and it's fine to be led.
You should split a topic into partitions, explain that order holds within a partition, and keep three copies of each partition on different brokers. You should know that a consumer group shares partitions and that each group keeps its own offsets, so a second group reads the same messages.
You aren't expected to raise the high watermark, rebalance protocols or tiered storage without being asked. You are expected to answer "the leader dies right after acknowledging a message, is it lost?" with something about waiting for followers.
Senior
You drive the structure, and three things should come up without prompting.
The storage layout. Segments, a sparse index and the page cache, and why the broker never keeps an index entry per message. Without them nothing explains the throughput.
When a message counts as written. acks=all, a minimum of two in-sync replicas and the high watermark. Requirement 2 rests on them, and they cost one round trip between zones.
The sizing, with the binding constraint named. Network, disk bandwidth and disk space computed separately. Space binds ten times over, and that's the case for tiered storage.
Two things are disqualifying: a database row per message at this scale, and claiming three replicas make data safe without saying what the producer waits for.
Staff+
A correct design is still the bar. A staff+ answer also decides what not to build.
Name the state per message, and remove it. Every feature becomes a number per partition, per producer or per reader, and the sizing shows why.
Separate the data's copies from the vote. Wait for the in-sync set on the data, and keep majority agreement for the metadata. Three in-sync copies survive two failures, and the floor of two guarantees one.
Keep per-message state to the in-flight window. Size it as rate times lock time, and point to SQS's in-flight cap as the same limit.
Move retention off the brokers. Tiered storage takes the cluster from 76 brokers to 12, and the zone traffic becomes the larger bill.
Be able to say what you would not build. No per-message status table on the broker. No custom deduplication service when the idempotent producer and an application key cover it. No cluster stretched across regions. No unclean leader election turned on cluster-wide. No partition count chosen for today's traffic on a keyed topic. A team could spend a quarter on any one of these.
Sources
The figures about real systems come from these, read for this page. Traffic, sizes and prices for this design are assumptions or the course's working numbers, shown in the worksheets where they're used.
- Kreps, Narkhede and Rao, Kafka: a Distributed Messaging System for Log Processing, NetDB 2011. Segments, offsets,
sendfile, pull over push, and the benchmark against ActiveMQ and RabbitMQ. - Apache Kafka documentation: design, producer, topic and broker settings, offset tracking, the record batch format and geo-replication. Batch validation, the ISR, f + 1 against 2f + 1, unclean election, no
fsyncper write, and every default quoted here. - Kafka Improvement Proposals: KIP-500 and KIP-631 on KRaft and broker heartbeats, and KIP-833 on KRaft being production-ready in 3.3. KIP-405 on tiered storage. KIP-345, KIP-429 and KIP-848 on rebalancing. KIP-932 on share groups and their leader-only reads. KIP-101 on leader epochs, and KIP-966 on eligible leader replicas. KIP-392 on fetching from the closest replica, and KIP-382 on MirrorMaker 2. KIP-497 on ISR changes during a controller outage. Eligible leader replicas, on by default for new clusters since 4.1.
- Kafka release announcements: 4.0, March 2025, for the removal of ZooKeeper and KIP-848's general availability; 4.2, February 2026, for share groups being production-ready; and 4.4, October 2026, for their dead-letter topics.
- Confluent: Narkhede and Wang, Exactly-once semantics are possible, 2017, for sequence numbers kept in the replicated log and the 3 and 20 percent costs of transactions. Jun Rao, How to choose the number of topics/partitions, 2015, for the partition formula and the tens of MB a second one partition takes.
- LinkedIn Engineering: How LinkedIn customizes Apache Kafka for 7 trillion messages per day, 2019, and Introducing Northguard and Xinfra, 2025. The cluster, broker, partition and message counts, controller memory pressure, the single controller as a bottleneck, and Northguard's metadata split across Raft groups.
- Amazon: the SQS visibility timeout page, for the in-flight limit of about 120,000 and
OverLimit, and the EBS gp3 page, for the 125 MiB/s included and the 2,000 MiB/s ceiling. - RabbitMQ, quorum queues, for the advice to use streams for backlogs over 5 million messages.