GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Distributed Message Queue (Kafka)

Keep a million messages a second so three teams can each read every one, keep one order’s events in order, survive a broker losing power, store a retried publish once, make a crash assign one courier instead of two, and deploy the readers without stopping every order. Built one step at a time, with experiments you can run.

A distributed message queue keeps messages from the services that write them until the services that need them read them, each at its own pace. This design is a replicated log, the way Apache Kafka works. A topic is split into partitions, and each partition is a file that only grows: a new message goes on the end, and each group of readers keeps one number per partition, the position of the next message it will read. A message’s key picks its partition, so all of one order’s events stay in one file, in order. Each partition has three copies. The leader confirms a write only when every copy that is keeping up has it, and refuses writes when fewer than two are keeping up. A producer tags every batch with its ID and a sequence number, so a retry is stored once. A reader records each event’s ID in the same database transaction as its effect, so a crash repeats reading without repeating the effect. When readers come and go, only the partitions that must change hands pause. Old messages are removed a whole file at a time after seven days.

Difficulty: Hard. Reported in interviews at Anchorage Digital, Amazon, Ethos, Opal Security. Also asked as Design Kafka, Design a pub/sub system, Design a message broker, Design SQS.

How do you design a distributed message queue?

A message queue sits between a service that has something to say and the services that need to hear it. The checkout service of a food delivery app says “order O-8812 was placed” once. The queue keeps that message. The kitchen, the courier dispatcher and the analytics warehouse each read it when they are ready. The checkout service does not wait for any of them, and does not need to know they exist. A distributed queue does this across many machines, for a million messages a second, and keeps every message it accepted when one of those machines dies. Apache Kafka, Amazon SQS and RabbitMQ are the ones most people have used.

  1. Publish: Placed O-8812. Checkout publishes at 19:02:00. The reply can be lost, and a retry must be stored once.
  2. Stored: Partition 41. Copied to every in-sync broker, at least two, before checkout hears “stored”.
  3. Kitchen: New order, 2 pizzas. Three teams read the same event, each at its own pace.
  4. Dispatch: Courier: Kwame. A crash halfway through a batch must not send a second courier.
  5. Replay: Analytics, last week. Next Tuesday, analytics reads last Friday again after fixing a bug.
One event, start to finish. The platform carries a million of these a second at its peak.

Picture Friday at 19:02. Elif orders two pizzas. The checkout service saves her order, O-8812, and publishes one message: placed. The pizzeria’s tablet must show the order within seconds. Dispatch must find a courier, and picks Kwame. Analytics counts the order tonight for the weekly report. Thirty seconds later Elif changes her mind and cancels, and that is a second message about the same order.

Interviewers like this problem because the first answer, a table of messages in a database, works on a laptop. It then fails at scale in ways a candidate can reason about out loud. Most versions of the question say “design Kafka” or “design a distributed message queue”. Both mean the same thing: the storage, the copies and the readers of a system like Kafka.

Here is the design in brief. Messages are grouped into topics, such as orders. Each topic is split into partitions, and each partition is a log. A log is a file where a new message is only ever added at the end. Every message has a number, its offset, that says where it sits. The partitions are spread over many machines called brokers, and each partition has copies on three of them. A reader belongs to a consumer group, and a group divides a topic’s partitions among its members. It remembers, for each partition, the offset of the next message it will read. Messages stay for seven days, whether anybody has read them or not.

The rest of this page is about the moments that design has to survive.

The first is the broker that loses power. It told the checkout service that Elif’s order was stored, and 3 ms later its power supply failed. The other two copies were 20 ms behind. Her order now exists nowhere. The kitchen never sees it, and nobody gets an error, because checkout was told it was safe.

The second is the reader that crashes. Dispatch assigns Kwame to Elif’s order, then crashes before it records how far it has read. Its replacement starts from the last position it did record, reads Elif’s order again, and assigns a second courier.

What is the interviewer testing?

Most candidates reach a working answer quickly: producers, a broker that stores messages, consumers that read them, and replicas for safety. That answer is right, and a mid-level answer often stops there.

The interviewer then pushes on what that answer takes for granted. Three teams need every message, and one of them wants to read last week again. One order’s events must arrive in order, while a million messages a second need many machines. A machine can die between storing a message and copying it. A producer that gets no reply cannot tell whether its message was stored. A reader can crash in the middle of its work, and readers come and go all the time. A senior answer uses a partitioned log with an offset per group, keys messages by the thing whose order matters, and waits for in-sync copies before confirming. A staff answer also explains why retries and crashes cannot duplicate an effect, and how a group changes members without stopping.

Spend most of the deep-dive time on partitions, replication and consumer offsets. Producer retries and rebalancing are the usual follow-ups, and the storage question comes first when the interviewer asks why not a database. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

A log that keeps messages, or a queue that hands out jobs?
Assume a log. Several teams read every message, and a team may read old messages again. A job queue, where each message goes to one worker and is deleted once done, is a different product; the follow-ups show how it changes the design.
How much, and for how long?
Assume a million messages a second at the peak, across every team, about 1 KB each, kept for seven days.
What must a confirmed message survive?
Assume any one broker failing, including losing power with no warning. Losing a whole region is a follow-up.
Does order matter, and does a message arrive once?
Assume order matters within one key, such as one order’s events, and not across keys. Assume a reader may see a message twice after a crash, and that no effect may happen twice. Ask whether the interviewer wants exactly once; the offsets deep dive says what that can honestly mean.

Functional requirements

On the board: Functional requirements
1. Publish to a named topic, with a key
2. Groups read every message, at own pace
3. In order per key
4. Read again from any point in 7 days
out: delays, priorities, per-message acks

Say it, don’t write it: Reading a message must not change it, or the second team never sees it.

Two kinds of service use the queue. Producers, such as checkout, publish messages. Consumers, such as the kitchen, dispatch and analytics, read them. Each consumer is a group of processes that share the work.

  1. Publish a message to a named topic, with an optional key, such as the order ID.
  2. Let any number of consumer groups read every message of a topic, each at its own pace, with the processes of one group sharing the work.
  3. Deliver the messages of one key in the order they were published.
  4. Let a group move back and read again from any point in the last 7 days.

Out of scope

  • Delayed messages, delivered at a set time
  • Priorities between messages
  • Acknowledging and retrying one message at a time, as a job queue does
  • Searching messages by content
  • Copying topics to another region

Non-functional requirements

On the board: Non-functional requirements
• 1M messages a second at peak, 1 KB each
• Confirmed = survives any one broker dying
• Publish confirmed in p99 < 100 ms
• Kept 7 days, even if nobody reads it
• No message stored twice by a retry

Say it, don’t write it: A million a second times 1 KB is 1 GB a second, before any copies.

  • About 1,000,000 messages a second at the peak, across every topic, averaging 1 KB.
  • A message is confirmed only once it would survive any one broker failing.
  • A publish is confirmed within 100 ms at the 99th percentile.
  • Messages are kept for 7 days, whether or not every group has read them.
  • A producer’s retry never stores a message twice, and a consumer’s crash never repeats an effect.

One number is worth working out now, because it sets the size of everything else. A million messages a second at 1 KB each is 1,000,000 × 1 KB = 1 GB a second coming in. The rest of the numbers appear in the deep dive that needs them. They are illustrative interview targets, not measurements of any real company.

Core entities

On the board: Core entities
Topic(name, partitions, retention)
Partition = log; message at an offset
Message(offset, key, event ID, value)
Group offset(group, partition) → next
Producer(id, epoch, seq per partition)

Say it, don’t write it: The broker keeps the messages; each group keeps only a number per partition saying where it is.

Follow Elif’s placed event through the records. Checkout publishes it to the topic orders with the key O-8812. The topic has 120 partitions, and the key picks one: partition 41. There the event gets the next offset, 4,210,337, and it keeps that number for as long as it exists.

The event itself holds its offset, its key and the time it was written. It also carries an event ID that checkout gave it, and its value: the order in JSON, about 1 KB. The dispatch group has one row of progress for partition 41: next offset 4,210,338, meaning it has handled everything before that. The kitchen has its own row for the same partition, and so does analytics. Checkout, as a producer, has an ID the broker gave it, and a sequence number for each partition it writes to. The producer deep dive shows what those are for.

RecordWhat it holdsWhy it is separate
TopicName, number of partitions, how long to keep messagesThe unit a team publishes to and reads from
PartitionAn ordered log of messages, with copies on three brokersThe unit of order, of storage and of parallel reading
MessageOffset, key, headers such as the event ID, value, timeNever changed after it is written
Group offsetGroup, partition, next offset to readProgress belongs to the reader, so reading changes nothing in the log
Producer stateProducer ID, epoch, last sequence number per partitionLets the broker recognise a retry

The one distinction that matters: a message belongs to the log, and progress belongs to the group. Nothing a reader does changes the log. So one message can be read by any number of groups, and read again.

API

On the board: API
produce(topic, key, value) → partition, offset
fetch(topic, partition, offset, max_bytes)
   → messages[]
commit(group, partition, offset, generation)
join(group, topics) → my partitions

Say it, don’t write it: Consumers pull from an offset they choose, so a slow reader slows only itself.

Clients talk to brokers over long-lived TCP connections with a binary protocol, not HTTP, because a busy producer sends thousands of requests a second on one connection. The calls look like this.

CallReturnsWhy it looks like this
metadata(["orders"])For each partition, the broker that leads itClients send each request straight to the partition’s leader
produce("orders", batch of messages for partition 41, producer_id, seq){partition: 41, base_offset: 4210337}Messages travel in batches, one request per broker holding a batch per partition, and the sequence number marks a retry
fetch("orders", 41, offset=4210338, max_bytes=1 MB)The messages from offset 4,210,338 on, up to 1 MBThe reader says where it is, so the broker keeps nothing per reader
join("dispatch", ["orders"])The partitions this member reads, and a generation numberThe group divides partitions among whoever is alive
commit("dispatch", 41, 4210338, generation=12)OK, or rejected if generation 12 is overProgress is saved per group, and an old member cannot overwrite it

Three details are there on purpose. The producer learns which broker leads each partition and sends there directly, so no router sits in the middle of a million messages a second. The fetch names its own offset, so the broker does not track what each reader has seen. And the commit carries a generation number, which the rebalancing deep dive explains.

Step 1: publish, and read at your own pace

Checkout publishes “placed O-8812” to the topic orders. The broker appends it to the end of the topic’s log and gives it the next offset. The kitchen, dispatch and analytics are three consumer groups. Each asks the broker for messages from its own offset onward, handles them, and saves its new offset. Nothing is deleted when a group reads it. A message older than seven days is deleted by the broker, however far each group has got.

The interactive version of this example is available when JavaScript loads.

Consumers pull rather than being pushed to. A broker that pushed would have to know how fast each reader can go. When a reader is slow, pulling means it asks less often, and falls behind without harming anyone else. A fetch that finds nothing new waits at the broker, up to half a second by default, for data to arrive, so pulling is not a busy loop. The first deep dive shows why a log, and not a table, is the right thing to store.

Step 2: partitions, spread over brokers

One log on one machine cannot take 1 GB a second. So the topic is split into partitions, and the partitions are spread over the brokers. A producer hashes the message’s key to pick a partition: every message with the key O-8812 goes to partition 41. It sends the message to the broker that leads partition 41, which it learned from a metadata request.

A consumer group splits the partitions among its members. The dispatch group has 80 members and 120 partitions, so each member reads one or two. Within a group, a partition is read by exactly one member at a time. A group coordinator, one of the brokers, keeps track of who is in each group. It has one member work out who reads which partition, and it stores each group’s offsets.

The interactive version of this example is available when JavaScript loads.

Order holds within a partition, because a partition is one log. Across partitions nothing is ordered, and nothing needs to be: two different orders do not care which was placed first. The partitions deep dive shows what goes wrong with any other way of choosing a partition.

Step 3: three copies of every partition

Each partition is stored on three brokers. One copy is the leader, which takes every write and serves every read. The other two are followers, which fetch new messages from the leader, the same way a consumer does, and append them to their own copy. A controller, a small group of three machines that agree with each other through the Raft protocol, keeps the list of brokers and which one leads each partition. When a leader dies, the controller picks one of its followers to take over. Clients learn of the change the next time they ask which broker leads a partition. The controller runs the brokers; the group coordinator from step 2 runs the consumer groups.

The interactive version of this example is available when JavaScript loads.

With steady traffic this already works. The deep dives take it through six moments: three teams that need the same message, an order cancelled before it is placed, a broker that loses power, a reply that never arrives, a reader that crashes halfway through a batch, and a deploy at dinner time.

Three teams need every message. Why not keep messages in a database table?

At the Friday peak the platform takes 1,000,000 messages a second from every team, about 1 KB each. Follow one of them. At 19:02:00 checkout publishes “placed O-8812”, Elif’s order. Three teams need it. The kitchen shows it on the pizzeria’s tablet. Dispatch finds a courier. Analytics counts it tonight, and next Tuesday it will count last Friday again, because someone will find a bug in last week’s report.

The first answer many candidates give is a table. Each message is a row. A consumer takes the oldest row nobody has claimed, marks it claimed, handles it and deletes it. On a laptop this is a fine queue. PostgreSQL’s documentation offers SELECT … FOR UPDATE SKIP LOCKED for exactly this, to avoid lock contention “with multiple consumers accessing a queue-like table” (PostgreSQL). It is also the right tool when a job must be created in the same transaction as the data it is about. Count the writes at the peak. Every message is inserted, then updated when a consumer claims it, then deleted. That is three row writes, and each one changes the table, changes its index and goes into the database’s own log. So 1,000,000 × 3 = 3,000,000 row writes a second, on the one database that holds the table.

The delete has a second cost. Dispatch claims O-8812’s row, handles it and deletes it. The kitchen never sees it, and neither does analytics. A table of jobs hands each message to one reader, because the first reader removes it.

The obvious repair gives each team its own copy. Checkout writes three rows, one per team, or a fan-out step copies every message into three queues. That is how Amazon SNS feeding three SQS queues works, and for a few teams that never need old messages it is a sound design. Now every team sees every message. The writes triple: 1,000,000 × 3 teams × 3 row writes = 9,000,000 a second. A fourth team adds a fourth full copy. And next Tuesday analytics still cannot read last Friday, because its copy was deleted when it was read.

Both attempts rest on one assumption: that reading a message changes it. Drop the assumption. Keep the messages in a file, in the order they arrived, and never change a message once it is written. A new message goes on the end. Its position in the file is its offset, a number that only grows, so Elif’s placed event is 4,210,337 forever.

A team, a consumer group in Kafka’s terms, does not mark messages as read. It remembers one number: the offset of the next message it will read. The kitchen is at 4,210,342, dispatch at 4,210,338 and analytics at 4,210,333, all in the same file. Reading changes nothing in the file. A fourth team costs one more number. Next Tuesday, analytics sets its number back to last Friday’s first offset and reads forward. That file is a log, and the numbers are the only thing the teams own. The full design splits each topic into partitions, as step 2 did, and each partition is a log like this one with its own offsets. Elif’s event sits in partition 41.

The log gives up one thing the table had. A group cannot delete or retry a single message on its own, so one message that always fails holds up its partition. The follow-ups show how to handle that.

A log is also what a disk does best. A write at the end of a file is sequential: the disk never has to find a place in the middle of the table and the index. Kafka’s own design notes make this their first principle. On an array of six 7,200 rpm disks they measured linear writes at about 600 MB a second. Random writes managed “only about 100kB/sec”, “a difference of over 6000X” (Kafka design).

Old messages leave in bulk. Each partition’s log is cut into segment files of 1 GB. When the newest message in a segment is older than seven days, the broker deletes the whole file. Nothing is ever deleted one message at a time.

Now work out what seven days costs. The platform takes 1 GB a second at the peak, so a day at that rate is 1 GB × 86,400 = 86.4 TB. The peak does not last all day, so this is an upper bound, which is the safe way to size disk. Seven days is 604.8 TB. Three copies, which the replication deep dive needs, make it 1,814.4 TB, about 1.8 PB. A broker that gives 30 TB of disk to the log means 1,814.4 ÷ 30 = 60.48 brokers, so at least 61. Plan on 64, so that when one dies the other 63 hold 1,814.4 ÷ 63, about 28.8 TB each, and still have room to rebuild its copies. Check the network before settling on 64. Two followers each copy the full 1 GB, so the cluster takes in 3 GB a second: 1 GB from producers and 2 GB of copies. Each broker takes its share: 3 GB ÷ 64, about 47 MB a second. Say an average message is read by three groups. Then the cluster sends out 3 GB a second of reads and 2 GB a second to followers. Each broker sends its share: 5 GB ÷ 64, about 78 MB a second. A 10 Gbit/s network card moves 1.25 GB a second. So disk decides how many brokers there are, and the spare network capacity goes to teams that replay. A replay reads old data from disk rather than memory, though, and competes for it with everyone else. So replays are capped with a quota: a limit on the bytes a second one client may fetch.

Three more habits make the log fast. First, most readers want messages a few seconds old, and the operating system still has those in memory, in its page cache. So a fetch at the head of the log reads memory, not disk. Second, the broker hands the file’s bytes straight to the network socket through a system call such as sendfile, without copying them through its own memory first. Third, producers send batches. A producer waits a few milliseconds, 5 by default since Kafka 4.0, and collects the messages for each partition into a batch. It then sends one request to each broker. That request holds a batch for every partition the broker leads. The broker writes each batch with one append, and a reader fetches it back with one read. A batch can also be compressed, which cuts disk and network alike.

One question is left: how does a fetch for offset 4,210,338 find its place in a 1 GB segment? Each segment file is named after the first offset it holds. The broker finds the right file by binary search over the names. Beside each segment sits a small index that records the byte position of an offset every 4 KB or so. A binary search of the index lands within 4 KB of the message, and a short scan finds it.

The experiment follows Elif’s event three ways. The tabs are a table that deletes a row when it is read, a table with a copy per team, and one log with an offset per team.

The interactive version of this example is available when JavaScript loads.

The gap: Three teams need every message, and one of them needs to read old messages again.

Option 1: A table, delete when read

Insert a row per message; a consumer claims the oldest row, handles it and deletes it.

Works when: One team, a modest rate, and jobs created in the same transaction as their data.

Breaks when: Each message reaches one reader, and a million messages cost 3,000,000 row writes a second.

Option 2: A copy per team

Copy every message into one queue per team, and each team deletes from its own.

Works when: A few teams that never need to read old messages again.

Breaks when: A fourth team adds a fourth full copy, 9,000,000 row writes a second for three, and nothing can be replayed.

Option 3: One log, an offset per team (start here)

Append every message to a partitioned log and keep one offset per group; delete whole segments after seven days.

Works when: Always, at this size.

Watch for: A group cannot retry one message on its own, so a message that always fails holds up its partition.

In the interview: Open with the log and say why: reading must not change the message. Do the storage arithmetic, 86.4 TB a day and 1.8 PB for seven days with three copies, and round the broker count up. Mention the page cache and batching if the interviewer asks why it is fast.

Say this: Each topic is a log: messages are appended and never changed, and each consumer group keeps one offset per partition. So any number of groups can read every message, and a group can go back and read again. Old data leaves a whole segment at a time after seven days, which at 1 GB a second is about 1.8 PB with three copies, or 64 brokers.

Elif cancels, and a courier still comes. How do you keep one order’s events in order?

At the dinner peak the app takes 1,000 orders a second. Each order produces six events over its life: placed, accepted by the restaurant, courier assigned, picked up, delivered, receipt sent. That is 6,000 events a second on the topic orders. Dispatch spends 10 ms on an event: it reads the couriers near the restaurant, picks one and writes the assignment. One dispatch process, working on one event at a time, therefore handles 1,000 ms ÷ 10 ms = 100 events a second. Keeping up with 6,000 takes 6,000 ÷ 100 = 60 processes, each busy every moment, with nothing spare to clear a backlog after a pause. So dispatch runs 80, each busy three quarters of the time: 80 × 100 = 8,000 a second of capacity, 2,000 more than arrives. A topic with a single partition would keep every event in order, and would cap each group at one reader, 100 events a second.

Within a group, one partition is read by one member. So 80 dispatch processes need at least 80 partitions. The topic has 120, so the group can grow by half before it runs out. Each partition then carries 6,000 ÷ 120 = 50 events a second. The question is which partition each event goes to.

The first answer spreads events evenly: the first to partition 1, the next to partition 2, and so on, round robin. Every partition gets the same load, which looks ideal. Now play Elif’s evening. At 19:02:00 her placed event lands on partition 7. Partition 7’s dispatch process has just restarted and is 40 seconds behind. At 19:02:30 she cancels, and the cancel lands on partition 12, whose process is 2 seconds behind. Dispatch reads the cancel at 19:02:32. It has never heard of O-8812, so there is nothing to cancel, and it moves on. At 19:02:40 it reads the placed event and assigns Kwame. Kwame rides to the pizzeria for an order that was cancelled ten seconds earlier.

Each partition kept its own messages in order. The trouble is that Elif’s two events went to two partitions, and nothing orders two partitions against each other.

The fix picks the partition from the key. The producer hashes the key, O-8812, and takes the remainder after dividing by 120, the number of partitions: partition 41. Every event with that key lands there, one after another in the order checkout published them. Replay the evening. The placed event and the cancel both go to partition 41. Its dispatch process reads the placed event at 19:02:02 and the cancel at 19:02:32, in that order. It calls Kwame back before he reaches the pizzeria. Kafka’s producer does exactly this, with a hash called murmur2. A message with no key goes to whichever partition the producer is filling a batch for at that moment, since nothing depends on its order.

The key has to be the thing whose order matters, and choosing it is the decision that counts. Suppose a team keys by city instead, so that all of one city’s events stay together. One big city makes 30% of all order events: 6,000 × 0.3 = 1,800 a second, all on one partition. One process reads a partition and handles 100 a second, so the partition falls behind by 1,800 − 100 = 1,700 events every second. That city’s rush started 32 minutes before Elif ordered, so her placed event joins a backlog of 1,700 × 32 × 60 = 3,264,000 events. At 100 a second it is read 32,640 seconds later, about 9 hours. The events arrive in perfect order, far too late to matter. A key is the unit of order, and also the unit of load: whatever shares a key shares one reader. The hot key guide covers the general problem. Here the answer is to key by order, which spreads the load over millions of keys.

Keying creates two new problems. The first is growth. Say the app doubles and the topic goes from 120 partitions to 240. A key’s partition is its hash modulo the count, so changing the count moves about half of all keys to a different partition. An order in progress at that moment has its old events in one partition and its new ones in another, and the order breaks for exactly those orders. Kafka’s documentation warns that after adding partitions “messages with the same key may be routed to different partitions”. It adds that Kafka “will not attempt to automatically redistribute existing data” (Kafka operations). So choose the count for a year or two of growth up front. Adding partitions to a keyed topic is a planned migration, not a dial. Consistent hashing moves fewer keys when servers change, but it does not help here: any key that moves still splits its history across two logs.

The second problem is inside the consumer. A dispatch process that reads partitions 41 and 42 might hand events to eight threads to go faster. Two threads could then take Elif’s placed event and her cancel at the same moment, and the cancel could finish first. The order the log kept is lost again, one step later. So a consumer that works in parallel hashes the key again to pick a thread, the same way the producer picked a partition. Events with one key then go to one thread, in order.

The log keeps events in the order they reach the partition. For one producer, that is the order it published them. Two services can also write events about one order, such as the restaurant accepting and dispatch assigning. Those are ordered by arrival, so a consumer that cares compares a version number inside the event.

The experiment sends Elif’s two events three ways. The tabs are round robin, keyed by order, and keyed by city.

The interactive version of this example is available when JavaScript loads.

The gap: A topic needs many partitions for throughput, and one order’s events must still be read in the order they were published.

Option 1: One partition

Put the whole topic in one log.

Works when: Fewer events than one reader can handle.

Breaks when: One member of each group reads it: 100 a second for dispatch, against 6,000.

Option 2: Round robin

Spread events evenly over the partitions.

Works when: Events that are independent of each other, such as page views.

Breaks when: Two events of one order land on two partitions, and a cancel can be read before its order.

Option 3: Key by the thing whose order matters (start here)

Hash the order ID to pick the partition, and hash it again to pick a thread inside the consumer.

Works when: Always, when order matters.

Watch for: A key with too much traffic overloads one partition, and adding partitions moves keys, so the count is chosen up front.

In the interview: Open by sizing the group: 6,000 events a second at 100 per process is 60 processes, and 80 leaves room to catch up. That needs at least 80 partitions, and 120 allows for growth. Then key by order ID and play the cancel. Mention the hot key and the partition count before the interviewer asks.

Say this: Order is kept within a partition, so I key each event by order ID. All of one order’s events then land in one partition, in the order they were published. Dispatch needs 60 processes at 100 events a second each and runs 80 to catch up after a pause. So the topic has 120 partitions, chosen up front because adding partitions moves keys. Inside a consumer, events are handed to threads by the same key.

A broker loses power 3 ms after it said a message was stored. Is the message gone?

Partition 41 lives on three brokers: broker 1 leads it, and brokers 2 and 3 follow. At 19:02:00.000 checkout sends Elif’s placed event. Broker 1 appends it at 19:02:00.002 and replies “stored”. At 19:02:00.005 broker 1’s power supply fails.

Whether Elif’s order survives depends on when broker 1 said “stored”. The fastest rule is to reply as soon as the leader has appended the message. Kafka calls this acks=1. The followers copy the message a moment later, when they next fetch. Look at the last eight messages on partition 41 at the moment of the failure. Broker 1 has all eight. Broker 2 has copied the first six, and broker 3 the first five. Elif’s placed event is the seventh. Checkout has been told that all eight are stored. The controller notices broker 1 is gone and promotes an in-sync follower. It takes the first one on the partition’s list, not the one with the most messages; say it is broker 2. Messages 7 and 8 exist nowhere. Had broker 3 been first on the list, message 6 would be gone too. Nobody gets an error: checkout was told they were safe, and dispatch never sees Elif’s order.

Across the whole platform it is not two messages. A broker leads a 64th of the partitions, so it takes 1,000,000 ÷ 64, about 15,625 messages a second. If its followers trail it by 20 ms, a leader that dies has confirmed 15,625 × 0.02, about 313 messages that no other broker has.

The opposite rule waits for every copy. The leader appends the message, waits until both followers have fetched it, and only then replies. Replay the power failure. Only messages 1 to 5 were on all three brokers, so only those were confirmed. Messages 6 to 8 were never confirmed, so checkout still has them and sends them again to broker 2, the new leader. Nothing is lost. Broker 2 already had message 6, so the resend would store it twice unless the leader can recognise a retry, which the producer deep dive adds.

Now play a different failure. Broker 3’s disk starts to stall, and it stops copying at message 5. Under “wait for every copy”, the leader cannot confirm message 6, or anything after it, until broker 3 catches up. Every partition that broker 3 follows stops taking writes, and checkout’s publishes wait. If broker 3 needs a new disk, that is hours. One slow disk has stopped every write that its machine was meant to copy.

Kafka’s answer sits between the two. The leader keeps a list of the followers that are keeping up, the in-sync replicas, and waits for every follower on that list, not for every follower. A message that every in-sync copy has is committed. That is Kafka’s word for safely stored, a different use from a consumer committing its offset, which comes later. Consumers are only ever given committed messages, so a reader never sees a message that a failover could take back. A follower that has not caught up for 30 seconds, the default for replica.lag.time.max.ms, is dropped from the list. Replay the stalled disk. For up to 30 seconds the leader waits for broker 3 and writes pause. Then broker 3 is dropped, the list is brokers 1 and 2, and writes continue with two copies. When broker 3 recovers, it copies what it missed and rejoins the list. The 100 ms target holds on a normal day; during those 30 seconds it is broken for every partition broker 3 follows. A publish that waits the full 30 seconds also meets the producer’s own 30-second request timeout and is sent again. Kafka’s documentation says that timeout “should be larger than replica.lag.time.max.ms” to reduce duplicates (Kafka producer configs), and the producer deep dive makes a resend safe. Teams that cannot accept the pause lower the lag limit, and pay for it by dropping followers during short hiccups.

The list can shrink too far. If broker 2 also falls behind, the list is only broker 1, and “every in-sync copy” means one copy: acks=1 again, without anyone having chosen it. So the topic also sets min.insync.replicas to 2. Its default is 1, so this is a choice you have to make. When fewer than two copies are in sync, the leader refuses writes with an error, and checkout knows its message was not confirmed. If the list shrank after the leader had appended, the message may still be in the log, which is one more reason a retry must be recognised. Checkout can retry later or hold the order. The platform gives up some availability to keep its promise. The producer asks for all of this with acks=all, the default in current Kafka versions. Kafka’s documentation names this exact setup as the typical one: “a replication factor of 3, set min.insync.replicas to 2, and produce with acks of "all"” (Kafka broker configs).

Two more rules make the promise hold. When a leader dies, the controller only promotes a follower that is on the in-sync list, because only those are sure to have every committed message. Promoting a follower that fell behind is called unclean leader election. It brings the partition back sooner, and it throws away the committed messages that follower never had, so it is off by default. And the three copies go on three different racks, or three availability zones, so that one power failure cannot take two of them.

Kafka does not write each message to the physical disk before it replies. It writes to the operating system, which flushes to disk a little later, and relies on the copies on other machines instead. Its documentation recommends leaving the flush to the operating system and letting replication provide durability. That is safe only because the three copies sit on independent power. A rack that loses power under all three copies at once could lose the last few messages.

A different family of systems waits for a majority rather than for the in-sync list. With three copies, the leader replies once any two have the message, so a slow third copy never delays a write. Redpanda and RabbitMQ’s quorum queues replicate each partition or queue with Raft this way, and Kafka uses Raft for its own controller. The cost is that each partition runs its own election protocol. To survive f failures a majority system also needs 2f + 1 copies, where an in-sync list keeps committed messages through f failures with f + 1. At three copies, both designs keep taking writes when one broker dies, and the difference that remains is the pause while a stalled follower is dropped. The leader and follower replication guide walks the same trade for databases, and database failover covers promoting a new leader safely.

The experiment plays the last eight messages on partition 41. Pick the failure, then the rule. The tabs are replying after the leader writes, waiting for every copy, and waiting for the in-sync copies with at least two.

The interactive version of this example is available when JavaScript loads.

The gap: A message confirmed by one machine is lost if that machine dies before the others copy it.

Option 1: Reply after the leader writes

The leader confirms once it has appended the message (acks=1).

Works when: Data you can afford to lose a little of, such as metrics.

Breaks when: A leader that dies loses what it confirmed and nobody copied: about 313 messages at 20 ms of lag.

Option 2: Wait for every copy

The leader confirms once all three copies have the message.

Works when: A partition whose brokers never slow down.

Breaks when: One stalled follower stops writes to every partition it follows, for as long as it is broken.

Option 3: Wait for the in-sync copies, at least two (start here)

Confirm once every in-sync copy has it, drop a follower that has not caught up for 30 seconds, and refuse writes below two.

Works when: Always, for data that must not be lost.

Watch for: A stalled follower pauses writes until it is dropped, 30 seconds by default, which teams often lower.

Option 4: Wait for a majority

Each partition runs Raft and confirms once two of three copies have the message.

Works when: Writes that must never pause for a stalled follower.

Watch for: Every partition runs its own election protocol, which is more for the cluster to run.

In the interview: Open with the power failure under acks=1 and count what is lost. Then give the in-sync rule its two halves: wait for the in-sync list, and refuse writes below two copies. Mention clean elections and copies in three zones. Offer the majority rule if the interviewer asks about the pause.

Say this: Each partition has three copies in three zones. A message counts as stored once every in-sync copy has it, with at least two in sync; otherwise the write is refused. So no confirmed message lives on only one machine. A follower that has not caught up for 30 seconds leaves the in-sync list, so a sick broker pauses writes briefly instead of stopping them. Only an in-sync follower can become leader.

The reply to a publish is lost. Does the order go out twice?

At 19:02:00 checkout sends Elif’s placed event to partition 41. The leader appends it at offset 4,210,337 and sends back “stored”. A network switch between the two drops that reply. Checkout waits. After 30 seconds, the default request timeout, it has heard nothing.

Checkout cannot tell what happened. Either the request never arrived and nothing is stored, or it arrived, was stored, and only the reply was lost. From checkout’s side the two look identical: silence.

The first answer is not to retry, and to report a failure. When the request was lost, Elif’s order never reaches the log, and nobody makes her pizzas. When only the reply was lost, the order is stored, and checkout has just told Elif it failed, so she may order again. That is at most once: a message arrives once or not at all.

The second answer is to retry. When the request was lost, the retry stores the message, and all is well. When the reply was lost, the retry stores it again. Thirty seconds of traffic have gone by, so at 50 events a second the copy lands about 1,500 offsets further on. Now the log holds two placed events for O-8812. Dispatch may assign two couriers, and analytics counts two orders. That is at least once: a message arrives once or more. Retrying also breaks order. A producer keeps several batches in flight to one partition at a time, to keep the pipe full. Suppose batch 1 fails and is retried while batch 2 succeeds. Batch 2 is then stored before batch 1.

The fix lets the broker recognise a retry. When checkout starts, it asks a broker for a producer ID, say P9. From then on it numbers every message it sends to each partition, 0, 1, 2 and so on, and each batch carries the number of its first message. The leader remembers, for each producer ID, the last few batches it stored in each partition. Kafka keeps five, and a producer may have at most 5 batches in flight to one partition, so every batch it might retry is still remembered. The producer ID and sequence travel with the messages to the followers, so a new leader remembers them too.

Replay the lost reply. Elif’s batch is P9, sequence 17. The leader stores it at 4,210,337, and the reply is lost. Checkout retries the same batch, still P9, sequence 17. The leader sees that sequence 17 from P9 is already stored, stores nothing, and replies “stored at 4,210,337” again. Replay the lost request instead. Sequence 17 never arrived, so the retry is new, and it is stored. Either way the log holds Elif’s order exactly once.

The same numbers restore order. Say the next batch arrives while the one starting at 17 is still missing. The leader refuses it as out of sequence, and the producer resends both in order. Kafka calls this the idempotent producer, and it is on by default in current versions (Kafka producer configs).

The producer ID has a weakness. It belongs to one run of checkout. If checkout restarts, it gets a new ID, and a batch it sends again after the restart looks new. The Kafka proposal that introduced it says so plainly: it can “only guarantee idempotent production within a single producer session” (KIP-98). Kafka’s transactional producer gives checkout a stable name instead, its transactional ID, plus an epoch that goes up on every restart. When the new run registers, the broker fences off the old one: any batch still arriving from the old epoch is refused. So a checkout process that was paused rather than dead cannot wake up and write behind its replacement’s back. The epoch does not help the broker spot a resend, though. A batch the old run had already stored, sent again by the new run, is new to the broker. That copy is caught at the other end, by the consumer.

There is one more gap, and it sits before the queue. Checkout saves Elif’s order in its own database and then publishes. If checkout crashes between the two, the order exists and the event never does. The queue cannot repair this, because it never received anything. The fix is an outbox: the same database transaction that saves the order writes a row into an outbox table. A relay reads the outbox and publishes each row, and marks it sent once the broker confirms. The order and its outbox row commit together or not at all. The producer deep dive adds a relay that publishes from an outbox table. One relay must then work through each key’s rows in order, or several relays must split the rows by the same key hash. A relay that loses a reply and retries is caught by the producer ID. A relay that crashes after publishing a row, and before marking it sent, publishes it again after it restarts. That copy is caught by the consumer, in the next deep dive.

The interactive version of this example is available when JavaScript loads.

The experiment plays the publish three ways, for a lost reply and for a lost request. The tabs are giving up, retrying, and retrying with a producer ID and sequence number.

The interactive version of this example is available when JavaScript loads.

The gap: A producer that hears nothing cannot tell a lost request from a lost reply.

Option 1: Do not retry

Report a failure when no reply arrives.

Works when: Messages you can afford to lose, such as a click stream.

Breaks when: A lost request loses the order, and a lost reply reports a failure for an order that was stored.

Option 2: Retry

Send the same messages again until one attempt is confirmed.

Works when: Consumers that already ignore duplicates.

Breaks when: A lost reply stores the order twice, and batches in flight can land out of order.

Option 3: Retry with a producer ID and sequence (start here)

Number every message per partition; the leader skips a batch it already has and refuses one that skips ahead.

Works when: Always.

Watch for: The ID lasts one run, so a resend after a restart is stored again and the consumer must catch it.

Fix within it: A crash before publishing is fixed by an outbox.

In the interview: Open with the two silences that look alike, then give the fix its two parts: a producer ID from the broker and a sequence number per partition. Say that it also keeps batches in order. If the interviewer asks about the database, add the outbox.

Say this: A producer that hears nothing retries, so a retry must not store the message twice. Each producer gets an ID and numbers its messages per partition. The leader remembers the last five batches and skips a sequence it has already stored, which also keeps batches in order. Checkout writes each order and an outbox row in one transaction, and a relay publishes the outbox, so a saved order is always published.

Dispatch crashes after assigning a courier. Does a second courier come?

Dispatch reads partition 41 in batches. At 19:02:02 its process polls and gets eight events, offsets 4,210,334 to 4,210,341. Elif’s placed event is 4,210,337. The process works through the batch in order. It assigns couriers to the orders at 334, 335 and 336, then assigns Kwame to Elif’s order at 337 and sends him a notification. Then the machine it runs on is killed.

The group coordinator notices, and another process takes over partition 41. It starts from the group’s committed offset, the last position the group saved. Where that is depends on when the process saved it.

The first rule saves the position first. On every poll, the process commits the offset after the batch, 4,210,342, and then does the work. Replay the crash. The committed offset is 4,210,342, so the new process starts there. It never sees 4,210,338 to 4,210,341. Those four orders never get a courier. This is at most once, and in a delivery app it means food going cold on a counter. Some versions of this question ask for at most once on purpose, for messages where a repeat is worse than a gap, such as a push notification. Then committing first is the right answer, and the design has to say which messages it is allowed to drop.

The second rule does the work first and saves the position after. This is what Kafka’s consumer does by default: every 5 seconds it commits the offsets of the messages returned by the previous poll. Replay the crash. The last commit was 4,210,334, before this batch, so the new process starts there. It assigns couriers to 334, 335 and 336 again, and at 337 it assigns a courier to Elif’s order again. Kwame is already riding there, and now a second courier is too. Nothing was lost. This is at least once, and the work between the last commit and the crash has happened twice. Some work is safe to repeat as it is: marking an order cancelled twice leaves it cancelled. Assigning a courier is not.

No choice of when to commit fixes this, because the commit and the work are two writes to two systems. The assignment goes to dispatch’s database, and the offset goes to the queue. A crash between them always leaves one without the other.

The fix makes the work safe to repeat. Every event carries an ID, set by checkout when it writes the outbox row and kept in the message. Dispatch’s database gets a table of event IDs it has handled, with the ID as its primary key. In one transaction, dispatch inserts the event’s ID and writes the courier assignment. The insert is written to skip a duplicate key. If the ID is already there, it adds no row, which means the event was handled before, so dispatch skips it and moves on.

Replay the crash one more time. The new process starts at 4,210,334 and reads Elif’s placed event again. Its ID is already in the table, because it was committed in the same transaction as Kwame’s assignment. So dispatch does nothing, and Kwame is the only courier. The queue delivered the event twice. The effect happened once, because the database made it happen once. The idempotency guide covers the same pattern for APIs.

A related way keeps the offset in the same place. Dispatch stores its own position for each partition in its database, in the same transaction as the assignments, and on start-up tells the consumer where to begin. The position and the effect can then never disagree. That catches a replay after a crash. It does not catch a copy a producer stored twice, which sits at its own offset; the event ID catches both.

The event ID table must keep an ID for as long as the event can come back: at least the seven days the log keeps it. Dispatch reads all 6,000 order events a second, so a week is 6,000 × 604,800, about 3.6 billion IDs. Partition the table by day and drop a whole day at a time. Dispatch also has a cheaper key of its own, because an order has at most one courier. A unique constraint on the order ID in the assignments table does the same job for assignments. Use the natural key when there is one, and an event ID table when there is not.

A replay on purpose is different again. When analytics moves its position back to recount last Friday, skipping known IDs would skip the whole replay, and adding would count Friday twice. So analytics recomputes Friday’s totals and overwrites them, keyed by day. Idempotent means the same result every time, not always skip.

The notification to Kwame is the part no local transaction covers, because it leaves the building. Sending it straight after the commit leaves a gap: a crash between the commit and the send means the replay skips the event and Kwame is never told. So the same transaction also writes an outbox row, the notification to send. A sender delivers each row and marks it sent. A sender that crashes between the two sends it again, and Kwame sees the same notification twice, which is harmless. An effect that is not harmless twice, such as charging a card, needs more: the sender passes an ID to the payment provider as an idempotency key, and the provider recognises the resend.

Parallel work brings back the commit problem in a new form. Say a process handles offsets 10, 11 and 12 on three threads. 10 and 12 finish; 11 is still running. The committed offset means “everything before this is done”, so the process may commit 11, not 13. Committing 13 would tell a replacement that 11 was finished. A consumer that works in parallel tracks which offsets have finished and commits only up to the first gap.

The interviewer may now ask about exactly once. Kafka’s transactions can make one step exactly once when the whole step stays inside Kafka. The step reads from one topic, writes to another and commits the offset, all in one transaction. The offsets themselves are stored in Kafka, in an internal topic called __consumer_offsets, which is what lets them join the transaction. Dispatch’s database and Kwame’s phone are outside that boundary. Messages from a transaction that was cancelled, or aborted, stay in the log, and consumers skip them only if they set isolation.level=read_committed; the default reads everything. So a correct answer names the boundary: delivery is at least once, and the effect is once because the effect is idempotent. The distributed transactions guide explains why no protocol stretches one transaction across the queue and a database for free.

The interactive version of this example is available when JavaScript loads.

The experiment plays dispatch’s crash three ways. The tabs are committing before the work, committing after it, and recording the event ID in the same transaction as the work.

The interactive version of this example is available when JavaScript loads.

The gap: The work goes to one system and the offset to another, and a crash can land between them.

Option 1: Commit, then work

Save an offset just past the batch, then handle it.

Works when: Messages where a repeat is worse than a gap, such as a push notification.

Breaks when: A crash skips the rest of the batch: four orders with no courier.

Option 2: Work, then commit

Handle the batch, then save the offset, as the default consumer does every 5 seconds.

Works when: Work that is safe to repeat as it is, such as marking an order cancelled.

Breaks when: A crash repeats everything since the last commit: a second courier for Elif.

Option 3: Work and record the event ID together (start here)

Insert the event’s ID and write the effect in one transaction; skip an ID already there; commit the offset afterwards.

Works when: Always, for effects that must happen once.

Watch for: Keep IDs at least seven days, send outside effects from an outbox with an idempotency key, and commit only up to the first unfinished offset.

In the interview: Open with the crash under the default consumer, which repeats work, and say that the commit and the effect are two writes. Then make the effect idempotent with an event ID in the same transaction. If the interviewer says exactly once, name the boundary it covers.

Say this: Delivery is at least once: the offset is committed after the work, so a crash repeats reading from the last commit. The effect happens once because dispatch writes each event’s ID in the same transaction as the courier assignment and skips any ID it has already seen. Exactly once inside Kafka exists for read, write and commit within Kafka; for a database it comes from the effect being idempotent.

The interactive version of this example is available when JavaScript loads.

The code has three tabs: the producer’s settings, the leader’s sequence check, and a consumer that records event IDs with its effects.

Dispatch deploys at dinner time. Why does every order stop?

At 19:05 on the same Friday, the dispatch team deploys a fix. The group has 80 processes reading 120 partitions, one or two each. The deploy restarts them one at a time, restarting the next one every 30 seconds. Each takes 20 seconds to stop and start again.

Every time a process leaves or joins, the group has to agree again on who reads which partition. That is a rebalance. The original rebalance protocol is simple, and it stops everyone. The coordinator tells every member to stop and give up all its partitions. Each member finishes the batch in hand, commits, and rejoins. One member, picked by the coordinator, computes a fresh assignment, and everyone starts again with their new partitions. The round lasts as long as the slowest member takes to finish its batch. A batch is up to 500 events, the default for max.poll.records, at 10 ms each: up to 5 seconds, during which nobody in the group reads anything.

Count the deploy. Each of the 80 processes causes two rebalances, one when it leaves and one when its replacement joins: 160 rebalances. Each stops all 120 partitions for up to 5 seconds. That is up to 160 × 5 = 800 seconds, over thirteen minutes, during which no order in the whole app gets a courier. Those minutes are spread over the 40 minutes of the deploy, at the busiest moment of the week. Each stop leaves 6,000 × 5 = 30,000 events waiting, and the spare 2,000 a second takes 15 seconds to clear them. In partition-seconds, the time each partition sat still, it is 160 × 120 × 5 = 96,000.

Almost all of that stopping was for nothing. When one process leaves, only its two partitions need a new reader. The other 118 could have kept going. The cooperative protocol, added to Kafka as incremental cooperative rebalancing, does exactly that. The coordinator works out the new assignment first. Only the members that must give up a partition stop reading it; everyone else keeps their partitions and keeps working. A partition moves in two short rounds: it is taken from its old owner in the first, and given to its new owner in the second.

Replay the deploy. Each rebalance pauses only the partitions that move, one or two, for up to 5 seconds. Every partition moves twice during the deploy, away and back, so that is 120 partitions × 2 moves × 5 seconds = 1,200 partition-seconds, against 96,000. At no moment does the whole group stop. Kafka 4.0 made a newer protocol generally available, in which the brokers compute the assignments and no change needs a round across the whole group. A consumer opts in with group.protocol=consumer.

A restart still moves partitions twice: away when the process stops, and back when its replacement starts. Static membership removes both moves. Each process is given a fixed name, its group.instance.id, so the coordinator can recognise the replacement as the same member. When a named member leaves, the coordinator does not rebalance. It waits. If the member comes back under the same name before the session timeout, 45 seconds by default, it gets its old partitions back, with no rebalance at all.

That is not free. While the process restarts, its partitions have no reader for the full 20 seconds. Every partition waits through one restart, so over the deploy that is 120 × 20 = 2,400 partition-seconds, more than the cooperative protocol’s 1,200. Static membership earns its keep when moving a partition is expensive. That is when the process keeps something warm for it, such as a cache of courier positions or a local store that takes minutes to rebuild. It also has an edge. A named member does not announce that it is leaving, even when it is shut down on purpose. So a member that is not coming back is noticed only after the session timeout, and its partitions wait the full 45 seconds.

Two more rules come with groups. A group can use at most as many readers as there are partitions, because a partition has one reader per group; a 121st dispatch process would sit idle. That is another reason the topic has 120 partitions for 80 processes.

The other rule fences the member that was declared dead but is not. A process that stops polling for longer than max.poll.interval.ms, 5 minutes by default, is removed from the group, and its partitions go to someone else. Suppose it was not dead, only stuck in a slow call, and it now wakes up and commits its old offsets. Each rebalance starts a new generation, numbered by the coordinator, and every commit carries the generation it was made in. The coordinator refuses a commit from an old generation, so the stuck process cannot move the group’s position backwards or forwards. It can still repeat an effect before it notices, which is one more reason the effect must be idempotent.

The experiment plays a rolling deploy of four processes on eight partitions. The tabs are stopping the whole group, moving only what changes, and keeping each member’s partitions across a restart.

The interactive version of this example is available when JavaScript loads.

The gap: The members of a group change all the time, and every change must decide again who reads which partition.

Option 1: Stop the whole group

Every member gives up every partition, rejoins, and gets a new assignment.

Works when: A small group that rarely changes.

Breaks when: A rolling deploy of 80 processes stops every partition 160 times: over thirteen minutes with no courier assigned.

Option 2: Move only what changes (start here)

Compute the new assignment first; only partitions that change owner pause.

Works when: Always.

Watch for: A restart still moves each of its partitions away and back, two short pauses, plus whatever the new owner must warm up.

Option 3: Keep partitions across a restart

Give each member a fixed name; a member that returns before the session timeout keeps its partitions with no rebalance.

Works when: Members with state that is slow to rebuild, restarted by a deploy.

Watch for: Its partitions wait for the whole restart, and a member that never returns is noticed only after 45 seconds.

In the interview: Open with the arithmetic of the old protocol: 160 rebalances times 5 seconds is over thirteen minutes of stopped dispatch. Then describe the cooperative protocol and the 1,200 partition-seconds. Offer static membership as a trade for members with warm state, and mention generation numbers if the interviewer asks what stops a zombie.

Say this: A rebalance should move only the partitions that change owner, so I use the cooperative protocol, and the rest of the group keeps reading. For members that are slow to warm up, a fixed member name lets a quick restart keep its partitions with no rebalance at all. Every commit carries the group’s generation, so a member that was removed cannot commit after it wakes up.

If they ask: a message that always fails

One placed event arrives with a malformed address, and dispatch throws an error on it every time. A job queue would retry it a few times and move it aside. A log cannot skip one message on its own. The offset means “everything before this is done”, so dispatch cannot commit past the bad event without handling it or giving up on it. If it keeps retrying, the whole partition stops behind one bad event, and 50 events a second pile up behind it.

So dispatch catches the failure, publishes the event to a retry topic with a count of attempts, and moves on. A separate consumer reads the retry topic after a delay and tries again. After a few attempts, the event goes to a dead letter topic, where an alert fires and a person looks at it. This keeps the partition moving and keeps the bad event. It does bend order: if Elif cancels while her placed event sits in the retry topic, dispatch sees the cancel first. When order matters, dispatch records in a shared table that O-8812 has a message parked, so whichever member reads the partition next knows. Every later event with that key is parked behind the first until it is resolved.

If they ask: a group falls eight days behind

Analytics has a bug and stops reading for eight days. The log keeps seven. When it restarts, the oldest day it has not read has already been deleted, and no number of extra readers can bring it back. That is why the most important thing to watch on a queue is lag, measured in time. Lag here means the age of the oldest message each group has not yet read. An alert at a few hours gives days of warning.

If a team really needs months of history, keeping it on the brokers’ disks is expensive. Kafka’s tiered storage moves closed segments to object storage, such as Amazon S3, and keeps only recent ones on the brokers. A reader asking for an old offset is served from object storage, more slowly, and the brokers’ disks stay sized for recent data.

Some topics only need the latest value for each key, such as each courier’s current position. Those can be compacted instead of expired: Kafka “will always retain at least the last known value for each message key” and drops older ones (Kafka design). Watch two more numbers beside lag: partitions with fewer copies than they should have, and how often an in-sync list shrinks.

If they ask: a broker dies for good

A broker’s disks fail, and its 30 TB of copies are gone. Every partition it held now runs on two copies, and with a minimum of two in sync, one more failure among them stops writes to that partition. So the copies have to be rebuilt elsewhere, soon. Apache Kafka does not move partitions on its own: an operator, or a tool such as Cruise Control, reassigns them to other brokers. Spread over the 63 survivors, each takes about 30 TB ÷ 63, about 476 GB. The copying is throttled so it does not starve producers and consumers; at 50 MB a second per broker, 476,000 MB ÷ 50 is 9,520 seconds, about 2.6 hours. Adding brokers works the same way. A new broker starts empty and takes no existing partition until one is reassigned to it.

If they ask: each message is a job, like SQS

Some teams want a job queue, not a log. Each message is a task, such as resizing a photo, and any free worker should take it. The worker acknowledges it when done. If the worker dies, the task goes back to the queue, and there is no order to keep. The log fits this badly. A slow task holds up its whole partition, and the number of workers is capped by the number of partitions.

A job queue tracks each message separately. Amazon SQS hides a message from other workers while one works on it, for a visibility timeout, 30 seconds by default. If the worker does not delete the message in time, it reappears for someone else. After a set number of failed attempts, SQS moves the message to a dead letter queue. RabbitMQ does the same with acknowledgements. Since Kafka 4.2, share groups are ready for production. The members of a share group take individual messages from the same partitions and acknowledge them one by one, and there may be more members than partitions. Pick the log when many teams read every message and order matters. Pick a job queue when each message is work for exactly one worker, done in any order.

If they ask: another region

A second region usually gets its own cluster, and a mirroring process copies topics from one to the other, as Kafka’s MirrorMaker does. The copy is asynchronous: checkout’s publish is confirmed by the first region, and the second hears about it a moment later. If the first region is lost, the last seconds of confirmed messages may not have arrived in the second. The offsets differ between the two clusters, so a consumer moving regions needs a translated position, and it will read some messages twice. Idempotent consumers, from the offsets deep dive, are what make that safe. Confirming only after the second region has a message would close the gap, and would add the round trip between the regions to every publish.

Walk one order through the final design

At 19:02:00 Elif orders. Checkout saves O-8812 and an outbox row in one transaction. The relay publishes the placed event to orders with the key O-8812, which hashes to partition 41, as producer P9, sequence 17. Broker 1 leads partition 41. It appends the event at offset 4,210,337, waits until broker 2 and broker 3, both in sync, have copied it, and confirms. If the confirmation is lost, the relay retries, and the leader recognises sequence 17.

The kitchen, dispatch and analytics groups each fetch from partition 41 at their own offsets, mostly from memory. Dispatch’s process for partition 41 writes the event’s ID, Kwame’s assignment and a notification row in one transaction. A sender tells Kwame, and dispatch commits offset 4,210,338 a few seconds later. At 19:02:30 the cancel arrives on the same partition, after the placed event, and dispatch calls Kwame back.

At 19:05 dispatch deploys. Each process that leaves hands on its partitions, and the rest keep reading. Seven days later, the segment holding offset 4,210,337 is deleted as a whole file.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 publishProducers send batches to each partition’s leader, from an outboxA publish waits for every in-sync copy, at least two
FR2 groups read at their own paceA log per partition and an offset per groupA group cannot retry one message on its own
FR3 order per keyThe key picks the partition; the consumer picks a thread by the same keyA heavy key overloads one partition, and the partition count is fixed up front
FR4 replay 7 daysSegments deleted as whole files after 7 days, about 1.8 PB with three copiesA group more than 7 days behind loses data
Survives one brokerThree copies in three zones, confirmed by every in-sync copy, at least twoA stalled follower pauses writes until it is dropped
No duplicate effectsProducer IDs and sequences; event IDs saved with the effectEvent IDs are kept for at least 7 days

How does the answer change for Kafka, SQS, RabbitMQ or a pub/sub system?

Interview variantWhat carries overWhat changes
Design KafkaEverything on this pageThe same problem; expect questions on the in-sync list and the controller
Design a pub/sub systemTopics, groups, offsets, replicationOften push rather than pull, with subscriptions over HTTP; ask whether old messages must be replayable
Design SQS or a task queueReplication, producer IDs, idempotent consumersPer-message visibility timeouts and acknowledgements replace offsets, and order is usually dropped
Design RabbitMQReplication, acknowledgements, dead lettersA broker routes each message through exchanges to queues, and deletes it once acknowledged
Design an event bus between servicesKeys, order per key, the outbox, idempotent consumersFewer messages, more teams; schemas and who may publish what matter more than raw throughput
Design a log aggregation pipelinePartitions, batching, retentionMessages are rarely keyed, and losing a few is often acceptable, so acks=1 may do

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelExplains producers, a broker that stores messages, and consumers that read them; knows that a crash can mean a message is read twice.
SeniorUses a partitioned log with an offset per group, keys by the thing whose order matters, sizes the partition count from consumer throughput, and waits for in-sync copies with a minimum of two.
StaffExplains the idempotent producer and the outbox, makes effects idempotent with event IDs in the same transaction, names the boundary of exactly once, and keeps a group working through membership changes.
PrincipalDecides what the platform promises every team, sets partitioning and retention policy, and plans region failure, tiered storage and how the cluster grows.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.