SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design a Distributed Message Queue (Kafka-like)

A durable, ordered log that millions of messages a second flow through, with replication and consumer groups.

⏱ 38 min readHard case studyAdvanced25 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a distributed message queue, like Kafka.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Choosing the right abstractionA 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 fastMillions 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 windowThis 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 semanticsOrder 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 clusterAdding brokers, moving data without hurting traffic, noisy tenants, upgrades and monitoring are what make a design real.

TL;DRThe whole design in 60 seconds

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.

  • Scale: 1M messages a second of 1 KB is 1 GB/s in. With 3 copies the cluster writes 3 GB/s and stores about 260 TB a day, so we shard into about 300 partitions across about 36 brokers.
  • Why it is fast: sequential appends, batching and compression, the OS page cache, and zero-copy reads. No random disk access and no per-message acknowledgement.
  • Ordering: guaranteed inside one partition only. The key picks the partition, so all events of one key stay in order.
  • Durability: replication factor 3, producers use acks=all, and min.insync.replicas is 2. A confirmed message then survives the loss of one broker. If fewer than 2 replicas are in sync, we refuse writes (safe, but unavailable).
  • Delivery: at least once by default. An idempotent producer plus transactions give exactly-once inside the system. Anything outside it still needs idempotent consumers.
  • Operate it: a Raft metadata quorum, throttled partition moves, quotas per tenant, tiered storage for old data, and alerts on consumer lag and under-replicated partitions.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
8
16
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Log or task queue, ordering scope, delivery guarantee, retention and replay, throughput, and what may be lost.
2. Estimate3Ingest, replicated writes, storage for the retention period, brokers, and partitions.
3. API and data4Produce and fetch, offsets and groups, the segment-file layout.
4. High-level design8Producers, brokers, partition leaders and followers, metadata quorum, consumer groups. Follow one message.
5. Deep dives16The log, then replication and the loss window, then consumers and semantics, then operations, then retention.
6. Scale and failures7A dead broker, a slow follower, a rebalance storm, a lost zone, a noisy tenant.
7. Wrap up3Recap, the durability versus availability trade-off, and what you would build next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about whether a message is deleted once read, what order means, what “saved” means to a producer, and how long data is kept.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Create topics with a number of partitions and a replication factor
  • •Producers append messages (key, value, headers) and get back a partition and offset
  • •Consumers read from any offset, in order within a partition, and replay old data
  • •Consumer groups share the partitions of a topic, and track their position
  • •Retention by time or size, and optional compaction to keep the latest value per key
Non-functional (how well)
  • •Throughput: 1M messages a second sustained, 3M at peak, about 1 to 3 GB/s
  • •Latency: p99 produce acknowledgement under 10 ms
  • •Durability: a message that was acknowledged with acks=all survives the loss of one broker, and of one zone
  • •Availability: keep serving when one broker or zone fails, and say what we give up when too few replicas are left
  • •Order: preserved per partition. At-least-once delivery, with exactly-once inside the system
Out of scope (say it)
  • •Stream processing (joins, windows). That is an engine such as a streaming framework on top
  • •Per-message acknowledgement, delays and priorities (hard in a log)
  • •Cross-region active-active (we describe mirroring as an extension)
  • •A user interface for browsing messages
🎤
Say it out loud
“Let me confirm the scope. This is a log, not a task queue: producers append messages with a key, the topic is split into partitions, and several consumer groups read the same data and can replay it. Order is guaranteed per partition, so per key. I will design for 1 million messages a second, 3 million at peak, about 1 KB each, with 7 days of retention. A producer that asks for the strongest setting is told “saved” only when the message is on several brokers, and we must survive losing a broker or a zone. Delivery is at least once, with exactly-once inside the system as an extra. Stream processing and cross-region active-active are out of scope. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: messages a second to bytes a second, then multiply by 3 for replication and by the number of consumer groups for reads. Then storage for 7 days, and the number of brokers that network, disk and storage each force.

Assumptions (say them first)

AssumptionValue
Messages (sustained, peak)1M and 3M per second
Message sizeabout 1 KB (max 1 MB)
Replication factor3, across 3 zones
Consumer groups reading each message3 on average
Retention7 days online
Broker network10 Gbps, about 1.25 GB/s, planned to run at most 50% busy at peak
Broker diskabout 30 TB usable, kept at most 70% full, sequential writes about 400 MB/s
Producer batchabout 100 messages (about 100 KB) per request
Partition throughput target10 to 20 MB/s peak per partition

The arithmetic, line by line

WhatMathsResult
Ingest, sustained and peak1,000,000 × 1 KB, and 3,000,000 × 1 KB1 GB/s sustained, 3 GB/s peak
Messages per day1,000,000 × 86,40086.4 billion
Disk writes with 3 copies1 GB/s × 3, and 3 GB/s × 33 GB/s sustained, 9 GB/s peak
Follower traffic (2 copies sent between brokers)3 GB/s × 26 GB/s at peak
Consumer reads (3 groups)3 GB/s × 39 GB/s out at peak
Cluster network at peakin = 3 GB/s + 6 GB/s; out = 6 GB/s + 9 GB/s9 GB/s in, 15 GB/s out
Brokers forced by network15 GB/s ÷ (1.25 GB/s × 50%)24 brokers (before spare capacity)
Brokers forced by disk writes9 GB/s ÷ 400 MB/sabout 23 brokers
Spare capacity to lose a whole zone24 ÷ (2/3 of the cluster left)36 brokers
Raw data per day, and replicated1 GB/s × 86,400, then × 386.4 TB, and 259 TB per day
Seven days of retention, replicated259 TB × 7about 1.8 PB
Brokers forced by storage1.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 s65 TB replicated, about 1.8 TB per broker on 36
Partitions3 GB/s peak ÷ 10 MB/s per partition = 300about 300 partitions (about 8 leaders and 25 replicas per broker)
Per-partition load at 300 partitions1 GB/s ÷ 300, and 3 GB/s ÷ 3003.3 MB/s sustained, 10 MB/s peak
What the numbers tell us about the design
  • •Network, not disk speed, forces about 24 brokers. Reads multiply it: 3 groups make out-traffic 5 times the in-traffic.
  • •Storage for 7 days forces 87 brokers, almost 4 times more than throughput needs. That is the reason to use tiered storage: keep hours on brokers and the rest in object storage.
  • •With tiering, 36 brokers (sized to survive a lost zone) hold about 1.8 TB each. A replaced broker re-copies that in 30 minutes at 1 GB/s, not hours.
  • •300 partitions is a floor for throughput. The consumer count is capped by it (up to 300 consumers in a group). Too many partitions cost memory, files and slower elections, so we do not go to tens of thousands.
  • •Batching matters: 1M messages a second is only about 10,000 requests a second at 100 messages per batch, which is easy for a broker.
🎤
Say it out loud
“Let me do the maths. A million messages of 1 KB is 1 GB a second in, 3 GB a second at peak. With three copies that is 9 GB a second of disk writes at peak. With three consumer groups reading, the cluster sends out 15 GB a second, so network forces about 24 brokers, and 36 once I leave room to lose a zone. Storage is the bigger surprise: 7 days is 1.8 petabytes replicated, which would need 87 brokers, so I would use tiered storage and keep only the last few hours on the brokers. Then about 300 partitions at 10 MB a second each handle the peak.”

Step 3Define the API and the data modelabout 4 min

🤔
Pause. Try it yourself first
Write the produce call with the setting that says how safe it must be. Then the fetch call, and the three calls a consumer group needs. What does one message and one segment file look like on disk?

Endpoints

MethodPathRequestResponseNotes
POSTproduce(topic, key, value, headers, acks)batch of records, acks = 0, 1 or all, producerId, sequencepartition, base offset, timestamp per batchRecords 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.
GETfetch(topic, partition, offset, maxBytes, maxWaitMs)nonerecords from the offset, plus the high watermarkA 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).
POSTjoinGroup(group, topics)member id, supported assignment strategiesgeneration, assigned partitionsSent to the group coordinator (a broker). Triggers a rebalance when members come or go.
POSTheartbeat(group, generation)noneOK or REBALANCE_IN_PROGRESSProves the consumer is alive. A stale generation is rejected, so a zombie consumer cannot commit.
POSTcommitOffset(group, topic, partition, offset)noneOKStored in an internal compacted topic. Commit after processing for at-least-once, before for at-most-once.
POSTcreateTopic(name, partitions, replicationFactor, config)noneOKAdmin. The controller assigns replicas to brokers in different zones. Config sets retention, min.insync.replicas and compaction.

Data model

On disk, per partition replicaWhat it holdsWhy it is there
segment files (about 1 GB each)Messages in offset order, appended at the endSequential writes. Retention deletes whole old segments, which is cheap.
offset index (sparse)One entry for every few KB: offset → file positionFinds a message by offset with a small lookup and a short scan.
time index (sparse)Timestamp → offsetLets a consumer start from a point in time.
leader epoch fileWhich leader (and its epoch) wrote which offsetsLets a follower cut its log correctly after a leader change.
checkpoint of the high watermarkThe last offset known to be on all in-sync replicasDecides what consumers may read after a restart.
One message (record)TypeNotes
offset64-bit, per partitionPosition in the partition. Never reused.
timestamp64-bitSet by the producer or the broker.
keybytes, optionalPicks the partition. Same key, same partition, same order.
value, headersbytes, mapThe payload. Large payloads go to object storage, and the message holds a link (claim check).
producerId, sequence64-bit, intUsed to drop duplicate retries from one producer.
Where a message ends up
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)
📝Which store, and why
The messages live in plain append-only files on each broker's local disk, one set per partition replica. A database would add random writes, locks and per-row overhead that we do not need: we only append and read ranges in order, which a file does best, and the operating system's page cache makes recent reads free. Cluster metadata (topics, partition leaders, who is in sync) is tiny and needs strong consistency, so it lives in a small Raft quorum. Old segments can move to object storage, because they are immutable files.
🎤
Say it out loud
“Producing is one call with a batch of records, a key, and an acks setting, and it returns the partition and offset. Fetching is a long poll from an offset, and it only returns data below the high watermark. A consumer group uses join, heartbeat and commit-offset calls, sent to a coordinator broker. On disk, each partition replica is a set of one-gigabyte segment files with a sparse offset index and a time index. A message is an offset, a timestamp, a key, a value and headers, plus a producer id and sequence number so retries can be de-duplicated.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw one message's journey: from a producer, to a leader, to its followers, to a consumer. Which box decides who the leader is? Which box remembers where the consumers are?
Distributed message queue: high-level design
📤Producerskey → partition, batch, compress
→↓produce
Broker cluster (3 zones)
👑Partition 7 leaderBroker 1, zone A
📑FollowerBroker 4, zone B
📑FollowerBroker 9, zone C
→↓fetch
📥Consumer groupspull, commit offsets
Control plane
🗳️Metadata quorum (Raft)3 or 5 nodes: leaders, ISR, topics
🧭Controllerelects leaders, moves partitions
Coordination
🤝Group coordinatormembers, assignments, offsets
🗂️Offsets topicinternal, compacted
Storage
💾Local diskssegments, page cache
🪣Object storageold segments (tiered)
Operations
📊Metrics and alertslag, under-replicated
🛡️Quotas and ACLsper client
Each partition has one leader and followers in other zones. Followers pull from the leader. The metadata quorum picks leaders. Consumers pull and track offsets.
ComponentWhat it does
Producer clientChooses the partition from the key, groups messages into compressed batches, retries, and carries a producer id and sequence numbers.
BrokerHosts 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 followersOne leader per partition, followers in other zones. Followers pull new messages. The leader tracks which followers are in sync (the ISR).
Metadata quorum and controllerA 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 coordinatorA broker that owns a consumer group: tracks members through heartbeats, assigns partitions, and stores committed offsets.
Page cache and disksWrites append to a segment file and reach the OS page cache first. Recent reads are served from memory, and old reads from disk.
Tiered storageClosed segments older than a few hours are copied to object storage. Brokers keep only the recent tail.
Quotas, ACLs and metricsLimit bytes a second per client, control who may read or write which topic, and expose lag, under-replicated partitions and latency.
Write path (follow one request)
  1. The producer picks a partition: hash(key) mod partition count (or round robin without a key), and adds the message to a batch for that partition.
  2. When the batch is full or the linger time ends (a few milliseconds), the producer compresses it and sends it to that partition's leader, with its producer id and sequence number.
  3. The leader checks the sequence number (drops a repeat), appends the batch to the end of its active segment file, and assigns offsets.
  4. The followers, fetching in a loop, copy the new data and report how far they have got. The leader moves the high watermark to the lowest offset that every in-sync replica has.
  5. With acks=all, the leader answers the producer only once the ISR has the batch (and the ISR has at least min.insync.replicas members). With acks=1 it answers right after its own write. With acks=0 there is no answer.
  6. If the write fails or times out, the producer retries the same batch with the same sequence numbers, so a repeat is dropped instead of stored twice.
Read path (follow one request)
  1. A consumer joins its group. The coordinator assigns it some partitions and gives it the last committed offset for each.
  2. The consumer sends fetch(partition, offset, maxBytes) to the partition leader and waits (a long poll) for data or a timeout.
  3. The broker finds the file position with the sparse offset index, then sends the bytes straight from the page cache to the network (zero-copy), up to the high watermark.
  4. The consumer processes the batch. It then commits the new offset to the coordinator, which stores it in the internal offsets topic.
  5. A consumer that falls behind just keeps fetching older offsets. A new group can start from the earliest offset and replay everything still kept.
  6. If the consumer dies, it misses heartbeats, the group rebalances, and another member continues from the last committed offset.
🎤
Say it out loud
“Here is the picture. Producers batch messages by key to partition leaders. Each partition lives on three brokers in three zones: a leader that takes writes and two followers that pull from it. The leader keeps an in-sync replica set and a high watermark, and with acks=all it answers a producer only when the in-sync replicas have the batch. A small Raft quorum holds the metadata and a controller elects new leaders from the in-sync set when a broker dies. Consumers pull from a leader at an offset, read only below the high watermark, and commit their offsets to a group coordinator. Old segments move to object storage.”

Step 5Deep dive into the hard partsabout 16 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

The log, and why it is fast

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.

OptionHow it worksGoodBad
A database table of messagesInsert 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 acknowledgementKeep 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 positionAppend 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 logSplit 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.
Pick
A partitioned, append-only, replicated log

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 keyWhat to know
Count from throughputPeak 3 GB/s ÷ 10 MB/s per partition = 300. Also enough partitions for the biggest consumer group (parallelism is capped by the count).
Too fewA partition becomes a throughput ceiling, and a consumer group cannot use more machines.
Too manyMore open files, memory, replication traffic, slower leader elections and longer recovery. Thousands per broker is a warning sign.
Changing the count laterhash(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 keyOne 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 keyRound robin or sticky batches spread load evenly but give no order.
📝Zero-copy in one line
Without it, a read goes disk → kernel → application → kernel → network (four copies). With 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.
🎤
Say it out loud
“A database or per-message acks would not reach this rate. So I would use a partitioned append-only log. Writes are sequential appends in batches of about a hundred messages, compressed. The broker keeps no per-message state, so the consumer just remembers an offset. Recent data is served from the page cache, and reads use zero-copy. The partition is the unit of order and parallelism: the key hashes to a partition, so a key stays in order, but there is no order across partitions. I would pick the partition count from throughput, about 300 here, and leave headroom, because changing it later reshuffles keys.”
5.2

Replication and the loss window

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.

OptionHow it worksGoodBad
No replicationOne 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.
Pick
Leader and followers with an in-sync set, acks=all, replication factor 3 and min.insync.replicas = 2

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.

SettingWhat the producer is toldWhat can be lost when the leader dies
acks=0Nothing. It does not wait.Anything not yet copied, with no error at all.
acks=1“Saved” once the leader wrote itMessages 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 itIf 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 replicasNothing acknowledged, while a second replica survives. Writes are refused if fewer than 2 are in sync.
ConceptMeaningWhy it exists
ISR (in-sync replicas)The leader plus followers that are caught up within a time limitA slow follower is dropped, so it cannot hold up every write.
High watermarkThe highest offset that every ISR member hasConsumers read only up to it, so they never see data that could vanish.
Leader epochA number that grows with each new leaderAfter an election, a follower cuts its log back to where the new leader's epoch starts, so logs cannot silently diverge.
Unclean electionChoosing a leader that is not in the ISRTrades possible loss for availability.
Rack-aware placementReplicas spread over zonesA zone failure then costs at most one replica.
⚠️fsync: where the durability really comes from
We usually do not flush to disk after every message. The data is on the leader's page cache and on followers. A power loss that hits all three zones at once could lose the last few messages. We accept that, because replication across zones is the durability, and flushing every message would cut throughput badly. Say it out loud, and offer a per-topic flush setting for the rare topic that needs it.
After the leader dies (what the controller does)
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
🎤
Say it out loud
“I would use a leader and followers with an in-sync set, a replication factor of three across three zones, acks=all and min in-sync replicas of two. The invariant is that an acknowledged message sits on at least two replicas and a new leader is picked only from the in-sync set. That survives any one broker or zone. The cost is that if two replicas are down, we refuse writes: safety over availability. Unclean election would bring the partition back faster but can lose confirmed messages, so I turn it off for important data. Use the visualizer to see what each acks setting loses.”
5.3

Consumers, groups and delivery semantics

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.

OptionHow it worksGoodBad
Push from the brokerThe 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 consumerThe 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 processingSave 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 handlingProcess, 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.
Pick
Pull consumers in groups, commit after processing, and an idempotent producer plus transactions for exactly-once inside the system

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 eventWhat happensCost
Consumer joins or leavesThe coordinator starts a rebalance and reassigns partitionsEager: everyone stops while it happens. Cooperative: only moved partitions pause.
Consumer is slow to heartbeatDeclared dead, partitions move awayToo aggressive: false alarms and rebalance storms. Too lax: slow recovery.
Zombie consumer commits lateRejected: its group generation is oldStops a paused consumer from overwriting newer progress.
Poison messageProcessing keeps failing on one messageRetry a few times, then park it in a dead-letter topic so the partition keeps moving.
Consumer is behindLag (latest offset − committed offset) growsAlert on it. Add consumers (up to the partition count), or fix the slow step.
💡Parallelism is capped by partitions
A group with 300 partitions can use at most 300 busy consumers. A 301st sits idle. If one slow consumer holds back one partition, only that partition lags, because order is per partition.
🎤
Say it out loud
“Consumers pull, which gives back pressure and cheap replay: the consumer owns an offset. I commit after processing, so the worst case is a repeat and never a loss, and I make the work idempotent. For exactly-once inside the system I use an idempotent producer, with a producer id and sequence numbers so the broker drops retried batches, and transactions that write the output and commit the input offset atomically. Anything outside the log, like an email or a payment, still needs an idempotent consumer. Groups rebalance when members change, and I would use cooperative rebalancing and poison-message handling with a dead-letter topic.”
5.4

Running the cluster: metadata, scaling and tenants

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.

OptionHow it worksGoodBad
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 speedStart 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 movesSet 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.
Pick
A Raft metadata quorum, rack-aware placement, throttled incremental partition moves, and per-client quotas

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.

OperationHow to do it safely
Add brokersJoin empty, then move partitions with a throttle. Also rebalance leaders so each broker leads about the same number.
Broker failsController elects new leaders from the ISR (seconds). The data is re-copied to a replacement in the background.
Disk failsWith several disks per broker, only the partitions on that disk need re-copying. Others keep running.
Rolling upgradeOne broker at a time: move its leaders away, restart, wait for it to rejoin the ISR, then the next. Keep versions compatible.
Noisy tenantByte-rate and request-rate quotas per client id. Critical workloads get a separate cluster.
SecurityTLS in transit, authentication of clients (for example SASL or mutual TLS), ACLs per topic, and encryption at rest on the disks.
Multi-regionMirror topics asynchronously to another region. Offsets differ between clusters, so consumers need offset translation. Active-active needs conflict rules.
🎤
Say it out loud
“Cluster metadata goes in a small Raft quorum: topics, leaders and the in-sync sets. If it loses its majority, existing leaders keep serving, but nothing can change, so I protect it. To grow the cluster I add empty brokers and move partitions with a replication throttle, a few at a time, dropping the old replica only after the new one has joined the in-sync set. With tiered storage, each broker holds only hours of data, so moves take minutes. Per-client quotas slow a runaway producer, and critical traffic gets its own cluster. Upgrades are rolling, one broker at a time.”
5.5

Retention, compaction and tiered storage

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.

OptionHow it worksGoodBad
Delete by time or sizeDrop 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 compactionKeep 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 brokersLarge retention on local disks.Simple, and fast replays.Storage forces 87 brokers, not 36. A replaced broker re-copies terabytes.
Tiered storageKeep 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.
Pick
Time-based deletion by default, compaction for state topics, and tiered storage for the long tail

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.

QuestionAnswer
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.
🎤
Say it out loud
“Most topics delete whole segment files after 7 days, which is cheap. Topics that hold state use compaction so only the latest value per key remains, and a tombstone deletes a key. Keeping 7 days on broker disks would force about 87 brokers, so I use tiered storage: roughly six hours local, the rest in object storage. That keeps brokers small, and a replaced broker copies about 2 terabytes, not tens. For deleting a person's data from an append-only log I would use a compacted topic with tombstones, or encrypt payloads and destroy the key, and I would say that compaction is not instant.”
VisualizerReplication, acks and a dying leader: what is lost?Pick acks, min.insync.replicas and what the followers are doing, then choose when the leader dies. Switch to “After the election” to see who takes over, which messages survive, and which confirmed ones are lost.
Producer setting (acks)
min.insync.replicas
Unclean leader election
Idempotent producer
What are the followers doing?
Show
In sync (ISR) when it dies:B1B2B3
Messages m1 to m5 on each replica, what the producer was told, and what consumers could read
Rowm1m2m3m4m5
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
·
·
High watermark
m3
readable by consumers
Producer errors
0
writes refused
New leader
B2
from the ISR
Confirmed but lost
1
m4
Repeats after retry
0
same message twice
Lost acknowledged messages: m4. With acks=1 the leader said OK before any follower copied the message. It died in between. B2 took over with only 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.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Run the day. A broker dies at peak. One follower is slow. A consumer group rebalances every few minutes. A zone is lost. One producer sends ten times its normal rate. What does each do to latency, to loss, to availability?

What breaks first, and the fix

BottleneckFix
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 brokerCap at a few thousand replicas a broker. Use fewer, larger partitions, or add brokers. Watch election time and open files.
Slow followers shrinking the ISRReplication lag limits, dedicated replication threads, and alerts on ISR shrink. A permanently slow broker is replaced.
Rebalance stormsCooperative rebalancing, static group membership, longer session timeouts, and no heavy work between polls.
Replica catch-up after a failureTiered storage makes it minutes. Throttle it so it does not starve live traffic.

What if a part fails?

FailureHow the design copes
A broker diesThe 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 lostAt 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 downThe 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 partitionedIt 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 majorityNo 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 leaderIt 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 ackThe idempotent producer's sequence number makes the broker drop the repeat, so the message is stored once.
What to monitor
  • •Under-replicated partitions and ISR shrink and expand rate (the first sign of trouble)
  • •Consumer lag per group and partition, and its growth over time
  • •Produce and fetch latency at p50, p99 and max, per broker
  • •Offline partitions and leader election rate
  • •Disk usage and the age of the oldest local segment, and tiering copy lag
  • •Bytes in and out per broker and per client, and quota throttling time
Security and abuse
  • •Encrypt traffic with TLS, and authenticate every client and broker
  • •ACLs per topic and per group: who may produce, consume or administer
  • •Quotas so one client cannot take all the bandwidth, and limits on connections
  • •Encrypt data at rest, and keep personal data out of long-retention topics (or encrypt it per person)
  • •Audit who changed topics and ACLs, and keep admin access separate from data access

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
A log, not a per-message queueHuge throughput, replay and many independent readers.No per-message ack, delay or priority. Order only inside a partition.
acks=all with min.insync.replicas = 2No 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 electionNo rewritten history, no confirmed loss.A partition can stay offline until a good replica returns.
At-least-once delivery by defaultNothing is lost, and the consumer is simple.Duplicates are possible, so consumers must be idempotent.
Replication, not fsync per message, for durabilityFar higher throughput.A simultaneous power loss in all zones could lose the last few messages.
Tiered storage36 small brokers instead of 87, and fast replacements.Slower reads of old data, and a dependency on object storage.
If we had more time, we would…
  • •Multi-region mirroring with offset translation, and a tested failover runbook.
  • •A schema registry, so producers and consumers agree on formats and can evolve them safely.
  • •Fetch from the nearest replica and rack-aware consumers to cut cross-zone traffic.
  • •Delayed and priority delivery built on top (timer topics), for the few use cases that need them.
  • •Chaos tests: kill brokers, partition the network, fill disks, and check that no confirmed message is lost.
🎤
Say it out loud
“To recap: a partitioned, replicated append-only log. Producers batch by key to partition leaders, followers in other zones pull, and an in-sync set with a high watermark decides what is safe to confirm and read. With acks=all and min in-sync replicas of two, a confirmed message survives losing a broker or a zone, and we pay with refused writes when too few replicas are left. Consumers pull in groups and track offsets, at least once by default, with exactly-once inside the system. A Raft quorum holds metadata, moves are throttled, tenants have quotas, and old data goes to object storage. Next I would add multi-region mirroring and chaos testing.”

Q&ACross-questions (25)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

The log and ordering

Show that you know why it is fast and what order really means.

Replication, durability and failure

The core of the question. Walk through each failure and say what is lost.

Producers, consumers and semantics

Delivery guarantees are where answers get sloppy. Be exact.

Operations, tenants and curveballs

Where interviewers push once the core is solid.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat 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 orderingOne 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 failurefsync before acknowledging (or replicas on durable media in separate sites), synchronous replication across nearby sites, and a larger latency budget.
Cross-region active-activeA 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 offsetAdd 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 MBClaim-check through object storage. Keep log messages small, and put a link, size and checksum in them.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts 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.
EstimationNo 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.
DesignA 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.
CorrectnessSays 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-offsOne 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.
OperationsNo failure plan.Mentions broker failure, lag and basic metrics.Covers throttled moves, rolling upgrades, quotas, rebalance storms, quorum failure and failure-injection testing.

AvoidCommon mistakes on this question

MistakeDo 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 orderingSay order is per partition, chosen by key, and explain the cost of one partition.
Saying exactly-once without limitsSay 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 durableShow the loss window, and use acks=all with a minimum in-sync set.
Ignoring what happens when too few replicas remainState the choice: refuse writes (safe) or allow loss (available), per topic.
Choosing the partition count without numbers, or raising it casually laterDerive it from throughput and consumer parallelism, and leave headroom, because key mapping changes.
Moving partitions at full speedThrottle moves and only drop the old replica after the new one joins the ISR.
Putting huge payloads or personal data in long-retention topicsUse claim-check for big files, and keep or encrypt personal data so it can be erased.

Revise60-second revision sheet

  • ✔What it is: a partitioned, replicated, append-only log. Consumers hold offsets. Replay is free.
  • ✔Why fast: sequential appends, batches and compression, page cache, zero-copy reads, no per-message state.
  • ✔Order: only inside a partition. The key picks the partition. Changing the count remaps keys.
  • ✔Scale (illustrative): 1M msgs/s × 1 KB = 1 GB/s. × 3 copies = 3 GB/s writes. 7 days = 1.8 PB. About 300 partitions, 36 brokers with tiering.
  • ✔Durability: replication factor 3, acks=all, min.insync.replicas = 2, no unclean election.
  • ✔ISR and high watermark: consumers read only what every in-sync replica has. A new leader comes only from the ISR.
  • ✔Cost of safety: too few replicas means refused writes. Safety over availability, per topic.
  • ✔Delivery: at least once by default. Idempotent producer (id + sequence) and transactions for exactly-once inside. Idempotent consumers outside.
  • ✔Operate: Raft metadata quorum, throttled moves, quotas, cooperative rebalancing, tiered storage, alert on under-replicated partitions and lag.
  • ✔One line: “Append to a log, copy it to three zones before you say saved, and let each reader remember its own place.”

Read these topics next

Kafka Deep Dive→

The concepts behind this design: topics, partitions, offsets and groups.

Event Streaming vs Message Queues→

Why we chose a log, and when a queue is the better tool.

Write-Ahead Log (WAL)→

The append-only log idea that every broker partition is built on.

Replication→

Leaders, followers and what copies protect against.

Quorum (R + W > N)→

The majority idea behind the metadata quorum and safe elections.

Raft→

The consensus algorithm that holds the cluster metadata.

Delivery Semantics→

At most once, at least once and exactly once, in detail.

Exactly-Once Processing→

What idempotence and transactions can and cannot give.

Message Ordering→

Order per key and per partition, and what it costs.

Design a Notification System→

A typical consumer of a queue like this one.

← Previous
Design a Metrics and Monitoring System
Next →
Design an E-commerce System (Amazon)