You've already used a queue in this course: the notification system, the news feed fan-out and video processing all said “put it on a queue”. Now interviewers ask the deeper question: design the queue itself. It's reported at Amazon, LinkedIn (where Kafka was born), Uber and Flipkart, and it teaches ideas every senior engineer is expected to know.
Step 1 · Requirements
- Functional: producers publish messages to named topics; consumers subscribe and read them; several independent consumer groups can read the same topic; consumers can replay from an earlier point.
- Non-functional: very high throughput (millions of messages a second); durable (an acknowledged message is never lost); ordered per key; horizontally scalable; low latency (milliseconds); keeps working when a machine dies.
- Out of scope (say it): complex routing rules, per-message priorities, delayed messages. Mention that a broker like RabbitMQ or SQS covers those better.
Step 2 · Estimates
- Throughput: 1 million messages/s × 1 KB = 1 GB/s coming in.
- Retention: keep 7 days → 1 GB/s × 86,400 s × 7 ≈ 600 TB; with 3 copies ≈ 1.8 PB of disk.
- Machines: if one broker comfortably handles ~100 MB/s of writes (plus replication and reads), you need roughly 30+ brokers. The exact number matters less than showing the method.
Step 3 · API
produce(topic="orders", key="order-42", value={...}, acks="all") → { partition: 1, offset: 1873 }
subscribe(topics=["orders"], group="billing")
poll(timeout=500ms) → [ { partition, offset, key, value }, ... ] (long-polling)
commit({ partition: 1, offset: 1874 }) // "I've finished everything before 1874"
seek(partition=1, offset=0) // replay from the startStep 4 · Design
The big idea: a log, not a mailbox
A simple queue hands a message to one consumer and deletes it. A log is different: messages are only ever appended to the end of a file, each gets a number called an offset (0, 1, 2…), and consumers just remember the offset they reached. Reading doesn't delete anything, so ten different teams can read the same stream, and anyone can rewind. Appending to the end of a file is also the fastest thing a disk can do.
🎮 Topic “orders”: 3 partitions, one consumer group
Partition 0
→ consumer 1 · offset 0
Partition 1
→ consumer 2 · offset 0
Partition 2
→ consumer 1 · offset 0
Press Produce a few times, then Consume.
Watch three rules: the same key always goes to the same partition (so its events stay in order); inside a group each partition is read by exactly one consumer; and messages are not deleted when read: the consumer just moves its offset forward.
Why it's so fast
- Sequential disk writes: appending is far faster than random writes, even on spinning disks.
- The operating system's page cache: recent messages are usually still in memory when consumers read them.
- Batching and compression: producers send many messages per request; brokers store and send the batch as is.
- Zero-copy: brokers can send file data straight from disk cache to the network socket without copying it through the application.
Delivery guarantees
| Guarantee | How | Risk | Use for |
|---|---|---|---|
| At-most-once | Commit the offset before processing | Crash = message lost | Metrics where a gap is fine |
| At-least-once (default) | Process, then commit | Crash = message read again | Almost everything, with idempotent consumers |
| Exactly-once (within Kafka) | Idempotent producer + transactions | More complexity, a bit slower | Stream processing: read → transform → write to Kafka |
Step 5 · Scale and reliability
- Replication: each partition has a leader and followers (replication factor 3 is common). Followers that are caught up form the in-sync replica set.
- Durable writes: with
acks=allandmin.insync.replicas=2, the leader confirms a write only after at least two copies have it. If the leader dies, an in-sync follower takes over with no acknowledged data lost. - Controller: one elected controller tracks which brokers are alive and which replica leads each partition. Kafka once used ZooKeeper for this; modern Kafka uses its own built-in Raft-based mode (KRaft).
- Scaling: more partitions = more parallel consumers and spread across more brokers. Pick enough up front: adding partitions later changes which partition a key maps to.
- Retention and compaction: delete old segments after N days or N GB, or compact a topic to keep only the latest value per key (great for “current state” topics).
- Poison messages: a message that always fails is retried a few times, then moved to a dead-letter topic so it doesn't block the partition.
- Backpressure: watch consumer lag (latest offset minus committed offset). Growing lag means add consumers (up to the partition count) or speed up processing.
🧠 PATH memory card
Remember the message queue design for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
At a big railway parcel office, the destination on the label decides which counter a parcel goes to, so all parcels for Pune arrive at the same counter in order. Each counter writes every parcel into a numbered register that is never erased. A delivery team sends one porter per counter, and each porter keeps a bookmark of the last line they handled. If a porter goes home sick, another porter picks up their counter from the bookmark.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Label, Register, Porter, Bookmark”
- Label→Message key; hash(key) picks the partition
- Counter→Partition: ordered within itself
- Register→Append-only log, kept for days, replicated
- Porter→Consumer: one per partition in each group
- Bookmark→Committed offset: where to resume after a crash
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Checkout producesorder-42 paidwithacks=all. hash(“order-42”) picks partition 1; the leader appends it at offset 1873 and two followers copy it before the producer gets its OK. The billing group's consumer for partition 1 polls, charges the order, and commits 1874. It crashes before the next commit; the group rebalances and another consumer resumes at 1874. Analytics reads the same offset 1873 an hour later for a dashboard. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 8 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Follow-up questions interviewers ask
- “Kafka or SQS/RabbitMQ?” Kafka for high-volume streams, replay and many readers; SQS or RabbitMQ for simple work queues, per-message retries, delays and routing.
- “One partition is much busier than the others?” A hot key. Add a suffix to spread it (
key#0…key#9) if strict order for that key isn't needed, or give it special handling. - “How do you update a database and publish an event safely?” The outbox pattern: write the event into an outbox table in the same database transaction, and a relay publishes it to the queue.
Where to go next
At-least-once delivery means a message can arrive twice. When that message says “charge ₹500”, a duplicate is a real problem. The final part solves it end to end: design a payment system.
Key takeaways
- ✓A message queue decouples services and absorbs spikes; Kafka stores messages as an append-only log.
- ✓Topics split into partitions by hash(key); order holds only within a partition.
- ✓In a consumer group, each partition has one consumer; offsets record progress and allow replay.
- ✓Replicate partitions (RF 3, acks=all, min in-sync 2) so a broker failure loses nothing.
- ✓Default to at-least-once delivery with idempotent consumers and a dead-letter topic.
Frequently asked questions
What is a message queue in system design?
A message queue is a buffer between services. A producer writes a message and moves on; a consumer reads it later, at its own pace. This decouples services, absorbs traffic spikes and lets slow work (emails, video processing, analytics) happen in the background without making users wait.
What is the difference between Kafka and RabbitMQ?
RabbitMQ is a classic message broker: it routes messages to queues and usually deletes each message once a consumer acknowledges it, which suits task queues. Kafka is a distributed log: messages are appended to partitions and kept for a set time (often days), so many consumer groups can read the same data and replay it. Kafka suits high-volume event streams; RabbitMQ suits flexible routing and per-message work queues.
Does Kafka guarantee message order?
Only within a partition. Messages with the same key always go to the same partition, so all events for one order or one user stay in order. Across different partitions there is no global order. If you truly need one global order, you need a single partition, which limits throughput.
What is a consumer group?
A set of consumers that share the work of reading a topic. Each partition is assigned to exactly one consumer in the group, so messages are processed once per group, in parallel across partitions. Different groups (say, billing and analytics) each get their own full copy of the stream and track their own offsets.
What does exactly-once delivery mean in Kafka?
Networks fail, so the practical default is at-least-once: a message may be delivered again after a retry. Kafka offers idempotent producers and transactions so that a read-process-write flow inside Kafka produces each result once. When a consumer writes to an outside system such as a database or a payment API, you still make that step idempotent, for example with a unique message ID.
🧠 Quick check: message queues
1. All events for order #42 must be processed in order. What do you do?
2. A topic has 6 partitions. You run 10 consumers in one group. What happens?
3. A consumer processes a message, then crashes before committing its offset. On restart...
4. Which settings keep acknowledged messages safe if one broker dies?
Checking your access…