A durable, ordered log that millions of messages a second flow through, with replication and consumer groups.
“Design a distributed message queue, like Kafka.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Choosing the right abstraction | A queue that deletes a message when it is read and a log that keeps it are different systems. The interviewer wants to hear you pick the log, and say why: replay, many readers, and speed. |
| Why a log is fast | Millions of messages a second on ordinary disks is not magic. You should name sequential appends, batching, the page cache and zero-copy reads, not just say “it is distributed”. |
| Replication and the loss window | This is the heart of it. You must say exactly which messages can be lost when a leader dies, for each acks setting, and what you give up to prevent it. |
| Ordering and delivery semantics | Order exists only inside a partition. At least once is the default, and exactly once is a feature built on top, with limits. Honest answers beat confident ones. |
| Operating a cluster | Adding brokers, moving data without hurting traffic, noisy tenants, upgrades and monitoring are what make a design real. |
A distributed message queue here is an append-only, partitioned, replicated log. Producers append messages to a topic. A topic is split into partitions, and each partition is one ordered file on a leader broker, copied by followers. Consumers pull from an offset they track themselves, so many readers can read the same data and replay it.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Log or task queue, ordering scope, delivery guarantee, retention and replay, throughput, and what may be lost. |
| 2. Estimate | 3 | Ingest, replicated writes, storage for the retention period, brokers, and partitions. |
| 3. API and data | 4 | Produce and fetch, offsets and groups, the segment-file layout. |
| 4. High-level design | 8 | Producers, brokers, partition leaders and followers, metadata quorum, consumer groups. Follow one message. |
| 5. Deep dives | 16 | The log, then replication and the loss window, then consumers and semantics, then operations, then retention. |
| 6. Scale and failures | 7 | A dead broker, a slow follower, a rebalance storm, a lost zone, a noisy tenant. |
| 7. Wrap up | 3 | Recap, the durability versus availability trade-off, and what you would build next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Is this a log that keeps messages and lets many readers replay, or a task queue where each message goes to one worker and is then deleted? | These are different designs. A log keeps data by time, a queue removes it on acknowledgement. | A log. Several teams read the same stream, and we need replay. | Append-only storage, consumers track offsets, retention by time or size. No per-message ack state on the broker. |
| What ordering do we promise? | Total order across a topic does not scale. Order per key does. | In order for messages with the same key. No global order. | Partitions by key hash. Order only inside a partition. |
| What does a producer need to be told: nothing, “leader has it”, or “it is safely replicated”? | It is the durability dial and the latency dial in one. | Configurable per producer. The default for important data is safely replicated. | An acks setting, replication factor 3, and min in-sync replicas. |
| Delivery guarantee: at most once, at least once or exactly once? | It decides offsets, retries and deduplication. | At least once by default. Exactly once where we can, inside the system. | Idempotent producer, transactions, and idempotent consumers for anything outside. |
| How long do we keep data, and do consumers replay old data? | Retention sets storage and the need for tiering. | 7 days online, replay of the last few days is common. | Time-based retention by segment, and tiered storage for the tail. |
| How many messages a second, and how big? | It sizes partitions, brokers, disks and network. | 1M a second on average, 3M at peak, about 1 KB each, max 1 MB. | About 1 to 3 GB/s in, 300 partitions, 36 brokers. Large payloads use the claim-check pattern. |
| What latency do producers need? | Low latency fights with batching. | p99 under 10 ms to be acknowledged, end to end under about 50 ms. | Small batches with a short linger, replication in the same region. |
| How many consumer groups, and how many consumers each? | Reads multiply the outgoing traffic. | About 3 groups per topic on average, up to 100 consumers in a group. | Read traffic is 3 times the write traffic. Parallelism is capped by the partition count. |
| Many teams share it. Do we need quotas and isolation? | One noisy producer can hurt everyone. | Yes. Per-client quotas and access control. | Byte-rate quotas, ACLs, and separate clusters for the most critical traffic. |
| One region or several? What if a zone fails? | It sets replica placement and the cost of failover. | One region, three zones. It must survive losing a zone. | Replicas in different zones. Cross-region mirroring is an extension. |
| Assumption | Value |
|---|---|
| Messages (sustained, peak) | 1M and 3M per second |
| Message size | about 1 KB (max 1 MB) |
| Replication factor | 3, across 3 zones |
| Consumer groups reading each message | 3 on average |
| Retention | 7 days online |
| Broker network | 10 Gbps, about 1.25 GB/s, planned to run at most 50% busy at peak |
| Broker disk | about 30 TB usable, kept at most 70% full, sequential writes about 400 MB/s |
| Producer batch | about 100 messages (about 100 KB) per request |
| Partition throughput target | 10 to 20 MB/s peak per partition |
| What | Maths | Result |
|---|---|---|
| Ingest, sustained and peak | 1,000,000 × 1 KB, and 3,000,000 × 1 KB | 1 GB/s sustained, 3 GB/s peak |
| Messages per day | 1,000,000 × 86,400 | 86.4 billion |
| Disk writes with 3 copies | 1 GB/s × 3, and 3 GB/s × 3 | 3 GB/s sustained, 9 GB/s peak |
| Follower traffic (2 copies sent between brokers) | 3 GB/s × 2 | 6 GB/s at peak |
| Consumer reads (3 groups) | 3 GB/s × 3 | 9 GB/s out at peak |
| Cluster network at peak | in = 3 GB/s + 6 GB/s; out = 6 GB/s + 9 GB/s | 9 GB/s in, 15 GB/s out |
| Brokers forced by network | 15 GB/s ÷ (1.25 GB/s × 50%) | 24 brokers (before spare capacity) |
| Brokers forced by disk writes | 9 GB/s ÷ 400 MB/s | about 23 brokers |
| Spare capacity to lose a whole zone | 24 ÷ (2/3 of the cluster left) | 36 brokers |
| Raw data per day, and replicated | 1 GB/s × 86,400, then × 3 | 86.4 TB, and 259 TB per day |
| Seven days of retention, replicated | 259 TB × 7 | about 1.8 PB |
| Brokers forced by storage | 1.8 PB ÷ (30 TB × 70%) | 87 brokers (storage, not network, is the limit) |
| If only the last 6 hours stay on brokers (tiered storage) | 1 GB/s × 3 × 21,600 s | 65 TB replicated, about 1.8 TB per broker on 36 |
| Partitions | 3 GB/s peak ÷ 10 MB/s per partition = 300 | about 300 partitions (about 8 leaders and 25 replicas per broker) |
| Per-partition load at 300 partitions | 1 GB/s ÷ 300, and 3 GB/s ÷ 300 | 3.3 MB/s sustained, 10 MB/s peak |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | produce(topic, key, value, headers, acks) | batch of records, acks = 0, 1 or all, producerId, sequence | partition, base offset, timestamp per batch | Records are grouped per partition and compressed. With acks=all the answer comes only when enough replicas have the data. A producer id plus a per-partition sequence number lets the broker drop repeats. |
| GET | fetch(topic, partition, offset, maxBytes, maxWaitMs) | none | records from the offset, plus the high watermark | A long poll: the broker waits for data or a timeout. Only data below the high watermark is returned. Clients fetch from the leader (or a nearby follower if allowed). |
| POST | joinGroup(group, topics) | member id, supported assignment strategies | generation, assigned partitions | Sent to the group coordinator (a broker). Triggers a rebalance when members come or go. |
| POST | heartbeat(group, generation) | none | OK or REBALANCE_IN_PROGRESS | Proves the consumer is alive. A stale generation is rejected, so a zombie consumer cannot commit. |
| POST | commitOffset(group, topic, partition, offset) | none | OK | Stored in an internal compacted topic. Commit after processing for at-least-once, before for at-most-once. |
| POST | createTopic(name, partitions, replicationFactor, config) | none | OK | Admin. The controller assigns replicas to brokers in different zones. Config sets retention, min.insync.replicas and compaction. |
| On disk, per partition replica | What it holds | Why it is there |
|---|---|---|
| segment files (about 1 GB each) | Messages in offset order, appended at the end | Sequential writes. Retention deletes whole old segments, which is cheap. |
| offset index (sparse) | One entry for every few KB: offset → file position | Finds a message by offset with a small lookup and a short scan. |
| time index (sparse) | Timestamp → offset | Lets a consumer start from a point in time. |
| leader epoch file | Which leader (and its epoch) wrote which offsets | Lets a follower cut its log correctly after a leader change. |
| checkpoint of the high watermark | The last offset known to be on all in-sync replicas | Decides what consumers may read after a restart. |
| One message (record) | Type | Notes |
|---|---|---|
| offset | 64-bit, per partition | Position in the partition. Never reused. |
| timestamp | 64-bit | Set by the producer or the broker. |
| key | bytes, optional | Picks the partition. Same key, same partition, same order. |
| value, headers | bytes, map | The payload. Large payloads go to object storage, and the message holds a link (claim check). |
| producerId, sequence | 64-bit, int | Used to drop duplicate retries from one producer. |
partition = hash(key) mod numPartitions // same key → same partition → same order leader = metadata[topic][partition].leader // all writes and reads go to the leader append → segment file → page cache → followers fetch it → high watermark moves up consumer → fetch(offset) from the leader → process → commit(offset)
| Component | What it does |
|---|---|
| Producer client | Chooses the partition from the key, groups messages into compressed batches, retries, and carries a producer id and sequence numbers. |
| Broker | Hosts many partition replicas. As a leader it takes writes and serves reads. As a follower it copies the leader. It also serves old data from tiered storage. |
| Partition leader and followers | One leader per partition, followers in other zones. Followers pull new messages. The leader tracks which followers are in sync (the ISR). |
| Metadata quorum and controller | A small Raft group that stores the truth about topics, leaders and the ISR. The controller reacts to broker failures by electing new leaders from the ISR. |
| Group coordinator | A broker that owns a consumer group: tracks members through heartbeats, assigns partitions, and stores committed offsets. |
| Page cache and disks | Writes append to a segment file and reach the OS page cache first. Recent reads are served from memory, and old reads from disk. |
| Tiered storage | Closed segments older than a few hours are copied to object storage. Brokers keep only the recent tail. |
| Quotas, ACLs and metrics | Limit bytes a second per client, control who may read or write which topic, and expose lag, under-replicated partitions and latency. |
The problem: We must take 1M to 3M messages a second on ordinary servers and disks. A database row per message, or an acknowledgement and delete per message, would be far too slow. And one ordered file cannot take 3 GB/s, so we must split it without losing order.
| Option | How it works | Good | Bad |
|---|---|---|---|
| A database table of messages | Insert a row per message, mark it consumed on read. | Familiar. Easy queries and transactions. | Random writes, indexes, locks and per-row overhead. Far below the rate we need, and replay is awkward. |
| A broker with per-message state and acknowledgement | Keep each message and its delivery state in memory or on disk, delete on ack (a classic queue). | Flexible routing, per-message retry and priority. | Per-message bookkeeping caps throughput. A slow consumer fills memory. No cheap replay. |
| One append-only log, one reader position | Append all messages to one file. Each consumer remembers an offset. | Simplest. Perfect order, sequential I/O. | One file means one machine and one leader. The throughput ceiling is one disk and one NIC. |
| A partitioned append-only log | Split the topic into partitions. Each is an append-only file with its own leader. The key picks the partition. Consumers track offsets per partition. | Sequential I/O at disk speed, parallelism by partition, order per key, cheap replay, many readers. | No order across partitions. The partition count is hard to change later. A hot key makes a hot partition. |
The speed comes from doing less per message. Writes are sequential appends (disks and SSDs are fastest at this). Producers send batches, compressed together, so a request carries about 100 messages. The broker does not track per-message state: the consumer holds one number, the offset. Recent data sits in the OS page cache, so tailing readers never touch the disk. And reads use zero-copy (the kernel sends file bytes to the network without copying them through the application).
The partition is the unit of parallelism and of order. Within a partition, offsets give a strict order. Across partitions there is none, and that is the price of scaling. Messages with the same key always go to the same partition, so order per user, per order or per device is kept.
| Choosing the partition count and key | What to know |
|---|---|
| Count from throughput | Peak 3 GB/s ÷ 10 MB/s per partition = 300. Also enough partitions for the biggest consumer group (parallelism is capped by the count). |
| Too few | A partition becomes a throughput ceiling, and a consumer group cannot use more machines. |
| Too many | More open files, memory, replication traffic, slower leader elections and longer recovery. Thousands per broker is a warning sign. |
| Changing the count later | hash(key) mod N changes, so a key can move to another partition and its order across the change is lost. Plan the count with headroom, or create a new topic and migrate. |
| Hot key | One key with a huge share of traffic makes one partition hot. Add a suffix to spread it (and lose order across the suffixes), or split that key into its own topic. |
| No key | Round robin or sticky batches spread load evenly but give no order. |
sendfile, the kernel moves the bytes straight from the page cache to the network card. That is why one broker can send many GB/s to consumers.The problem: A single broker will die. We must say exactly which acknowledged messages can be lost when it does, and what we give up to prevent it. The invariant we want: a message the producer was told is saved is never lost while enough replicas survive.
| Option | How it works | Good | Bad |
|---|---|---|---|
| No replication | One copy on the leader's disk. | Fastest and cheapest. | A dead disk or broker loses data and the partition is down until it returns. |
| Asynchronous replication (acks=1) | The leader answers as soon as it has written. Followers copy afterwards. | Low latency. Writes work while followers are down. | If the leader dies before a follower copied the message, an acknowledged message is lost. This is the loss window. |
| Synchronous to all in-sync replicas (acks=all) | The leader answers when every replica in the in-sync set has the message, and the set has at least min.insync.replicas members. | No acknowledged message lost while one in-sync replica survives. Clear, testable rule. | Latency is the slowest in-sync follower. If the ISR shrinks below the minimum, writes are refused. |
| Consensus per partition (Raft-style quorum) | A write commits when a majority has it. A leader needs a majority to be elected. | Strong, well-understood safety. No separate ISR concept. | Always waits for a majority, and each partition runs its own consensus group, which is heavier at thousands of partitions. |
The invariant is: an acknowledged message is on at least 2 replicas, and a new leader is chosen only from replicas that have it. acks=all with min.insync.replicas=2 enforces the first half (a write succeeds only if the leader and at least one follower have it). A clean election from the ISR enforces the second half. Together they survive the loss of any one broker, and because the 3 replicas sit in 3 zones, of one zone.
The cost is stated plainly: if two of three replicas are down, the ISR has one member, below the minimum, so we refuse writes. That is a choice of safety over availability (the partition behaves like a CP system for writes). Allowing an unclean election (taking a replica that was not in sync) brings the partition back sooner, but it can lose confirmed messages and rewrite history that consumers already read. Use it only for data you can afford to lose.
| Setting | What the producer is told | What can be lost when the leader dies |
|---|---|---|
| acks=0 | Nothing. It does not wait. | Anything not yet copied, with no error at all. |
| acks=1 | “Saved” once the leader wrote it | Messages the leader had but no follower had yet. The producer was told they were saved. |
| acks=all, min ISR 1 | “Saved” once every in-sync replica has it | If the ISR shrank to the leader alone, the leader confirms by itself, so the loss window is back. |
| acks=all, min ISR 2 | “Saved” on at least 2 replicas | Nothing acknowledged, while a second replica survives. Writes are refused if fewer than 2 are in sync. |
| Concept | Meaning | Why it exists |
|---|---|---|
| ISR (in-sync replicas) | The leader plus followers that are caught up within a time limit | A slow follower is dropped, so it cannot hold up every write. |
| High watermark | The highest offset that every ISR member has | Consumers read only up to it, so they never see data that could vanish. |
| Leader epoch | A number that grows with each new leader | After an election, a follower cuts its log back to where the new leader's epoch starts, so logs cannot silently diverge. |
| Unclean election | Choosing a leader that is not in the ISR | Trades possible loss for availability. |
| Rack-aware placement | Replicas spread over zones | A zone failure then costs at most one replica. |
1. broker 1 stops sending heartbeats to the controller → declared dead 2. controller picks a new leader from the ISR of each partition it led 3. new leader bumps the leader epoch and starts accepting writes 4. old leader, when it returns, fetches from the new leader and truncates its log to the offset where the new epoch began 5. consumers re-read metadata and fetch from the new leader
The problem: Many consumers must share the work of a topic, never skip a message, and survive restarts. A crash between “processed” and “committed” makes a message come twice, and a crash the other way loses it. And the group must be able to change members without stopping for long.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Push from the broker | The broker sends messages to consumers as they arrive. | Lowest latency for light traffic. | A slow consumer is flooded. The broker must track each consumer's speed. Hard to batch well. |
| Pull by the consumer, offset kept by the consumer | The consumer fetches from an offset when it is ready, in batches, and commits the offset. | Natural back pressure and batching. Replay is just a lower offset. The broker stays simple. | A long poll is needed to avoid empty fetches. Latency depends on the fetch wait. |
| Commit before processing | Save the offset, then process. | No message is processed twice. | A crash after the commit loses the message: at most once. |
| Commit after processing, with idempotent handling | Process, then commit. A crash in between means the batch is processed again, so make the work safe to repeat. | No message is lost: at least once. Safe when the work is idempotent. | Duplicates happen, so the consumer must de-duplicate or be idempotent. |
Pull gives back pressure for free: a consumer takes only what it can handle, and a slow one simply lags without hurting anyone. Commit after processing gives at-least-once: the worst case is a repeat, never a loss. Then we remove the repeats where we can.
For exactly-once inside the system: the idempotent producer (a producer id plus a sequence number per partition) lets the broker drop a retry it has already stored. Transactions let a consumer-processor write its output messages and commit its input offset in one atomic step, so a crash neither duplicates the output nor loses the input. Be honest about the limit: it covers data that stays inside the log. An email sent, a payment made, or a database written outside the transaction is still at-least-once, so that consumer must be idempotent.
| Group event | What happens | Cost |
|---|---|---|
| Consumer joins or leaves | The coordinator starts a rebalance and reassigns partitions | Eager: everyone stops while it happens. Cooperative: only moved partitions pause. |
| Consumer is slow to heartbeat | Declared dead, partitions move away | Too aggressive: false alarms and rebalance storms. Too lax: slow recovery. |
| Zombie consumer commits late | Rejected: its group generation is old | Stops a paused consumer from overwriting newer progress. |
| Poison message | Processing keeps failing on one message | Retry a few times, then park it in a dead-letter topic so the partition keeps moving. |
| Consumer is behind | Lag (latest offset − committed offset) grows | Alert on it. Add consumers (up to the partition count), or fix the slow step. |
The problem: The cluster changes every day: brokers fail, new ones join, topics grow, tenants misbehave. Moving partitions copies terabytes while live traffic continues, and the cluster needs one trustworthy source of truth for who leads what.
| Option | How it works | Good | Bad |
|---|---|---|---|
| External coordination service (ZooKeeper style) | Store metadata and elect the controller in a separate quorum service. | Proven. Brokers stay simple. | Another system to run. Metadata changes travel a slow path, which limits the number of partitions. |
| Built-in metadata quorum (Raft) | A few brokers run a Raft group that stores metadata as a replicated log, and the controller is the Raft leader. | One system to operate. Fast failover. Scales to far more partitions. | Needs a careful migration from the old way. The quorum must be sized and protected. |
| Move partitions at full speed | Start copying a partition to a new broker with no limit. | Finishes quickly. | The copy competes with live traffic, so latency spikes and producers time out. |
| Throttled, incremental moves | Set a byte-rate limit on replication for moves, move a few partitions at a time, and let the new replica join the ISR before the old one is dropped. | Live traffic stays healthy. A bad move can be stopped. | A big rebalance takes hours. |
The metadata is small but must never be wrong, so it goes in a Raft group of 3 or 5 nodes (this is what newer Kafka versions do, replacing ZooKeeper). If that quorum loses its majority, the cluster cannot change leaders or create topics, but brokers that already lead partitions keep serving. That is a limited failure, so we protect the quorum with dedicated nodes and monitoring.
To add a broker, we move whole partitions to it with a throttle (for example 100 MB/s per broker), a few at a time, and only drop the old replica after the new one is in the ISR. With tiered storage, each broker holds only hours of data, so a move is minutes, not a day. Quotas cap bytes a second and request time per client, so a runaway producer is slowed (the broker delays its responses) before it hurts others.
| Operation | How to do it safely |
|---|---|
| Add brokers | Join empty, then move partitions with a throttle. Also rebalance leaders so each broker leads about the same number. |
| Broker fails | Controller elects new leaders from the ISR (seconds). The data is re-copied to a replacement in the background. |
| Disk fails | With several disks per broker, only the partitions on that disk need re-copying. Others keep running. |
| Rolling upgrade | One broker at a time: move its leaders away, restart, wait for it to rejoin the ISR, then the next. Keep versions compatible. |
| Noisy tenant | Byte-rate and request-rate quotas per client id. Critical workloads get a separate cluster. |
| Security | TLS in transit, authentication of clients (for example SASL or mutual TLS), ACLs per topic, and encryption at rest on the disks. |
| Multi-region | Mirror topics asynchronously to another region. Offsets differ between clusters, so consumers need offset translation. Active-active needs conflict rules. |
The problem: A log grows forever. We need to delete old data cheaply, keep the latest value per key for some topics, replay when asked, and still be able to erase a person's data when the law requires it.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Delete by time or size | Drop whole segment files older than 7 days, or when the topic passes a size. | Very cheap: deleting a file, not rows. Predictable storage. | Old data is gone. Replay stops at the retention limit. |
| Log compaction | Keep only the latest message for each key. A message with a null value (a tombstone) deletes the key. | A compact, current picture of state. Good for changelogs and configuration. | History is lost. Compaction costs disk and CPU in the background. A consumer sees only the latest value per key. |
| Keep everything on brokers | Large retention on local disks. | Simple, and fast replays. | Storage forces 87 brokers, not 36. A replaced broker re-copies terabytes. |
| Tiered storage | Keep the recent hours on broker disks, copy closed segments to object storage, and fetch them back for old reads. | Brokers become small and cheap. Long retention at object-storage prices. Fast broker replacement. | Reading old data is slower. One more system to depend on, and a copy step to monitor. |
Most topics are event streams: delete by time, and let replays go back 7 days. Topics that represent state (a user profile table, a configuration) use compaction, so a new consumer can rebuild the full current state by reading the topic once. Tiering moves the cost from fast disks to cheap object storage: only about 6 hours stay local (65 TB replicated), the remaining days are stored in object storage as single or erasure-coded copies.
For erasing a person's data from an append-only log: use a compacted topic keyed by the person and write a tombstone, which removes earlier values when compaction runs (not instantly, so say so). Or store only encrypted payloads and destroy the person's key (crypto-shredding). Avoid putting personal data in plain messages with long retention.
| Question | Answer |
|---|---|
| How much data stays on brokers with tiering? | 6 hours × 1 GB/s × 3 copies = 65 TB, about 1.8 TB per broker on 36 brokers. |
| What do 7 days cost in object storage? | About 600 TB for one copy (86.4 TB a day × 7), before compression. |
| Does compression help? | Yes, a lot for text and JSON. At 3 times, 7 days replicated falls from 1.8 PB to about 600 TB. |
| How do large messages work? | Keep messages near 1 KB. Put big payloads in object storage and send a link (claim check), or the broker's size limit and memory get hurt. |
| How is a tombstone cleaned up? | Kept for a delay long enough for all consumers to see it, then removed by compaction. |
| Row | m1 | m2 | m3 | m4 | m5 |
|---|---|---|---|---|---|
B1 (leader) dies now | m1 | m2 | m3 | m4 | · |
B2 follower | m1 | m2 | m3 | · | · |
B3 follower | m1 | m2 | m3 | · | · |
Producer was told “saved” | saved | saved | saved | saved | · |
Consumers can read up to the high watermark (m3) | m1 | m2 | m3 | · | · |
A simplified model: one partition, three replicas, one message per tick. In each tick the leader saves the message first and the followers fetch it after. The leader dies right after it saved the chosen message, before any follower fetched it. A follower that stops is dropped from the ISR when m3 arrives. No random numbers, and real systems add timeouts, leader epochs and many partitions.
| Bottleneck | Fix |
|---|---|
| Network (15 GB/s out at peak) | More brokers, 3 consumer groups' reads served from the page cache, compression on the producer, and fetch-from-nearest-replica so reads stay inside a zone. |
| Disk space for 7 days (1.8 PB) | Tiered storage, compression, and a retention policy per topic. Keep only hours on brokers. |
| A hot partition (one hot key) | Add a suffix to spread the key, give the key its own topic, or accept it and size that partition. Watch per-partition throughput. |
| Too many partitions per broker | Cap at a few thousand replicas a broker. Use fewer, larger partitions, or add brokers. Watch election time and open files. |
| Slow followers shrinking the ISR | Replication lag limits, dedicated replication threads, and alerts on ISR shrink. A permanently slow broker is replaced. |
| Rebalance storms | Cooperative rebalancing, static group membership, longer session timeouts, and no heavy work between polls. |
| Replica catch-up after a failure | Tiered storage makes it minutes. Throttle it so it does not starve live traffic. |
| Failure | How the design copes |
|---|---|
| A broker dies | The controller elects new leaders from the ISR within seconds. acks=all with min ISR 2 means no acknowledged message is lost. Producers retry with the same sequence numbers, so repeats are dropped. |
| A zone is lost | At most one replica of each partition is gone. Leaders move to the other zones. Capacity was planned (36 brokers) to carry the load with 2 zones. |
| Two replicas of a partition are down | The ISR is 1, below the minimum of 2, so writes to that partition are refused (producers get errors) while reads of committed data continue. We prefer an error over a lost message. |
| A follower is slow or partitioned | It is dropped from the ISR after a lag limit, so it stops blocking writes. When it catches up it rejoins. If the ISR hits the minimum, writes stop. |
| The metadata quorum loses its majority | No new leader elections or topic changes. Existing leaders and consumers keep working. Restore the quorum first; alert at once. |
| A network partition isolates an old leader | It keeps accepting acks=1 writes for a moment, but with acks=all it cannot reach the ISR and refuses. The controller elects a new leader with a higher epoch, and the old leader's log is truncated when it rejoins. |
| A producer retries after a lost ack | The idempotent producer's sequence number makes the broker drop the repeat, so the message is stored once. |
A partitioned, replicated, append-only log. Producers batch messages by key to partition leaders. Followers in other zones pull from the leader, an in-sync set and a high watermark define what is safe, and acks=all with min.insync.replicas of 2 means an acknowledged message survives a broker or zone loss, at the cost of refusing writes when too few replicas remain. Consumers pull and track offsets in groups, with at-least-once delivery and exactly-once inside the system. A Raft quorum holds metadata, partition moves are throttled, tenants have quotas, and old data moves to object storage.
| Decision | What we gain | What it costs |
|---|---|---|
| A log, not a per-message queue | Huge throughput, replay and many independent readers. | No per-message ack, delay or priority. Order only inside a partition. |
| acks=all with min.insync.replicas = 2 | No acknowledged message lost when one broker or zone fails. | Write latency of the slowest in-sync follower, and refused writes when too few replicas are left. |
| No unclean leader election | No rewritten history, no confirmed loss. | A partition can stay offline until a good replica returns. |
| At-least-once delivery by default | Nothing is lost, and the consumer is simple. | Duplicates are possible, so consumers must be idempotent. |
| Replication, not fsync per message, for durability | Far higher throughput. | A simultaneous power loss in all zones could lose the last few messages. |
| Tiered storage | 36 small brokers instead of 87, and fast replacements. | Slower reads of old data, and a dependency on object storage. |
Show that you know why it is fast and what order really means.
The core of the question. Walk through each failure and say what is lost.
Delivery guarantees are where answers get sloppy. Be exact.
Where interviewers push once the core is solid.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Per-message acknowledgement, retry and delay (a task queue) | Add per-message state: visibility timeout, retry count, dead-letter after N tries, and a delay. Throughput falls. Often a separate queue service next to the log is better. |
| Strict global ordering | One partition for the topic, which caps throughput at one leader and one disk. Or assign sequence numbers upstream and re-order in the consumer. |
| Zero message loss even in a full-site power failure | fsync before acknowledging (or replicas on durable media in separate sites), synchronous replication across nearby sites, and a larger latency budget. |
| Cross-region active-active | A mirror in each direction, topic prefixes by region, idempotent consumers, and rules for conflicting keys. Offsets are translated between clusters. |
| Millions of tiny topics (one per user) | Topics and partitions are heavy. Use a single topic keyed by user and filter in the consumer, or a different system built for many lightweight queues. |
| Long retention for audit (years) | Tiered storage plus a cold archive, compaction where possible, and a separate reader path for old data. Plan for erasure requests. |
| Consumers need to query by field, not just by offset | Add an indexer or a stream-processing job that writes to a search or database store. The log stays the source of truth. |
| Messages up to 100 MB | Claim-check through object storage. Keep log messages small, and put a link, size and checksum in them. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts with brokers. Does not ask about replay, ordering or loss. | Distinguishes log from queue, asks about order, durability and throughput. | Also settles delivery semantics, retention, tenants and zone failure, and writes the scope down. |
| Estimation | No numbers, or only messages a second. | Gets ingest, replication and storage for the retention period. | Includes read fan-out, finds that network and storage force different broker counts, and uses it to justify tiering and the partition count. |
| Design | A single queue server with a database. | Partitions, replicas, producers and consumers with offsets. | Explains why the log is fast, the ISR and high watermark, the metadata quorum, group coordination and tiered storage. |
| Correctness | Says nothing is lost, or exactly-once everywhere. | Knows acks levels and at-least-once. | States the invariant, shows what each setting can lose, covers leader epochs, idempotent producers and transactions, and their limits. |
| Trade-offs | One choice presented as obvious. | Compares acks settings and partition counts. | Names the cost of each choice (refused writes, no global order, duplicates) and says when to choose differently per topic. |
| Operations | No failure plan. | Mentions broker failure, lag and basic metrics. | Covers throttled moves, rolling upgrades, quotas, rebalance storms, quorum failure and failure-injection testing. |
| Mistake | Do this instead |
|---|---|
| Designing a task queue when the problem asks for a log (or the reverse) | Ask first whether messages are kept for replay and read by many groups, then choose. |
| Promising global ordering | Say order is per partition, chosen by key, and explain the cost of one partition. |
| Saying exactly-once without limits | Say at-least-once by default, exactly-once inside the system with idempotent producer and transactions, idempotent consumers outside. |
| Using acks=1 for important data and calling it durable | Show the loss window, and use acks=all with a minimum in-sync set. |
| Ignoring what happens when too few replicas remain | State the choice: refuse writes (safe) or allow loss (available), per topic. |
| Choosing the partition count without numbers, or raising it casually later | Derive it from throughput and consumer parallelism, and leave headroom, because key mapping changes. |
| Moving partitions at full speed | Throttle moves and only drop the old replica after the new one joins the ISR. |
| Putting huge payloads or personal data in long-retention topics | Use claim-check for big files, and keep or encrypt personal data so it can be erased. |
The concepts behind this design: topics, partitions, offsets and groups.
Why we chose a log, and when a queue is the better tool.
The append-only log idea that every broker partition is built on.
Leaders, followers and what copies protect against.
The majority idea behind the metadata quorum and safe elections.
The consensus algorithm that holds the cluster metadata.
At most once, at least once and exactly once, in detail.
What idempotence and transactions can and cannot give.
Order per key and per partition, and what it costs.
A typical consumer of a queue like this one.