The Problem#
A distributed message queue lets one program hand data to another without the two talking directly. A producer writes a message to the queue and moves on. A consumer reads it later, at its own pace. The queue sits in the middle, keeps the message safe until it is read, and spreads the load across many machines.
Almost every large system has one at its centre. An online shop publishes "order placed" events that the payment, inventory, email and analytics services all consume. A ride-hailing app queues ride requests so matching servers can take them one at a time. A video site puts "transcode this file" jobs on a queue for a fleet of workers. A monitoring system streams millions of metric samples per second through one. Apache Kafka, created at LinkedIn and described in "Kafka: a Distributed Messaging System for Log Processing" (Kreps, Narkhede and Rao, NetDB 2011), became the standard design for the high-throughput kind, and this case study designs a system in that style from scratch.
A queue for one small application is easy: a table in a database, or a list in Redis. It becomes hard when four things are true at once:
- Throughput is huge. Millions of messages per second, gigabytes per second, from thousands of producers.
- Nothing acknowledged may be lost. A message that the queue confirmed must survive disk failures, machine crashes and whole data-centre zone outages.
- Order matters. Events about the same order, user or account must be read in the order they were written, even though the system is spread over hundreds of machines.
- Many independent readers. Ten different services want every message, each at its own speed, and some want to re-read last week's data after fixing a bug.
The central idea that makes all four possible is to model the queue not as a set of messages that are deleted when read, but as an append-only log: a file that only ever grows at the end, split into many independent pieces (partitions) so it can be spread across machines, and copied to several machines so it survives failures. Readers do not remove messages; each one just remembers how far it has read.
Analogy. Think of a ship's logbook, or better, a set of logbooks in a busy harbour office. Every event (a ship arrives, cargo is unloaded) is written on the next empty line of a book, with a line number, and nothing is ever erased. There is one book per dock, so many clerks can write at the same time without waiting for each other. Each book has photocopies kept in other buildings, in case of fire. Anyone who needs the information (customs, the port authority, the shipping companies) keeps a bookmark with the last line they read and reads forward at their own pace. Old books are archived after a fixed period. Nobody has to tell the clerks who has read what, and a new reader can start from page one. This is exactly how a log-based message queue works.
Background: a few terms used in this design#
- Message (record): a small piece of data, typically 100 bytes to a few kilobytes, with an optional key (such as an order id), a value (the payload), a timestamp and optional headers.
- Topic: a named stream of messages of one kind, such as
ordersorpage-views. Producers write to a topic; consumers read from it. - Partition: a topic is split into partitions. Each partition is an ordered, append-only log stored on one machine (plus copies). Partitions are the unit of parallelism and of ordering.
- Offset: the position of a message within its partition: 0, 1, 2, and so on. An offset never changes and is never reused.
- Broker: a server that stores partitions and serves producers and consumers. A cluster has many brokers.
- Replica, leader and follower: each partition is stored on several brokers. One copy, the leader, accepts writes and (normally) serves reads. The others, followers, copy from the leader and can take over if it fails.
- Consumer group: a set of consumers that share the work of reading a topic. Each partition is read by exactly one member of the group at a time, so adding consumers (up to the number of partitions) adds throughput.
- Committed offset: the position a consumer group has recorded as "processed up to here". After a crash, the group resumes from it.
- Acknowledgement (ack): the broker's confirmation to a producer that a message has been stored. What "stored" means (on one machine, or on several) is configurable and is the core durability trade-off.
- Retention: how long messages are kept, for example 7 days, after which old data is deleted regardless of whether it was read.
- Consumer lag: how far behind a consumer is: the newest offset in the partition minus the consumer's committed offset.
Queue versus log. Classic message brokers such as RabbitMQ or Amazon SQS are queues: a message is delivered to one consumer and deleted once acknowledged. Kafka-style systems are logs: messages stay for the retention period and any number of consumer groups read them independently. A log can act as a queue (one consumer group sharing partitions) or as a publish/subscribe stream (many groups each reading everything). We design the log, and in Deep Dive 10 show how to provide queue features (per-message retries, dead-letter queues, delays) on top of it. For the wider comparison, see Asynchronous Processing and Message Queues and Pub/Sub and Event Streaming.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| Is this a work queue (each message processed once, then gone) or an event log (many readers, replay)? | An event log that can also serve as a work queue | Decides whether messages are deleted on ack or retained, and how consumers track progress |
| What throughput? | 1 million messages per second on average, 3 million at peak, across all topics | Sizes the number of brokers, partitions and network capacity |
| Message size? | Average 1 KB, maximum 1 MB; larger payloads go to object storage with a pointer in the message | Big messages hurt batching, memory and replication; a 1 MB cap is standard |
| How long are messages kept? | 7 days by default, configurable per topic, up to "forever" for some topics | Storage is the largest cost; long retention suggests tiered storage |
| Ordering guarantees? | Order preserved per key (per partition), not across the whole topic | Global order would force one partition and kill throughput |
| Delivery guarantee? | At-least-once by default; exactly-once available for producer-to-log and read-process-write pipelines | Determines acks, idempotent producers and transactions |
| Durability target? | An acknowledged message survives the loss of any one broker, and of one availability zone | Replication factor 3 across 3 zones, acks from all in-sync replicas |
| Latency target? | p99 publish-to-consume under 50 ms within a region; p50 a few milliseconds | Allows batching of a few milliseconds, but no waiting for slow disks on every message |
| How many readers per topic? | Typically 1 to 10 consumer groups, some topics up to 50 | Outbound traffic is a multiple of inbound; sizes the network |
| How many topics and partitions? | Thousands of topics, up to a few hundred thousand partitions in total | Metadata management and controller design must scale |
| Multi-tenant? | Yes, many teams share the cluster, with quotas per client | Needs quotas, authentication and isolation |
| Multi-region? | One cluster per region; selected topics mirrored to other regions asynchronously | Avoids cross-region latency on every write; defines disaster-recovery behaviour |
Requirements#
Functional#
- Producers can publish messages to a named topic, optionally with a key, and receive an acknowledgement once the message is durably stored.
- Consumers can read messages from a topic in order within each partition, either individually or as part of a consumer group that shares the partitions, and can commit their position so they resume after a restart.
- Messages are retained for a configurable time or size per topic, independently of whether they were read, so consumers can replay from any retained offset (including from the beginning, or from a point in time).
- Operators can manage topics: create topics with a partition count and replication factor, increase partitions, change retention, and add or remove brokers without downtime.
Out of scope: message transformation and routing rules inside the broker (that is stream processing, done by consumers such as Flink), schema management (a separate schema registry), and the client-facing APIs of services that use the queue.
Non-Functional#
- Throughput: 1 million messages per second on average, 3 million at peak, about 1 GB/s in and 3 GB/s out on average. The cluster must scale roughly linearly by adding brokers.
- Durability: no acknowledged message lost after the failure of any single broker or of one availability zone. This is the most important requirement: a queue that loses data silently is worse than one that is slow.
- Availability: 99.99% for publishing to a topic (about 52 minutes of downtime per year). Leader failover within seconds.
- Ordering: messages with the same key are delivered in the order they were acknowledged.
- Latency: p99 under 50 ms from publish to delivery within a region, under normal load.
- Retention: 7 days by default; the design should support months to years cheaply for selected topics.
- Scalability of metadata: thousands of topics and hundreds of thousands of partitions, with fast leader elections.
Which matter most? Durability first, then availability and throughput, then latency. We will happily add a few milliseconds of batching delay to gain an order of magnitude in throughput, and wait for a replica's acknowledgement to gain durability. The consistency model we promise is also explicit: total order per partition, nothing across partitions. Being precise about this is half of a good answer, because "the queue preserves order" is ambiguous and is where many designs go wrong.
Capacity Estimation#
Only the numbers that change the design.
Inbound traffic.
- 1 million messages per second × 1 KB = about 1 GB/s on average, 3 GB/s at peak.
- Producers batch and compress messages (LZ4 or zstd). Text formats such as JSON typically compress 3 to 5 times in batches; assume 4 times. On the wire and on disk that is about 250 MB/s average, 750 MB/s peak.
Replication and disk writes.
- Replication factor 3 means each byte is written to 3 brokers: 750 MB/s of disk writes across the cluster on average, 2.25 GB/s at peak.
- Of that, 2 of every 3 copies cross the network between brokers: 500 MB/s of replication traffic on average.
Outbound traffic.
- With an average of 3 consumer groups per topic, consumers read 750 MB/s compressed (3 GB/s of uncompressed messages) on average. Brokers send compressed batches as they are stored; consumers decompress. Outbound is usually larger than inbound in a log system, and it is the reason "fan-out to many readers" must be cheap.
Storage.
- Per day: 250 MB/s × 86,400 s ≈ 21.6 TB per day compressed, times 3 replicas ≈ 65 TB per day.
- Seven days of retention: about 450 TB of disk across the cluster.
- This is the number that sizes the cluster. With 24 TB of usable disk per broker, kept at most half full for headroom and rebalancing, we need about 40 brokers for storage alone.
Per-broker load at 40 brokers.
- Messages: 3 million per second at peak / 40 ≈ 75,000 per second per broker, well under the commonly quoted rough ceiling of around a million small messages per second for a well-tuned broker.
- Network: peak inbound 750 MB/s + replication 1.5 GB/s + outbound 2.25 GB/s ≈ 4.5 GB/s across the cluster, about 110 MB/s per broker, a small fraction of a 25 Gbit/s (about 3 GB/s) network card.
- So storage, not throughput, determines the broker count. Deep Dive 7 shows how tiered storage (old segments moved to object storage) changes this: keeping only 1 day on local disks cuts local storage to about 65 TB, and the cluster can then be sized for throughput and partition count instead.
Partitions.
- A partition is consumed by one consumer per group, so partition count caps consumer parallelism. A common sizing rule is "enough partitions that each handles at most about 10 MB/s", so a consumer can keep up comfortably. Peak 3 GB/s / 10 MB/s ≈ 300 partitions minimum for throughput.
- In practice the count is driven by the number of topics and their consumer parallelism: assume 50,000 partitions across thousands of topics, so 150,000 replicas, about 3,750 per broker on 40 brokers. Older guidance for ZooKeeper-based Kafka suggested staying around a few thousand partitions per broker; the newer Raft-based metadata layer raises the cluster-wide limit substantially (Deep Dive 8).
Consumer offsets.
- 2,000 consumer groups × an average of 50 partitions each = 100,000 committed positions. With commits every 5 seconds, about 20,000 offset commits per second, a small write load that we store in the log itself (Deep Dive 4).
Latency budget.
- Producer batching (
linger): 0 to 10 ms, chosen per producer. - Leader append to page cache: well under 1 ms.
- Replication to two followers in other availability zones: about 1 to 3 ms round trip.
- Consumer long-poll wake-up and network: about 1 ms.
- So p50 of a few milliseconds and p99 under 50 ms are realistic; the tail comes from garbage-collection pauses, disk stalls and overloaded brokers, not from the protocol.
| Quantity | Estimate | Design implication |
|---|---|---|
| Messages per second | 1M average, 3M peak | Batch everything; one disk write per batch, not per message |
| Inbound bytes | 1 GB/s raw, about 250 MB/s compressed | Compress batches at the producer, store them compressed |
| Outbound bytes | About 3 times inbound | Serve reads from page cache, zero-copy, compressed batches |
| Disk across cluster | About 450 TB for 7 days at RF 3 | Storage sizes the cluster; consider tiered storage |
| Brokers | About 40 (storage-bound) | Rebalancing and partition moves are routine operations |
| Partitions | About 50,000 (150,000 replicas) | Metadata must be scalable; fast leader election |
| Offset commits | About 20,000 per second | Store offsets in a compacted internal topic |
Core Entities#
- Topic: name, partition count, replication factor, and configuration (retention time and size, cleanup policy of delete or compact, maximum message size, minimum in-sync replicas).
- Partition: (topic, partition number). Has a leader, a replica set, an in-sync replica set, a log start offset, a high watermark and a log end offset.
- Replica: one copy of a partition on one broker.
- Segment: a chunk of a partition's log on disk (for example up to 1 GB or 7 days), with an offset index and a time index. Old segments are deleted or moved to object storage whole.
- Record batch: the unit of writing, storage and replication: a header (base offset, producer id, producer epoch, base sequence, compression type, timestamps, CRC) plus one or more records.
- Broker: a server with an id, rack (availability zone), listeners, and the replicas it hosts.
- Controller: the component that holds cluster metadata (topics, partition assignments, leaders, in-sync replica sets) and makes decisions such as leader elections.
- Producer: a client with an optional producer id and epoch, used for idempotence and transactions.
- Consumer group: group id, members, the assignment of partitions to members, and a generation number that increases with every rebalance.
- Offset commit: (group, topic, partition) → committed offset plus optional metadata.
API Design#
Producers and consumers talk to brokers over a binary protocol on long-lived TCP connections, not request-per-message HTTP. Throughput depends on batching many messages per request, pipelining several requests per connection, and avoiding per-request headers and connection setup. An HTTP or gRPC gateway can be offered for clients that cannot use the native protocol. The calls, written as remote procedures:
# Admin
CreateTopic(name, partitions, replicationFactor, configs) -> ok
CreatePartitions(name, newTotalCount) -> ok
AlterConfigs(topic, {retention.ms, cleanup.policy, min.insync.replicas, ...}) -> ok
# Discovery: which broker leads each partition
Metadata(topics[]) -> [{topic, partition, leader, replicas[], isr[]}]
# Produce: one request carries batches for many partitions led by this broker
Produce(acks = 0 | 1 | all, timeoutMs,
batches[{topic, partition, producerId, producerEpoch, baseSequence, records[]}])
-> [{topic, partition, baseOffset, error}]
# Fetch: long poll, returns as soon as minBytes are available or maxWaitMs passes
Fetch(isolation = read_uncommitted | read_committed, maxWaitMs, minBytes, maxBytes,
partitions[{topic, partition, fetchOffset}])
-> [{topic, partition, highWatermark, lastStableOffset, batches[]}]
# Find an offset by time, for replay ("from yesterday 09:00")
ListOffsets(topic, partition, timestamp | earliest | latest) -> offset
# Consumer groups
FindCoordinator(groupId) -> broker
JoinGroup / SyncGroup / Heartbeat / LeaveGroup (groupId, memberId, generation, ...)
OffsetCommit(groupId, generation, [{topic, partition, offset, metadata}]) -> ok
OffsetFetch(groupId, partitions[]) -> [{topic, partition, committedOffset}]
# Idempotence and transactions
InitProducerId(transactionalId?) -> {producerId, producerEpoch}
AddPartitionsToTxn / AddOffsetsToTxn / EndTxn(commit | abort)Notes:
- Clients route themselves. A client fetches metadata once, then sends each produce or fetch request directly to the leader of the partition. There is no proxy tier in the data path, which saves a network hop and a whole fleet of servers. A client that hits a broker which is no longer the leader gets a
NOT_LEADERerror and refreshes its metadata. - Idempotence is built into the protocol through (producer id, epoch, sequence number) on each batch, rather than requiring application-level idempotency keys (Deep Dive 3).
- Authentication and quotas are per connection: TLS or SASL authenticates the client principal, access-control lists authorise topic operations, and the broker throttles clients that exceed byte-rate or request-rate quotas (Deep Dive 11).
High-Level Design#
We build the design one requirement at a time, starting from the simplest thing that works.
1) Producers can publish messages#
Start simple: one server, one file. A single broker process accepts messages over TCP and appends each one to the end of a file. The position in the file (or a counter) is the message's offset. Appending to the end of a file is the fastest thing a disk can do: no seeks, sequential writes that hard drives handle at hundreds of MB/s and SSDs at GB/s. The operating system's page cache absorbs the writes, and the broker can acknowledge as soon as the data is in memory (or after fsync, see Deep Dive 1).
One file is one bottleneck. A single file on one machine limits throughput to that machine and allows only one writer at a time. So we split each topic into partitions, each its own append-only log, and spread partitions across many brokers. The producer decides the partition:
- With a key:
partition = hash(key) mod partitionCount. All messages with the same key go to the same partition, so they stay in order. - Without a key: spread messages across partitions for balance. Modern clients use a "sticky" approach: fill a batch for one partition, then move to another, which gives larger batches than strict round-robin.
Batching. The producer does not send each message separately. It collects messages per partition for a few milliseconds (linger) or until a batch reaches a size limit (for example 64 KB to 1 MB), compresses the batch, and sends one request per broker containing batches for all partitions that broker leads. One request may carry thousands of messages. The broker appends the whole batch as one unit, so per-message overhead almost disappears.
2) Consumers can read messages and commit their position#
Pull, not push. Consumers ask the broker for messages starting at an offset ("give me partition 7 from offset 1,000,200, up to 1 MB"). Pull lets each consumer go at its own speed, makes batching natural (one fetch returns many messages), and means a slow consumer never makes the broker buffer data for it. To avoid busy polling, a fetch is a long poll: if no new data exists, the broker holds the request until data arrives or a timeout (say 500 ms) passes.
Consumer groups for parallelism. A single consumer might not keep up with a busy topic. Consumers that share a group id divide the topic's partitions among themselves: with 12 partitions and 4 consumers, each consumer reads 3 partitions. Each partition is read by exactly one member of the group, which keeps per-partition order and avoids two consumers processing the same message. If a consumer dies, its partitions are reassigned (a rebalance). A different group reading the same topic gets its own copy of every message, which is how one topic serves many services.
Committed offsets. After processing messages up to offset 1,000,350, the consumer commits that position. After a restart, it resumes from the committed offset. Messages processed after the last commit are processed again, which is why the default guarantee is at-least-once (Deep Dive 5).
3) Acknowledged messages survive broker failures#
A partition on one broker is lost if that broker's disk dies. So each partition has replicas on several brokers (replication factor 3), placed in different availability zones. One replica is the leader: producers write to it, and it serves reads. Followers continuously fetch new data from the leader, exactly like consumers do, and append it to their own copy of the log.
The leader tracks which followers are in sync (caught up within a time limit such as 30 seconds). This set, the in-sync replicas (ISR), includes the leader. With acks=all, the leader acknowledges a write only when every replica in the ISR has it. If the leader dies, a new leader is chosen from the ISR, so it has every acknowledged message. Deep Dive 2 explains the exact rules (high watermark, leader epochs, minimum ISR size) that make this safe.
4) Messages are retained and replayable; operators manage the cluster#
Retention, not deletion on read. Each partition's log is split into segments (files of up to, say, 1 GB). The broker deletes whole old segments once they are older than the retention time (7 days) or the partition exceeds its size limit. Deleting a file is cheap, and reading does not change anything on disk. Because data stays, a consumer can replay from any retained offset, or find the offset for a timestamp ("restart from yesterday 09:00") through a per-segment time index. Some topics instead use log compaction, which keeps the latest message for each key indefinitely, making the topic a durable changelog of current state (Deep Dive 7).
A controller for cluster metadata. Someone has to decide which brokers hold which partitions, who leads each partition, and what to do when a broker dies. That is the controller: a small group of nodes (3 or 5) that keep the cluster metadata in a replicated log using a consensus protocol (Raft), with one active leader. The controller detects broker failures through heartbeats, elects new partition leaders from the ISR, and handles topic creation and partition reassignment. Brokers follow the metadata log and cache it locally, so producers and consumers can ask any broker for metadata. Kafka originally used ZooKeeper for this role and has since moved to its own Raft-based quorum, called KRaft (Deep Dive 8).
The full high-level design#
Components:
- Producers: client libraries that look up partition leaders, choose partitions by key, batch and compress messages, attach producer id and sequence numbers, retry on transient errors, and send directly to leaders.
- Partition leaders: the broker replica that accepts writes for a partition, assigns offsets, appends batches to the local log and serves consumer fetches (usually from the page cache, with zero-copy transfer).
- Followers: replicas that fetch from leaders and append the same bytes, so they can take over. They can also serve reads to consumers in their own zone to save cross-zone traffic.
- Group coordinators: each consumer group is managed by one broker (chosen by hashing the group id onto a partition of the internal offsets topic). It tracks members, runs rebalances and stores committed offsets in that internal, compacted topic.
- Transaction coordinators: manage producer ids and transactional state for exactly-once writes, stored in another internal topic.
- Local segments: the partition log on broker disks: segment files plus sparse offset and time indexes.
- Object storage (tiered): optional; closed segments are copied to S3-compatible storage, and only recent data stays on local disk.
- Controller quorum: three or five nodes holding the metadata log with Raft; the active controller assigns partitions, elects leaders, and fences failed brokers.
- Admin tools and rebalancer: create topics, change configurations and move partitions between brokers to balance disk and network (LinkedIn's open-source Cruise Control is a well-known example of such an automated rebalancer).
- Operations: metrics on consumer lag, under-replicated partitions, request latency and disk usage; mirroring of selected topics to clusters in other regions.
Key Flows#
Flow 1: publishing with acks=all#
- The producer accumulates 400 messages for partition 7 over a few milliseconds and compresses them into one batch.
- It sends the batch to the partition's leader with its producer id (42) and the sequence number of the first message (1,200).
- The leader checks that the sequence follows the last one it saw from producer 42 (rejecting duplicates and gaps), assigns offsets 5,000 to 5,399, and appends the batch to its log.
- Followers are already long-polling the leader; the new data wakes their fetch.
- The leader returns the batch to broker 5.
- Broker 8 fetches the same way.
- It receives the batch too.
- Each follower's next fetch asks for offset 5,400. This is how the leader learns that the follower has everything before 5,400; there is no separate acknowledgement message.
- The same for broker 8.
- All in-sync replicas now have offset 5,399, so the leader advances the high watermark to 5,400. Messages below the high watermark are committed and visible to consumers.
- The leader acknowledges the producer. Total time is typically a few milliseconds: one replication round trip on top of the append.
Flow 2: a consumer joins a group, reads and commits#
- The consumer finds the coordinator for group
billingand asks to join. - The coordinator starts a new generation (8) and picks one member (here A) to compute the assignment with the configured strategy.
- All members send SyncGroup; the leader member includes the assignment.
- Consumer B learns it owns partitions 3, 4 and 5.
- It asks for the group's committed offsets on those partitions.
- It receives the positions to resume from.
- It long-polls the leaders of those partitions; one fetch can cover several partitions on the same broker.
- Brokers return data up to the high watermark only, so the consumer never sees messages that could be lost in a failover.
- It processes the messages, for example writing billing records to a database.
- It commits the new positions, tagged with its generation; a commit from an older generation (a "zombie" consumer that lost its partitions) is rejected.
- Periodic heartbeats keep the membership alive; missing them for the session timeout triggers a rebalance.
Flow 3: a leader fails#
- Broker 3 crashes or is partitioned away, and its heartbeats to the controller stop.
- After the session timeout (a few seconds), the controller fences broker 3: its leadership is revoked in the metadata log, so even if it comes back it cannot act as leader.
- For each partition broker 3 led, the controller picks a new leader from the ISR and increments the leader epoch.
- Broker 5 learns from the metadata log that it now leads partition 7 at epoch 13.
- It starts accepting writes. Followers will reconcile their logs against the new leader using the epoch (Deep Dive 2).
- The producer's in-flight request to broker 3 fails or times out.
- The producer refreshes metadata and retries the same batch with the same sequence number. If the old leader had already replicated it before crashing, the new leader recognises the sequence and does not append it twice.
- The producer is acknowledged. Failover takes seconds, dominated by failure detection.
Data Model#
A message queue is itself a storage system, so its "data model" is mostly its own on-disk and metadata structures, not tables in another database.
Where each piece lives.
- Topic, partition, replica and broker metadata are records in the controller's Raft metadata log (for example "topic created", "partition 7 leader changed to broker 5 at epoch 13", "broker 3 fenced"). Every broker replays this log into an in-memory image. The metadata for 150,000 replicas is only tens of megabytes, so it fits in memory easily; the log is snapshotted periodically so new brokers do not replay from the beginning.
- Messages live in segment files per replica. A partition directory such as
orders-7/contains files named by the base offset of each segment:00000000000005000000.log(record batches),.index(offset index) and.timeindex(time index). The active segment is the only one being written; all others are immutable. - Committed offsets are messages in an internal, compacted topic (Kafka calls it
__consumer_offsets) with key (group, topic, partition) and value (offset, metadata, commit time). Compaction keeps only the latest commit per key. The group coordinator also caches them in memory. - Transaction and producer state live in another internal topic, and per-partition producer state (last sequence numbers per producer id) is rebuilt from the log itself and snapshotted.
The record batch on disk. Producers, brokers and consumers all handle the same binary batch, so the broker never decodes or re-encodes individual messages on the hot path.
| Field | Purpose |
|---|---|
| Base offset, batch length | Locate the batch and the offsets of its records |
| Partition leader epoch | Which leader wrote it; used to reconcile logs after failover |
| CRC | Detect corruption on disk or in transit |
| Attributes | Compression codec, timestamp type, transactional and control-batch flags |
| Last offset delta, first and max timestamp | Index building and time-based retention without decompressing |
| Producer id, producer epoch, base sequence | Idempotence and transactions |
| Records | Each record: length, timestamp delta, offset delta, key, value, headers (varint-encoded) |
Records inside a batch store deltas from the batch's base offset and first timestamp as variable-length integers, so a small message has only a few bytes of framing. The whole record section can be compressed as one block, which is why batching and compression are so effective together.
Why not a database table? The obvious first design is a messages table:
CREATE TABLE messages (
topic text,
id bigserial,
key text,
payload bytea,
created_at timestamptz DEFAULT now(),
claimed_by text,
claimed_at timestamptz,
PRIMARY KEY (topic, id)
);
-- A worker claims the next batch of unclaimed messages
UPDATE messages SET claimed_by = 'worker-17', claimed_at = now()
WHERE (topic, id) IN (
SELECT topic, id FROM messages
WHERE topic = 'orders' AND claimed_by IS NULL
ORDER BY id LIMIT 100
FOR UPDATE SKIP LOCKED)
RETURNING id, key, payload;FOR UPDATE SKIP LOCKED lets many workers claim different rows concurrently, and this is a perfectly good queue for thousands of messages per second (see PostgreSQL in Practice); several popular job libraries work this way. It fails at our scale for structural reasons: every message costs an index insert, an update when claimed and a delete later, each generating write-ahead log and (in PostgreSQL) dead tuples to vacuum. Multiple consumer groups would need a row per group per message, or a position per group, at which point we are building a log. And the table lives on one primary, so it cannot spread to 40 machines without sharding. The log design keeps the message bytes in sequential files and reduces "state per message" to nothing: the only per-reader state is one integer per partition.
Database choice. Messages need no general-purpose database at all: the broker's own log files are the store, because the access pattern (append at the end, read sequentially from an offset, delete whole old files) is exactly what a filesystem and page cache do best. The small amount of metadata needs strong consistency and ordering, so it goes in a Raft-replicated log inside the controller quorum rather than an external database. Offsets are stored in the log itself, which avoids a dependency and gives them the same durability and replication as messages. For the general reasoning, see Choosing a Database: A Decision Guide.
| Data | Store | Why |
|---|---|---|
| Messages | Segment files on broker disks, replicated 3 times | Sequential append and read, page-cache friendly, cheap whole-file deletion |
| Old messages (optional) | Object storage, tiered | Cheap long retention, brokers stay small |
| Cluster metadata | Controller quorum, Raft log plus snapshots | Strongly consistent, ordered, small |
| Committed offsets | Internal compacted topic | Same durability as messages, compaction keeps latest per key |
| Producer and transaction state | Internal topic plus per-partition snapshots | Survives failover so idempotence and transactions keep working |
Deep Dives#
1. How should a partition be stored on disk?#
The storage design decides throughput, latency and cost, so it is the first deep dive.
Basic: an in-memory queue. Keep messages in a list in the broker's memory and drop them once consumed. Very fast, but a crash loses everything, memory caps how much can be buffered, and nobody can replay. Redis lists and Redis pub/sub behave roughly like this unless persistence is configured; they are fine for best-effort signals, not for the durable backbone of a company.
Better: a database table. Durable and queryable, but every message costs index maintenance and updates (see the Data Model), and the store does not spread across machines without sharding.
Best: a segmented append-only log. Each partition is a directory of segment files. New batches are appended to the active segment; when it reaches a size limit (for example 1 GB) or an age limit, it is closed and a new one starts. Closed segments are immutable. Three properties make this fast:
- Sequential I/O only. Writes append; reads scan forward from an offset. Hard drives manage perhaps 100 to 200 random operations per second but 100 to 200 MB/s sequentially; SSDs are faster at both but still favour large sequential writes. A log gets the sequential numbers.
- The operating system's page cache is the cache. The broker does not keep its own in-process message cache. Writes go into the page cache and are flushed by the kernel; reads of recent data come from the page cache. Consumers that are caught up (the common case) read data that was written moments ago and is still in memory, so they cause no disk reads at all. Using the page cache rather than the heap avoids garbage-collection pressure (Kafka runs on the JVM), avoids storing data twice, and keeps the cache warm across broker process restarts.
- Zero-copy transfer. To send a range of a file to a socket, the broker can call
sendfile(), which copies directly from the page cache to the network card's buffers without passing through user space. Because batches are stored exactly as producers sent them (compressed) and consumers receive them unchanged, the broker never has to decode them. One caveat: with TLS encryption in user space, the data must be copied into the process to be encrypted, so zero-copy is lost unless the kernel performs TLS.
Finding an offset quickly. A consumer asks for offset 5,123,456. The broker:
- Finds the segment whose base offset is the largest one at or below 5,123,456, using an in-memory sorted map of segments (for example, the segment starting at 5,000,000).
- Searches that segment's offset index. The index is sparse: one entry roughly every 4 KB of log, mapping a relative offset (4 bytes) to a byte position in the file (4 bytes). A 1 GB segment has about 250,000 entries, a 2 MB index file that is memory-mapped, so binary search takes about 18 steps in memory.
- Reads forward from that byte position, at most a few kilobytes, until it reaches the batch containing the requested offset.
A time index maps timestamps to offsets the same way (12-byte entries: an 8-byte timestamp and a 4-byte relative offset), which serves "give me the offset for yesterday 09:00" and time-based retention.
When to call fsync. Writing to the page cache is not the same as writing to disk: a power loss on the machine loses data not yet flushed. Kafka's default is to not force fsync on every write and to rely on replication for durability: an acknowledged message is in the memory of three machines in three zones, and the chance of all three losing power before the kernel flushes is small. Systems such as Redpanda fsync before acknowledging (it markets this as a safety advantage), and Kafka can be configured to flush every N messages or milliseconds. The trade-off is correlated failures (a whole region losing power at once) against throughput and latency, since an fsync per batch costs from tens of microseconds on fast NVMe drives to milliseconds on network block storage. For our requirement (survive one broker or one zone), replication without per-write fsync is sufficient, and we say so explicitly.
Catch-up readers versus tail readers. A consumer replaying 3 days of data reads old segments that are not in the page cache. Those reads go to disk and, worse, pull cold data into the page cache, evicting the recent data that tail readers need. Mitigations: give brokers plenty of RAM for the page cache, use SSDs, throttle catch-up consumers with quotas, and with tiered storage (Deep Dive 7) serve old data from object storage through a separate path.
Disks. Brokers commonly use several independent disks (JBOD, "just a bunch of disks") with partitions spread across them, instead of RAID, because replication already provides redundancy across machines; losing one disk loses only the replicas on that disk, which are then rebuilt from other brokers.
2. How does replication keep acknowledged messages safe?#
Why a leader per partition. Ordering requires one place that assigns offsets, so each partition has a single leader that sequences writes. Spreading the leaders of 50,000 partitions evenly across 40 brokers means every broker is a leader for some partitions and a follower for others, so the write load is balanced even though each partition has one writer.
The in-sync replica set. A follower is in sync if it has fetched up to the leader's log end within a time limit (Kafka's replica.lag.time.max.ms, 30 seconds by default in recent versions). Followers that fall behind are removed from the ISR, and added back once they catch up. Changes to the ISR are recorded through the controller, so everyone agrees on who is eligible to become leader.
Two offsets per partition.
- Log end offset (LEO): the next offset to be written on a given replica.
- High watermark (HW): the smallest LEO among the ISR. Everything below it is on every in-sync replica, so it is committed: it will survive the loss of any replica that is not the last in-sync one. Consumers can only read below the high watermark. Followers learn the current high watermark from the leader's fetch responses.
Acks and minimum ISR. With acks=all, the leader acknowledges once the high watermark passes the batch. But "all in-sync replicas" could be just the leader if both followers dropped out, so on its own acks=all could silently mean "one copy". The min.insync.replicas setting closes this gap: with replication factor 3 and min.insync.replicas=2, a write is rejected (NOT_ENOUGH_REPLICAS) unless at least two replicas are in sync. This is the standard durable configuration: tolerate one failure and keep accepting writes; with two failures, stop accepting writes rather than accept writes that one more failure would lose.
ISR versus majority quorums. A Raft or Paxos group needs 2f + 1 replicas to tolerate f failures, because a majority must acknowledge each write. The ISR approach can tolerate f failures with f + 1 replicas, since every in-sync replica acknowledges each write and the controller (itself running consensus) decides membership. In practice both are configured with 3 replicas and 2 required acknowledgements, so the difference is in behaviour: ISR waits for all in-sync replicas (a slow follower adds latency until it is removed from the ISR, up to the lag limit), while a majority quorum waits only for the fastest majority, which gives better tail latency. Kafka chose ISR in its original design; Redpanda, a Kafka-compatible system, runs Raft per partition instead (see Consensus: Raft and Paxos).
Leader epochs and log truncation. When a leader changes, followers may have log entries the new leader does not (they were appended on the old leader but never committed). Followers must truncate those entries, or replicas would diverge. Early Kafka versions truncated to the high watermark on restart, which in certain double-failure sequences could lose committed data or leave replicas with different data at the same offset. Kafka 0.11 fixed this with leader epochs (KIP-101): every leader term has an epoch number, each replica keeps a small file mapping epoch → first offset of that epoch, and each batch records the epoch that wrote it. A follower that rejoins asks the leader: "what is the end offset of epoch 12?" and truncates to exactly that point before fetching.
Worked example.
- Leader A (epoch 12) has offsets 0 to 104. Follower B has 0 to 104. Follower C has 0 to 101 and is still in the ISR (it is only milliseconds behind). The high watermark is 102.
- A crashes. The controller elects B as leader, epoch 13. B's log ends at 104, but offsets 102 to 104 were never acknowledged to producers (the high watermark was 102). B keeps them; they will become committed once C catches up.
- C asks B for the end of epoch 12: answer 105 (the next offset after 104). C has nothing to truncate, fetches 102 to 104 from B, and the high watermark advances.
- A restarts. It also asks B for the end offset of epoch 12, gets 105, and keeps 0 to 104. Had A written offsets 105 and 106 in epoch 12 that never reached B, it would truncate them now, and their producers, never acknowledged, would have retried them.
Unclean leader election. If every in-sync replica is lost, two bad choices remain: wait until one returns (the partition is unavailable) or elect an out-of-sync replica (the partition is available but acknowledged messages are lost). Kafka exposes this as unclean.leader.election.enable, false by default since version 0.11. Our requirement prefers durability, so we keep it false and accept unavailability in this double-failure case.
Zones and rack awareness. Replicas of each partition are placed on brokers in different availability zones (Kafka's broker.rack), so losing a zone leaves two replicas of everything. Cross-zone replication costs money in public clouds (data transfer charges between zones), which becomes a meaningful part of the bill at 500 MB/s; fetch from follower (KIP-392, Kafka 2.4) lets consumers read from a replica in their own zone, removing cross-zone consumer traffic.
Preferred leaders. After failovers, leadership can bunch up on a few brokers. Each partition has a preferred leader (the first replica in its list), and the controller periodically moves leadership back to it, restoring balance. See Database Replication for the general replication trade-offs.
3. Producer acks, retries and idempotence#
The producer decides how much durability it pays for, per request, through acks.
| Setting | Broker replies when | Latency | What can be lost |
|---|---|---|---|
acks=0 | Never; the producer does not wait | Lowest | Anything: a network error or crash loses the batch silently |
acks=1 | The leader has appended the batch | Low, one network round trip | Batches the leader acknowledged but had not replicated before it died |
acks=all | All in-sync replicas have the batch (with min.insync.replicas as a floor) | One extra replication round trip, typically 1 to 3 ms across zones | Nothing, as long as at least one in-sync replica survives |
When each fits. acks=0 suits data where loss is acceptable and speed is everything, such as high-volume debug metrics. acks=1 was a common default for logs and clickstreams. acks=all is the right default for anything that represents business facts: orders, payments, state changes. Kafka made acks=all the default producer setting in version 3.0, along with idempotence.
Retries create duplicates. A producer sends a batch, the leader appends it, and the acknowledgement is lost because of a network glitch. The producer times out and retries; the leader appends the batch again. Now the log has two copies. Without help, retries turn "at-most-once" into "at-least-once with duplicates".
The idempotent producer. On start-up, the producer obtains a producer id (and an epoch) from the cluster. It numbers each batch per partition with a sequence number. The leader remembers, for each producer id and partition, the sequence numbers of the last few batches it appended (Kafka keeps the last five). Then:
- A retried batch with a sequence the leader has already seen is acknowledged again without being appended: the duplicate disappears.
- A batch whose sequence skips ahead (a gap, meaning an earlier batch was lost) is rejected with an out-of-order sequence error, so ordering cannot silently break.
- This per-producer state is stored with the log and rebuilt on the new leader after failover, so idempotence survives leader changes (Flow 3).
The cost is a few bytes per batch and a small table in memory per partition. It removes duplicates caused by producer retries within a producer session. It does not remove duplicates if the application itself crashes and sends the same business event again with a new producer id; that needs an application-level idempotency key (see Idempotency and Safe Retries) or transactions.
Ordering under retries. A producer may have several requests in flight to the same partition (pipelining) for throughput. If request 1 fails and request 2 succeeds, a naive retry of request 1 lands after request 2, reordering messages. Without idempotence, the only safe setting is one in-flight request per connection, which costs throughput. With idempotence, the broker's sequence check rejects request 2 until request 1 is in place, so up to five in-flight requests keep order (Kafka requires max.in.flight.requests.per.connection at most 5 for this guarantee).
Batching and compression in numbers. Suppose a producer sends 50,000 messages per second of 500 bytes to one partition.
- Without batching: 50,000 requests per second, each with tens of bytes of protocol overhead and a separate network round trip. A broker would spend most of its CPU on request handling.
- With
lingerof 5 ms: each batch holds about 250 messages, 125 KB. That is 200 requests per second. Compressed with zstd or LZ4 at 4 times, about 31 KB per request on the wire. - The cost is up to 5 ms of added latency per message. For most pipelines that is a good trade; latency-critical producers set
lingerto 0 and still batch whatever accumulates while the previous request is in flight.
Compression choice. Gzip compresses well but is CPU-heavy; Snappy and LZ4 are fast with moderate ratios; zstd (supported since Kafka 2.1) usually gives the best balance of ratio and speed. Compression happens on the producer and decompression on the consumer; the broker stores batches as they arrive, unless it is told to recompress to a different codec, which costs CPU and loses zero-copy.
Large messages. Keep messages small: our maximum is 1 MB, and most should be a few kilobytes. Large payloads (videos, documents, model outputs) belong in object storage, with a message that carries only the location (the claim-check pattern, see Pattern: Handling Large Files and Blobs). Big messages break batching, use broker memory in large chunks, slow replication for every other partition on the broker, and make consumer memory hard to bound.
Producer-side backpressure. The producer has a bounded buffer (for example 32 MB). If the broker is slow and the buffer fills, send() blocks for a configured time and then fails. That is the correct behaviour: the application learns that the system is overloaded instead of running out of memory. Applications that cannot block must decide what to do: shed load, spill to local disk, or return an error to their own callers.
4. Consumer offsets, consumer groups and rebalancing#
Why the consumer owns its position. A traditional broker tracks per-message state: delivered, acknowledged, redelivered. That is a lot of bookkeeping per message and per consumer. In a log, a consumer group's state per partition is one integer, the committed offset. The broker does no per-message work for readers, so adding a tenth consumer group costs only its read bandwidth. Rewinding is trivial: set the offset back.
Where offsets are stored. Commits are written as messages to the internal offsets topic, partitioned by group id (Kafka uses 50 partitions by default). The leader of the offsets partition that a group hashes to acts as that group's coordinator. The topic is compacted, so only the latest commit per (group, topic, partition) is kept. Before Kafka 0.9, offsets were stored in ZooKeeper, which was not designed for tens of thousands of writes per second; moving them into a Kafka topic was a scalability fix.
When to commit. The choice sets the delivery guarantee:
- Commit before processing: at-most-once. A crash after commit but before processing skips messages.
- Commit after processing: at-least-once. A crash after processing but before commit reprocesses messages. This is the usual choice, combined with idempotent processing.
- Commit atomically with the output: exactly-once for the pipeline, via transactions (Deep Dive 5) or by storing the offset in the same database transaction as the result.
Auto-commit is a trap for at-least-once. Kafka consumers by default commit periodically (every 5 seconds) whatever has been returned by poll(). If the application hands messages to a background thread and the consumer commits before that thread finishes, a crash loses those messages. Applications that process asynchronously should commit manually after processing.
Keep consumer work small and checkpoint often. The more work done between commits, the more is redone after a crash. A web crawler, for example, can split "download the page and store it in object storage" from "parse the stored page" into two consumers on two topics, so a parser crash never repeats a download. A ride-matching service can commit the offset of a ride request only after a driver is assigned, so a crashed matcher's requests are picked up by another instance.
Rebalancing. When a member joins, leaves or misses heartbeats, partitions must be reassigned.
- Eager rebalancing (original protocol): every member gives up all its partitions, the group leader computes a new assignment, and everyone resumes. Simple, but all processing in the group stops during the rebalance, a "stop the world" pause of seconds that grows with group size.
- Cooperative incremental rebalancing (KIP-429, Kafka 2.4): only partitions that need to move are revoked; others keep being processed. Rebalances become nearly invisible for stable members.
- Static membership (KIP-345, Kafka 2.3): members have a fixed instance id, so a rolling restart of a consumer within the session timeout does not trigger a rebalance at all.
- Broker-driven assignment (KIP-848): a newer protocol in which the coordinator, not a client leader, computes assignments incrementally, with members reconciling through heartbeats; it became generally available in Kafka 4.0, according to the project's release notes.
The coordinator tracks each group through a small state machine (these are the states of Kafka's classic group protocol):
- Empty: no members, but committed offsets may still exist, so a consumer that comes back resumes where the group left off.
- PreparingRebalance: the coordinator waits for current members to rejoin (up to the rebalance timeout).
- CompletingRebalance: members have joined; the coordinator waits for the leader member's assignment.
- Stable: everyone has an assignment and is consuming; heartbeats keep it here.
- Dead: the group's metadata is removed.
Assignment strategies. Range (contiguous partitions per member, which co-locates the same partition numbers of two topics on one member for joins), round-robin (even spread) and sticky (even spread while minimising movement). Sticky with cooperative rebalancing is the usual modern choice.
Zombies and fencing. A consumer that is paused (a long garbage-collection pause, a network blip) may be removed from the group while it still thinks it owns partitions. When it wakes, it might commit offsets or write results for partitions now owned by someone else. The generation id fences it: commits carry the generation, and the coordinator rejects commits from an old generation. The consumer must then rejoin. For external side effects (writes to a database), fencing requires the database writes to carry the generation or an offset too, or to be idempotent.
Consumer lag (log end offset minus committed offset, or better, the age of the oldest unprocessed message) is the most important metric of a consumer. It drives autoscaling (add consumers up to the partition count) and alerts. Lag that grows steadily means the consumer cannot keep up; lag that spikes and recovers is normal burst absorption, which is exactly what a queue is for. Queueing theory gives a quick check: by Little's law, the number of messages waiting equals the arrival rate times the average wait, so 200,000 messages of lag on a topic receiving 20,000 messages per second means data is about 10 seconds old.
5. Delivery guarantees and exactly-once processing#
Every message system has to answer: if something fails, can a message be lost, duplicated, or neither? (See Delivery Guarantees: At-Most, At-Least and Exactly-Once for the general theory.)
- At-most-once: never duplicated, may be lost. Producer with
acks=0or no retries; consumer commits before processing. - At-least-once: never lost, may be duplicated. Producer with
acks=alland retries; consumer commits after processing. This is our default, because duplicates can be handled downstream and losses cannot. - Exactly-once: each message affects the result once. In a distributed system this always means "at-least-once delivery plus deduplication or atomic commit", never a magic network.
Where duplicates come from, end to end.
- Producer retries after a lost acknowledgement. Fixed by the idempotent producer (Deep Dive 3).
- The producing application crashes and restarts, re-sending events it had already sent. Fixed by transactional ids (below) or application idempotency keys.
- A consumer processes messages and crashes before committing. Fixed by committing offsets atomically with the output.
- A consumer writes to an external system (a database, an email service) that has no idea about offsets. Fixed only by making that write idempotent or transactional with the offset.
Transactions for read-process-write pipelines. Kafka 0.11 (2017, KIP-98) added transactions so a stream processor can read from input topics, write to output topics and commit its input offsets atomically. The mechanism:
- The producer is configured with a stable transactional id (for example "invoice-processor-partition-3"). On start-up it registers with a transaction coordinator, which bumps the epoch for that id. Any older instance with the same id (a zombie) is fenced: its writes are rejected.
- During the transaction, the producer tells the coordinator which partitions it writes to, writes its output batches (marked transactional), and adds its consumer offsets to the transaction.
- To commit, the coordinator runs a two-phase commit internally: it records "prepare commit" in its transaction log (another internal topic), then writes commit markers (special control batches) into every partition touched, including the offsets topic, then records "complete".
- Consumers with
isolation.level=read_committedread only up to the last stable offset (LSO), the position before which all transactions are decided, and skip batches from aborted transactions.
- The processor registers its transactional id; the coordinator increments the epoch, so any zombie with the same id is now fenced.
- It reads an input batch and computes results.
- It declares the output partitions it will write to.
- It writes the results; they are in the log but invisible to read-committed consumers.
- It adds its consumer group's offsets to the transaction.
- It writes the input offsets, also as part of the transaction.
- It asks to commit.
- The coordinator, after logging the decision, writes commit markers into the output partitions.
- And into the offsets partition, so the input positions and the outputs become visible together.
- Downstream read-committed consumers now see the results. If the processor had crashed before step 7, the coordinator would abort, the outputs would be skipped, and the offsets would not move, so the input would be reprocessed with no visible duplicate.
Costs. Each transaction adds a few round trips and marker writes, so processors commit every 100 ms to a few seconds, not per message. Read-committed consumers see data only after the commit, which adds that interval to end-to-end latency. A long-open transaction holds back the LSO for its partitions, blocking read-committed consumers, so transactions have timeouts.
Limits. Kafka transactions cover Kafka only. An email sent or a row written to PostgreSQL inside the processing step is not rolled back by an abort. For external effects, the options are:
- Idempotent sinks: upsert by a deterministic key (such as the message's topic, partition and offset, or a business id), so replays overwrite rather than duplicate.
- Offsets stored with the output: write results and the consumed offset in one database transaction; on restart, read the offset from the database, not from Kafka.
- Two-phase-commit sinks in stream processors: Flink, for example, pre-commits to the sink during a checkpoint and commits when the checkpoint completes (see Apache Flink and Stream Processing).
- A deduplication table of processed message ids with a time-to-live, checked before acting, for side effects such as notifications.
Practical advice. For most services, at-least-once delivery plus idempotent consumers is simpler and enough. Reserve transactions for stream-processing pipelines that write back to the log and must produce exact aggregates (billing, ad-click counts).
6. Ordering: what we guarantee and how to keep it end to end#
The guarantee. Within one partition, every consumer sees messages in offset order, which is the order the leader appended them. Across partitions there is no order at all. With keyed partitioning, that becomes order per key, which is what most applications actually need: all events for order 123 in order, all events for user 456 in order.
Why not global order? A single partition has a single leader on a single machine and a single consumer per group. A well-tuned partition can handle tens of MB/s, but that is a hard ceiling for the topic. Global order is sometimes needed (a ledger with one sequence, a small configuration stream), and then a single partition is correct, as long as its throughput fits.
Choosing the key. The key must be the entity whose events need ordering, and it must be well distributed:
- Good: order id, account id, device id, video id for comments.
- Too coarse: country, tenant, or event type. A few values carry most of the traffic, producing hot partitions.
- Too fine: a random UUID per message. Even distribution, but no useful ordering.
A useful habit in interviews is to ask "what is the unit of consistency?" and use that as the key. For a sports-scores feed, the key is the match id: goals and substitutions for one match stay in order, and thousands of matches spread across partitions.
Changing the partition count breaks key placement. hash(key) mod 12 and hash(key) mod 24 put most keys in different partitions. After adding partitions, new messages for key K may go to a new partition while older ones sit unread in the old one, so a consumer could process them out of order. Options:
- Over-partition at creation time so the count never has to change (partitions are cheap within limits).
- For an increase, pause producers until consumers drain the topic, then resume with the new count.
- Create a new topic with the new count, dual-write or migrate, and switch consumers over at a known point.
Producer side. Ordering is the order of arrival at the leader. Two producers writing the same key race; the log records whichever arrives first. If the application needs causal order across producers, make one producer own each key (route by key upstream), or put a version number in the message so consumers can discard stale updates. Within one producer, idempotence keeps order across retries (Deep Dive 3).
Consumer side. The consumer can break order in three ways:
- Parallel processing within a partition. A consumer that hands messages to a thread pool processes them out of order. Fix: parallelise by key: hash each message's key to one of N worker queues, so different keys run in parallel and each key stays sequential. Some open-source consumer libraries do exactly this, committing an offset only when every message below it is done.
- Retries. If the message for key K at offset 100 fails and is sent to a retry topic, the message for K at offset 101 may be processed first. Options: block the partition and retry in place (simple, preserves order, but one poison message stops the whole partition: head-of-line blocking); or track "blocked keys": once a key has a message in the retry path, divert all later messages for that key too, until it clears. Many systems accept the reordering for retries, because most failures are transient and the business logic tolerates it.
- Rebalances. When a partition moves from consumer A to consumer B, B starts from the last committed offset, possibly reprocessing messages A already processed. The order is preserved but some messages repeat, which again argues for idempotent processing.
Ordering across distributed servers in realtime systems. Chat, live comments and collaborative apps face a related problem: messages for one room pass through different servers and arrive at clients in different orders. Wall-clock timestamps do not fix this, because server clocks differ by milliseconds or more (see Time, Clocks and Ordering). The robust approach is a single sequencer per ordering domain: route every message for a room through one partition, whose offset is a gap-free sequence number for that room (or keep a per-room counter in one place). Clients then display by sequence number, hold back a message whose predecessor has not arrived for a short time, and fetch any missing sequence numbers from storage on reconnect. Where a single sequencer is not possible (multi-region writes), logical clocks such as Lamport timestamps or hybrid logical clocks give a consistent order, at the cost of the order not always matching real time.
7. Retention, compaction and tiered storage#
Time and size retention. Each topic has retention.ms (7 days by default in Kafka) and optionally retention.bytes per partition. A background task deletes the oldest closed segments once they are entirely older than the limit. Because deletion is per segment, data can live a little longer than the retention time (until its segment closes and ages out), so segment size and roll time are set with retention in mind: a topic with 1-hour retention should roll segments every few minutes, not every gigabyte.
When the oldest segment is deleted, the partition's log start offset moves forward. A consumer whose committed offset is now older than the log start gets an "offset out of range" error and follows its reset policy (earliest to start from the oldest retained message, latest to skip to the newest). A consumer that was down for longer than the retention period has lost data; consumer lag alerts must fire well before that point.
Log compaction. For some topics, the interesting thing is the latest value for each key, not the history: the current address of each customer, the latest configuration of each service, the latest committed offset for each consumer group. With cleanup.policy=compact, the broker keeps at least the last message for every key and removes older ones:
- The log has a cleaned tail and a dirty head (written since the last cleaning). When the dirty fraction exceeds a threshold (
min.cleanable.dirty.ratio, 0.5 by default), a cleaner thread scans the dirty part, builds an in-memory map of key → latest offset, then rewrites the segments, keeping only records that are the latest for their key. - Offsets do not change: a compacted log has gaps, which consumers handle naturally.
- A message with a key and a null value is a tombstone: it says "delete this key". The cleaner removes older values of the key and keeps the tombstone for a while (
delete.retention.ms, 24 hours by default), so consumers that are reading have time to see the deletion, then removes the tombstone too. - The guarantee: a consumer that reads a compacted topic from the beginning ends up with the latest value of every key that has not been deleted. That makes a compacted topic a durable, replayable table, which is how stream processors restore state and how change-data-capture topics stay bounded (see Change Data Capture and the Outbox Pattern and Event Sourcing and CQRS).
Worked compaction example. Messages for key user-7: offset 10 "city=Paris", offset 55 "city=Lyon", offset 91 "city=Nice". For key user-9: offset 12 "city=Rome", offset 80 null. After cleaning: offset 91 (user-7 → Nice) and offset 80 (tombstone for user-9). After the tombstone retention passes, only offset 91 remains. A new consumer reading from the start rebuilds "user-7 lives in Nice, user-9 does not exist".
Policies can be combined (compact,delete): keep the latest value per key, but drop anything older than 30 days.
Tiered storage. Our estimate showed that storage, not throughput, sets the broker count: 450 TB of local disk for 7 days. Retention of months or years on broker disks would be prohibitively expensive, and moving a broker's data during rebalancing takes hours when it holds tens of terabytes. Tiered storage splits the log:
- Local tier: recent segments on broker disks, for example 12 to 24 hours (
local.retention.ms). - Remote tier: closed segments (with their indexes) are copied by the leader to object storage such as S3, and metadata about remote segments is tracked in an internal topic. Once copied and past local retention, the local files are deleted.
- Reads: a consumer asking for an old offset is served by the broker fetching the segment (or a range of it) from object storage; recent offsets are served locally as before.
Kafka's version is KIP-405; it shipped as early access in the 3.6 release and was declared production-ready in later 3.x releases, according to the project's release notes. Benefits:
- Cost. Object storage stores one logical copy (replicated internally by the provider) at a fraction of the price of replicated block storage. Roughly: 7 days on local disks is 450 TB of block storage; with tiering, it is about 65 TB local (1 day × 3 replicas) plus about 150 TB in object storage, which at list prices is several times cheaper.
- Elasticity. Brokers hold little data, so adding a broker or replacing a failed one moves only the local tier: minutes instead of hours.
- Isolation. Catch-up reads go to object storage rather than evicting the page cache of hot partitions.
Costs: reads of old data have higher first-byte latency (tens to hundreds of milliseconds) and incur object-storage request charges; compacted topics have historically not been supported in the remote tier; and operations now depend on the object store's availability for old data.
Object-storage-native designs. A step further is to make object storage the primary store and brokers stateless: producers' batches are written to object storage files and a metadata service assigns offsets. This removes inter-zone replication traffic and broker disks entirely, at the cost of higher latency (object-store writes take tens to hundreds of milliseconds). WarpStream (acquired by Confluent in 2024) is one example of this approach, and proposals exist to add similar "diskless" topics to Apache Kafka. It is a good fit for high-volume, latency-tolerant data such as logs and analytics events, and a poor fit for request-path messaging.
Retention and personal data. An immutable log complicates "delete this user's data" requests. Options: keep personal data out of long-retention topics (store an id, keep the data in a database); use compacted topics keyed by user and write tombstones; or crypto-shredding: encrypt each user's fields with a per-user key and delete the key to make the data unreadable. See Data Lifecycle, Tiering and Retention.
8. The control plane: controller, metadata and failure detection#
What the controller does. It owns the cluster's metadata: topics and their configurations, the replica list of every partition, the current leader and leader epoch, the ISR, broker registrations and access-control lists. It decides leader elections, applies topic changes and coordinates partition reassignments. Mistakes here cause split-brain (two leaders for one partition) or lost data, so the controller must be strongly consistent.
The ZooKeeper era. Kafka originally stored metadata in ZooKeeper and elected one broker as controller using an ephemeral ZooKeeper node (see ZooKeeper and etcd). It worked, but had two well-known problems. First, a new controller had to read the entire metadata from ZooKeeper before acting, which became slow with hundreds of thousands of partitions, so controller failover could leave the cluster unable to elect leaders for a long time. Second, operators had to run, secure and tune a second distributed system.
The Raft-based design (KRaft). KIP-500 replaced ZooKeeper with a built-in controller quorum:
- Three or five controller nodes run Raft over a metadata log (an internal topic). Every metadata change is a record appended through the Raft leader, the active controller, and committed by a majority.
- The other controllers are hot standbys that replay the log continuously, so a controller failover takes as long as a Raft election, not a full reload.
- Brokers fetch the metadata log from the controllers and apply it to an in-memory image, receiving deltas instead of full updates. Periodic snapshots bound replay time.
- Kafka marked KRaft production-ready in version 3.3 (2022) and removed ZooKeeper support entirely in 4.0 (2025).
This is a general design pattern: put the metadata of a log system in a log, replicated with consensus, and let every component follow it (see Leader Election and Coordination Services).
Failure detection and fencing. Brokers send heartbeats to the active controller. If a broker misses heartbeats for the session timeout (for example 9 seconds), the controller fences it, recording that it may no longer lead partitions, and elects new leaders from the ISR for every partition it led. Epochs prevent stale actors from doing damage: a deposed leader's writes carry an old leader epoch and are rejected by followers; a deposed controller's decisions carry an old epoch and are ignored. The general approach is described in Heartbeats, Failure Detection and Gossip.
Controlled shutdown. Most broker restarts are planned (upgrades, configuration changes). Before stopping, a broker asks the controller to move leadership of its partitions to other in-sync replicas, waits until that is done, then exits. Producers and consumers see a metadata change but no errors, so a rolling restart of all 40 brokers causes no unavailability.
How long does a failover take? A broker leading about 1,250 partitions crashes. Detection takes the session timeout (several seconds). The controller then writes the leadership changes as a batch of metadata records, committed by the Raft quorum in milliseconds, and brokers apply them within a fraction of a second. Clients discover the new leaders on their next error-triggered metadata refresh. End to end, partitions are writable again within roughly 5 to 15 seconds of the crash, almost all of it detection time. Lowering the timeout speeds failover but risks false positives during long garbage-collection pauses or network blips.
9. Scaling brokers, partitions and hot partitions#
How the cluster grows. Adding a broker adds disk, network and CPU, but a new broker starts empty: existing partitions do not move by themselves. Scaling therefore has two steps:
- Add brokers to the cluster (they register with the controller).
- Reassign partitions so some replicas move to the new brokers. A reassignment adds the new broker as an extra replica, lets it copy the partition from the leader (a full copy of the retained data), waits until it joins the ISR, then removes the old replica. Moving a partition holding 500 GB at 100 MB/s takes about 1.5 hours, which is why reassignment traffic is throttled (so it does not starve producers and consumers) and why tiered storage, which shrinks local data, makes scaling much faster.
Because this is routine at 40 brokers (disks fill unevenly, brokers fail, traffic shifts), production clusters use an automated rebalancer that watches disk, network and CPU per broker and proposes or executes moves under goals such as "no broker above 70% disk", "replicas spread across zones", "leaders balanced". LinkedIn's Cruise Control is an open-source example.
How many partitions? Too few partitions cap parallelism; too many waste resources. A practical approach:
- Throughput: partitions ≥ peak topic throughput / throughput one consumer can handle per partition. A topic at 200 MB/s whose consumers handle 10 MB/s each needs at least 20 partitions.
- Consumer parallelism: at least as many partitions as the largest consumer group will ever need, since extra consumers beyond the partition count sit idle.
- Headroom for growth: because increasing the count remaps keys (Deep Dive 6), choose for 2 to 3 years of growth, for example 2 to 4 times today's need.
- Costs of too many: each partition has open files, memory for indexes and buffers, replication fetch work, and a share of controller metadata. More partitions also mean smaller batches per partition (the producer's messages are spread thinner), which lowers compression and efficiency, and more leaders to move in a failover.
Hot partitions. Keyed partitioning assumes keys are evenly loaded. Real traffic is skewed: one celebrity, one viral video, one huge tenant. If one key produces 50 MB/s, its partition, its leader broker and its single consumer all overload, while the rest of the cluster idles. Options in increasing order of effort:
- No key for messages that do not need ordering: the default partitioner spreads them evenly.
- Salting the key: append a random suffix from 0 to N−1 to hot keys (
video-42#3), spreading one key across N partitions. Ordering for that key is lost, and consumers that aggregate must combine the N partial results (for example, partial counts per salt, then a merge step keyed by the original id). - Compound keys: key by (video id, region) or (tenant, user) instead of video or tenant alone, if ordering is only needed at the finer level.
- Detect and split dynamically: producers or a routing layer keep a list of known hot keys (from metrics) and salt only those, leaving normal keys ordered.
- Backpressure: if the hot key is a misbehaving client, throttle it with quotas rather than redesign partitioning.
Scaling consumers. Consumers scale horizontally up to the partition count. A queue in front of a service gives a natural autoscaling signal: scale workers on lag (or on the age of the oldest message) rather than CPU. A matching service for ride requests, for example, can partition requests by geographic region, add matcher instances when a region's lag grows, and commit offsets only after a match succeeds. A code-execution service can put submissions on a queue so a burst during a contest is absorbed rather than overloading the execution containers; the trade-off is that the API becomes asynchronous, so clients poll a status endpoint (once a second is fine) or receive a push.
When not to add a queue. For a system whose peak load fits easily on its workers, a queue can be over-engineering. The deciding arguments are often not throughput but retries and buffering: a queue lets a crashed worker's job be retried by another worker and guarantees no submissions are lost in a burst. Say which benefit you need.
10. Queue semantics on top of a log: work queues, retries, delays and priorities#
Many users of a message queue want job-queue behaviour: hand out tasks, retry failures, give up on poison messages, delay some messages, run urgent ones first. A log does not provide these natively, so we either build them on top or offer a queue mode. (For the general pattern, see Pattern: Managing Long-Running Tasks.)
Message queue versus task queue. A message queue receives, stores and delivers messages; what the consumer does with them is up to the consumer. A task queue (Celery is a well-known Python example) also runs the tasks: it schedules work, tracks results and often supports periodic jobs, usually on top of a broker such as RabbitMQ or Redis. Our system is the former; task frameworks can sit on top.
How classic queues differ.
| Feature | Log (Kafka-style) | Classic queue (RabbitMQ, Amazon SQS) |
|---|---|---|
| Unit of acknowledgement | Offset per partition | Each message |
| After acknowledgement | Kept until retention | Deleted |
| Multiple independent readers | Yes, any number of groups | Needs a copy per subscriber queue (fan-out exchange or SNS-to-SQS) |
| Replay | Yes, rewind the offset | No |
| Per-message retry and redelivery | Build it yourself | Built in (visibility timeout or negative ack) |
| Dead-letter queue | Build it yourself | Built in after N failed deliveries |
| Delayed delivery | Build it yourself | Built in (for example SQS delay, per message up to 15 minutes) |
| Ordering | Per partition | Per queue in principle; SQS standard queues are best-effort order with possible duplicates; FIFO queues order per message group |
| Parallelism | Up to partition count per group | Any number of competing consumers |
The primer-level summary of the classic options still holds: Redis is a simple broker but can lose messages; RabbitMQ is popular and flexible but uses the AMQP protocol and must be operated; SQS is fully managed but has higher latency than a self-hosted broker and its standard queues can deliver a message more than once.
Building retries on a log.
- Retry topics: on failure, the consumer publishes the message to
orders.retry.1mand commits the original offset, so the main partition keeps moving. A consumer of the retry topic waits until each message's due time (by checking a timestamp header and pausing), then reprocesses. Failures escalate throughretry.10m,retry.1h. - Dead-letter topic: after N attempts, the message goes to
orders.dlqwith headers recording the error, the original topic, partition and offset. Operators inspect, fix and replay it. The DLQ must have its own alert: a DLQ nobody watches is data loss with extra steps. - Poison messages: a message that crashes the consumer every time (a parse error) would stop the partition forever without a DLQ. Distinguish permanent errors (send straight to the DLQ) from transient ones (retry).
- Ordering caveat: retry topics reorder messages per key (Deep Dive 6).
Delayed messages and timers. "Deliver this in 10 seconds" (for example, move a ride request to the next driver if the first does not respond) is not natural in a log, which delivers in order. Options: a small set of delay topics with fixed delays (consumers pause until the head message is due, which works because all messages in a fixed-delay topic become due in order); a separate timer service (a durable scheduler or a database table polled by time); or a queue that supports per-message delay. Cancelling a timer (the driver did accept) is done by making the delayed handler check the current state before acting.
Priorities. A log has no priority: a long backlog delays urgent messages behind routine ones (head-of-line blocking). Use separate topics per priority with dedicated or weighted consumers (process urgent first, fall back to normal), and separate topics for mixed workloads: if some jobs take 50 ms and others 30 minutes, put them on different topics with different worker pools, so short jobs are never stuck behind long ones.
Long-running jobs. A consumer that takes 10 minutes per message must keep its group membership alive (the poll interval limit, max.poll.interval.ms, defaults to 5 minutes in Kafka) or it will be kicked out mid-job and its partition reassigned, causing duplicate work. Options: raise the limit, process asynchronously and pause the partition while working, or, better, treat the message as a trigger and run the job in a workflow engine (see Temporal and Workflow Engines) that handles heartbeats, retries and job dependencies.
Preventing duplicate work. With at-least-once delivery, the same job can run twice (after a rebalance, or a crash before commit). Make jobs idempotent: a job id, a status row claimed with a conditional update ("set status to running where status is pending"), and outputs written with deterministic keys.
A queue mode inside the log system. Kafka has been adding share groups (KIP-932, "Queues for Kafka"), in which members of a group consume the same partitions cooperatively with per-message acknowledgement and redelivery, available in early access in the 4.x releases according to the project's release notes. This would remove the "consumers ≤ partitions" limit and make retries native. Whether built in or built on top, the important design point is the same: queue semantics need per-message state, and that state is what the log design avoided for scalability, so it should be confined to the topics that need it.
11. Multi-tenancy, quotas, backpressure and the many-topics problem#
A shared cluster serves hundreds of teams. One team's bug (a producer retry loop, a consumer replaying a year of data) must not hurt everyone else.
Authentication and authorisation. Every connection authenticates (mutual TLS certificates or SASL with tokens), giving a principal such as service:billing. Access-control lists grant principals operations on resources: billing may read orders and write invoices. Topic naming conventions (team.domain.event) make ownership and ACLs manageable. See Multi-Tenant SaaS Architecture for isolation models in general.
Quotas. Brokers enforce per-principal (or per-client-id) limits:
- Produce and fetch byte rates, for example 50 MB/s per service per broker.
- Request rate, as a percentage of broker request-handler time, which catches clients that send floods of tiny requests.
- Controller mutations, so a script creating thousands of topics cannot overload the controller.
Kafka enforces quotas by delaying responses rather than rejecting them: the broker computes how long the client must wait to fall back under its quota and holds the response (and tells the client the throttle time). Clients slow down naturally, without error-handling paths, and well-behaved clients are unaffected. This is a form of token-bucket rate limiting applied at the broker (see Rate Limiting and Throttling).
Backpressure, end to end. A queue absorbs bursts, but an unbounded queue only postpones the problem: if producers outpace consumers for long enough, lag grows until data ages out of retention. Backpressure is how each stage tells the previous one to slow down:
- Consumers to the log: pull-based consumption is inherently backpressured: a slow consumer fetches less, and lag grows instead of the broker pushing data at it.
- Log to producers: broker quotas delay responses; producer buffers fill;
send()blocks; the producing application must slow down or shed load. - Producers to their callers: a service whose queue is full returns "server busy" (HTTP 503 or 429) with a retry-after hint, and callers retry with exponential backoff and jitter.
Bounding the queue is what keeps latency predictable. A queue that grows larger than memory turns every read into a disk read and slows down further, a death spiral; a bounded queue keeps serving the work it has quickly and pushes the excess back to the edge.
The many-topics problem. Some applications want a topic or a partition per entity: one per chat room, one per live video, one per user. With millions of entities, that is millions of partitions, far beyond what a log cluster's metadata and file handles support, and most of them would be idle. Options:
- Hash entities onto a bounded set of partitions:
partition = hash(videoId) mod N. Each partition carries many entities; consumers filter. - Co-locate consumers with entities: route all viewers of a video to the same realtime server (a layer-7 load balancer using consistent hashing on the video id, or a mapping in a coordination service), so each server subscribes to few partitions and receives mostly relevant messages.
- Use a different tool for fine-grained, dynamic subscriptions. A log is excellent for durable, high-volume streams with stable consumers; it is awkward when subscriptions change every second as users switch videos. Redis pub/sub or a dedicated fan-out layer handles dynamic subscriptions with low latency, and its fire-and-forget nature is acceptable when the messages are also persisted elsewhere for catch-up (see Pattern: Pushing Realtime Updates).
Noisy neighbours on disk and page cache. Quotas limit bytes, but a consumer replaying cold data still pulls old segments into the page cache. Isolating such consumers (dedicated quotas, follower fetching, tiered storage) or giving very large tenants their own cluster are the remaining options. Many companies run several clusters per region by workload class (critical transactional events, high-volume logs and metrics, analytics) rather than one giant cluster.
12. Multi-region deployment and disaster recovery#
One cluster per region is the default. Stretching one cluster across regions would put a cross-region round trip (tens of milliseconds or more) into every acks=all write and every ISR decision. Instead, each region runs its own cluster with replicas spread across that region's availability zones, which handles zone failures synchronously. Regions are connected asynchronously.
Mirroring. A mirroring process (Kafka's MirrorMaker 2, built on Kafka Connect, or vendor tools such as Confluent's Cluster Linking) consumes topics in one cluster and produces them to another:
- Active-passive (disaster recovery): region A serves everything and mirrors to region B. If A is lost, producers and consumers move to B. Data written in the last seconds before the failure (the mirroring lag) may be lost: the recovery point objective equals the replication lag.
- Active-active: each region produces locally to its own topics and mirrors the other region's topics in (often prefixed with the source cluster name, such as
us-east.orders). Consumers that need a global view read both. Writes never cross regions synchronously, but there is no global order, and applications must tolerate the same entity being updated in two regions. - Aggregation: regional clusters mirror into a central cluster for analytics.
Offsets do not line up across clusters. Offset 5,000 in partition 7 in region A is not offset 5,000 in region B: mirroring may batch differently, retries may duplicate, and retention may differ. When consumers fail over, they need translated offsets. MirrorMaker 2 periodically emits offset-sync records mapping source offsets to target offsets and can translate committed group offsets, so a consumer group resumes near the right point in the other region. Some reprocessing is inevitable, so failover again relies on idempotent consumers.
Stretched clusters for zero data loss. If the requirement is truly "no acknowledged message lost even if a whole region disappears", the only way is synchronous replication across regions: a cluster stretched over three regions (or two regions plus a tie-breaker for the controller quorum), with acks=all and min.insync.replicas spanning regions. Every write then pays the inter-region round trip. Financial systems sometimes accept this cost for a small set of critical topics; most systems choose asynchronous mirroring with a few seconds of RPO.
Backups. Because the log is itself replicated, traditional backups matter mainly for logical mistakes: a bad producer that wrote garbage, an accidental topic deletion. Tiered storage in object storage with versioning, or periodic copies of critical topics to object storage, provides a point-in-time copy. For the general framework (RPO, RTO, drills), see Disaster Recovery and Backups and Multi-Region and Global Data.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Hot partition from a skewed key | One broker and one consumer overloaded, lag for every key on that partition | Choose finer keys, salt known hot keys, compound keys, quotas on misbehaving producers |
| Broker crash | Partitions it led are briefly unwritable; its replicas must be rebuilt | Leader election from the ISR in seconds, idempotent producer retries, rack-aware replicas, automated replacement |
| Whole availability zone lost | One third of replicas gone | Replicas in three zones, min.insync.replicas=2, capacity headroom in the remaining zones |
| ISR shrinks to one replica | Writes either fail or become non-durable | min.insync.replicas=2 rejects writes, alert on under-replicated partitions, unclean leader election disabled |
| Slow follower | acks=all latency rises until it is dropped from the ISR | Lag limit removes it from the ISR, monitor follower fetch latency, replace bad disks |
| Consumer falls behind beyond retention | Data deleted before it is processed | Alert on lag in time, long enough retention, autoscale consumers up to partition count, more partitions for future growth |
| Catch-up consumer evicts the page cache | Tail readers start hitting disk, latency rises for everyone | Fetch quotas, follower fetching, tiered storage for old data, more RAM |
| Rebalance storms in large consumer groups | Processing pauses repeatedly | Cooperative rebalancing, static membership, longer session timeouts, sensible poll intervals |
| Poison message | Partition stuck, or consumer crash loop | Classify permanent errors, dead-letter topic with alerting, retry topics for transient errors |
| Controller unavailable | No leader elections or topic changes; data path keeps working until a broker fails | Three or five controller nodes across zones with Raft, fast failover, monitoring of metadata lag |
| Partition reassignment saturates the network | Producers and consumers slowed during scaling | Throttled reassignment, tiered storage to shrink moves, automated rebalancer with goals |
| Region outage | Region's cluster unavailable, unmirrored data lost | Asynchronous mirroring with offset translation, documented RPO, idempotent consumers, stretched cluster for critical topics |
What Interviewers Expect#
Mid-level. Explain the core model clearly: topics split into partitions, each an append-only log with offsets; producers choose a partition by key; consumers in a group share partitions and commit offsets; messages are retained, not deleted on read. Add replication with a leader and followers for durability, and explain the basic acks options. Size the cluster roughly from throughput and retention, and know that keys give per-key ordering but there is no order across partitions.
Senior. Go into the mechanisms. Explain the ISR, the high watermark and why consumers read only committed data, acks=all with min.insync.replicas, and the durability versus availability choice when replicas fail. Describe the on-disk design: segments, sparse indexes, the page cache and zero-copy, and why per-write fsync is not needed when data is replicated. Discuss delivery semantics precisely: idempotent producers with sequence numbers, commit-after-processing for at-least-once, idempotent consumers, and when transactions are worth their cost. Handle hot partitions, partition-count changes, consumer rebalancing and lag-based scaling.
Staff and above. Reason about the system as a platform. Compare ISR replication with Raft per partition, ZooKeeper-based with Raft-based metadata, and local storage with tiered or object-storage-native designs, with their latency, cost and operational trade-offs. Design multi-tenancy (quotas by delayed responses, ACLs, cluster-per-workload-class), multi-region mirroring with offset translation and an explicit RPO, and queue semantics (retries, DLQs, delays, priorities) on top of a log without breaking its scalability. Use leader epochs to explain how logs reconcile after failover. Bring numbers: replication and cross-zone traffic costs, reassignment times, failover time dominated by detection, and Little's law for lag.
Deep Dive: how real systems compareShow
- Apache Kafka. The design this case study follows: partitioned logs, ISR replication, consumer-managed offsets, page-cache-centred storage, KRaft metadata, idempotent producers and transactions, tiered storage. Created at LinkedIn and open-sourced in 2011; LinkedIn has publicly described running it at trillions of messages per day. Strengths: throughput, replay, a large ecosystem (Connect, Streams, schema registries). Weaknesses: queue semantics and per-message features are add-ons, and operations at scale take expertise.
- Apache Pulsar. Originated at Yahoo. Separates stateless brokers from storage in Apache BookKeeper, where each topic's log is a sequence of ledgers striped across storage nodes (bookies). Because brokers hold no data, moving a topic between brokers is fast, and storage scales separately. It supports both streaming and queue-style subscriptions (exclusive, shared, failover, key-shared) natively, and tiered storage. The trade-off is more components to operate.
- RabbitMQ. A classic broker implementing AMQP: exchanges route messages to queues by rules (direct, topic, fan-out), consumers acknowledge each message, and messages are deleted after acknowledgement. Excellent for task distribution, routing flexibility and per-message features at moderate throughput. Quorum queues (replicated with Raft) provide durability, and newer stream queues add log-like replay.
- Amazon SQS. A fully managed queue with practically no operations: standard queues offer very high throughput with at-least-once delivery and best-effort ordering; FIFO queues give ordering per message group and deduplication. Visibility timeouts, dead-letter queues and delays are built in. No replay, and no multiple independent readers without fan-out through SNS.
- Redpanda. A Kafka-protocol-compatible broker written in C++ with a thread-per-core design and Raft per partition, aiming at lower tail latency and simpler operations (no JVM, no separate metadata system).
- Object-storage-native systems such as WarpStream trade latency for much lower cost and stateless brokers, as discussed in Deep Dive 7.
- Redis Streams provide a lightweight log with consumer groups inside Redis, fine for modest volumes where Redis is already present (see Redis in Practice).
Choosing in an interview. A durable event backbone with replay and many readers: Kafka (or Pulsar or Redpanda). Task distribution with per-message retries and little operational effort: SQS or RabbitMQ. Low-latency, ephemeral fan-out with dynamic subscriptions: Redis pub/sub or a purpose-built realtime layer. For deeper Kafka operations, see Apache Kafka in Practice.
Deep Dive: sizing worked end to endShow
Requirements: 1 GB/s average and 3 GB/s peak of 1 KB messages, 4 times compression, replication factor 3, 3 consumer groups on average, 7 days retention.
- Stored bytes: 250 MB/s compressed × 86,400 s × 7 days ≈ 151 TB logical, × 3 replicas ≈ 454 TB.
- Brokers by storage: 24 TB usable per broker at 50% target fill gives 12 TB each, so about 38, rounded to 40 brokers.
- Brokers by network at peak: producers 750 MB/s in, replication 1.5 GB/s between brokers, consumers 2.25 GB/s out: about 4.5 GB/s. With 40 brokers, about 110 MB/s each. Even at a 30% target utilisation of a 25 Gbit/s NIC (about 0.9 GB/s), 5 or 6 brokers would suffice for network. Storage dominates.
- With tiered storage keeping 1 day locally: about 65 TB local, so at 12 TB per broker roughly 6 brokers for storage; partition count and failure headroom then set the size, perhaps 12 to 15 brokers, plus about 151 TB in object storage.
- Page cache: to serve tail readers from memory, each broker should cache at least a few minutes of its write rate. At 750 MB/s peak compressed across 40 brokers (about 19 MB/s each, ×3 for replicas, about 56 MB/s of writes per broker), 10 minutes is about 34 GB. Brokers with 64 to 128 GB of RAM and a small JVM heap (a few GB) leave most memory for the page cache.
- Partitions: 50,000 partitions × 3 = 150,000 replicas; with 40 brokers, 3,750 replicas each; with 15 tiered brokers, 10,000 each, which pushes per-broker limits, so the tiered design might use fewer, larger partitions or more brokers.
- Cross-zone traffic: replication sends 2 of 3 copies across zones (500 MB/s average). At an illustrative $0.01 per GB in each direction, that is about 1.3 PB per month, potentially tens of thousands of dollars per month. Follower fetching removes most cross-zone consumer traffic, and object-storage-native designs remove replication traffic altogether, which is the main reason they exist.
The lesson: in a log system, retention and replication, not message rate, usually determine the cost.
Deep Dive: what happens during a slow consumer incidentShow
At 14:00, a downstream database slows, and the billing consumer group drops from 20,000 to 5,000 messages per second on a topic receiving 20,000 per second.
- 14:00 to 14:30: lag grows by 15,000 messages per second: 27 million messages after 30 minutes. By Little's law, new messages now wait about 27 million / 5,000 ≈ 90 minutes to be processed at the current rate. Producers are unaffected: the queue is doing its job of decoupling.
- 14:05: the lag-in-time alert fires (threshold: oldest unprocessed message older than 5 minutes). On-call checks the consumer dashboards and finds database latency.
- 14:20: the database is fixed. Consumers return to their full speed of 30,000 messages per second (they were provisioned with 50% headroom). Catch-up rate: 30,000 − 20,000 = 10,000 per second, so 27 million messages of lag take 45 minutes to clear.
- During catch-up, the consumers read data from 30 to 75 minutes ago, still in the page cache on brokers with enough RAM, so other tenants are unaffected. Had catch-up required reading data several hours old, the fetch quota and follower fetching would protect the hot path.
Takeaways: provision consumers with headroom for catch-up (not just for steady state), alert on lag in time rather than in messages, and make sure retention is far longer than any plausible outage of a consumer.
Deep Dive: testing a message queue for correctnessShow
- Linearisability and loss tests under faults. Kyle Kingsbury's Jepsen analyses have tested Kafka and many other systems by injecting network partitions, process pauses and clock changes while checking that acknowledged writes are never lost. His 2013 analysis of Kafka found that acknowledged writes could be lost when the ISR shrank to a single replica and that replica then failed, the scenario
min.insync.replicasexists to prevent. Testing exactly these sequences is how a design earns trust. - Property tests on the log: for any sequence of produce, crash, failover and restart, every acknowledged batch is present exactly once at the same offset on every in-sync replica, and offsets are gap-free except for compaction and aborted transactions.
- Idempotence and transactions: kill producers mid-transaction, restart with the same transactional id, and verify that read-committed consumers see each committed result exactly once.
- Consumer-group behaviour: random member crashes and pauses; verify no partition is processed by two members of one generation and all offsets eventually advance.
- Performance and soak tests: sustained peak plus catch-up reads, rolling restarts under load, partition reassignment under load; watch p99 latency and under-replicated partitions.
- Game days: fail a zone, fail the controller leader, fail over a region with mirrored topics and measure actual RPO and RTO against the documented ones.
Deep Dive: a 45-minute interview planShow
| Minutes | What to do |
|---|---|
| 0 to 5 | Clarify: log or work queue, throughput, message size, retention, ordering scope, delivery guarantee, durability target |
| 5 to 10 | Estimates: GB/s in and out, storage for retention at RF 3, broker count, partitions |
| 10 to 18 | High-level design: topics, partitions, offsets, producers routing to leaders, consumer groups, committed offsets, controller |
| 18 to 25 | Replication: leader and followers, ISR, high watermark, acks, minimum ISR, leader election and fencing |
| 25 to 31 | Storage: segments, sparse indexes, page cache, zero-copy, retention and compaction, tiered storage |
| 31 to 38 | Delivery and ordering: idempotent producer, commit strategies, transactions, per-key ordering, hot partitions |
| 38 to 43 | Operations: scaling and reassignment, quotas, retries and DLQs, multi-region mirroring |
| 43 to 45 | Summary and trade-offs: what we chose, and alternatives such as Pulsar or object-storage-native designs |
The most common mistake is designing a queue that deletes messages on read and tracks per-message state, then discovering it cannot serve many readers or replay. State the log model in the first five minutes.
Deep Dive: follow-up questions and short answersShow
- "What if Kafka goes down?" A whole cluster outage is rare because of replication across zones; the realistic failures are a broker, a zone or a consumer. Still, producers should buffer briefly and fail visibly, critical producers can write to a local outbox table and publish later (see Distributed Transactions: 2PC, Sagas and Outbox), and a mirrored cluster in another region provides disaster recovery.
- "How do you guarantee a message is processed exactly once by a service that sends emails?" You cannot make the email provider transactional with the log. Use at-least-once delivery, a deduplication key per email (stored before sending, checked on retry), and the provider's idempotency features if it has them.
- "How would you support 10 million topics?" You would not map them to partitions. Hash them onto a bounded set of partitions and filter in consumers, or use a system designed for many lightweight topics (some brokers, such as Pulsar, support far more topics per cluster), or a pub/sub layer for ephemeral subscriptions.
- "How do consumers read from a point in time?"
ListOffsetswith a timestamp uses each segment's time index to find the first offset at or after that time; the consumer seeks there. - "Why is the consumer pull-based?" So each consumer controls its rate, batching is natural, and slow consumers never make the broker buffer for them. Long polling removes the latency cost of pulling.
- "Can a consumer read data that was later lost?" Not in this design: consumers read only below the high watermark, which is on every in-sync replica, so a failover to any ISR member keeps everything a consumer could have seen.
Key Takeaways#
- Model the queue as a partitioned, replicated, append-only log. Offsets instead of per-message state make many readers and replay nearly free; partitions give parallelism; retention deletes whole segments.
- Durability comes from replication plus clear acknowledgement rules. Leader per partition, ISR, high watermark,
acks=allwithmin.insync.replicas=2, leader epochs for safe truncation, and fencing of stale leaders. Unclean election is a deliberate durability-versus-availability choice. - Throughput comes from batching and sequential I/O. Producer batching and compression, page-cache reads, zero-copy sends, and binary protocols with clients routing directly to leaders.
- Order is per partition, so choose keys carefully. The key is the unit of ordering; skewed keys make hot partitions; changing the partition count remaps keys; consumers must parallelise by key and handle retries without silently reordering.
- Exactly-once is at-least-once plus deduplication or atomic commits. Idempotent producers, commit-after-processing, transactions for read-process-write pipelines, and idempotent sinks for external effects.
- Operate it as a platform. Quotas by delayed responses, lag-in-time alerts, automated rebalancing, tiered storage for cost and elasticity, queue features (retries, DLQs, delays) built only where needed, and asynchronous mirroring across regions with a stated RPO.