What it is
A distributed message broker in the Kafka style stores streams of records as partitioned, replicated, append-only logs. Producers append records to a topic. The topic is split into partitions spread over a cluster of brokers, and each partition is copied to several brokers. Consumers read a partition sequentially from an offset they choose and remember. Records are not deleted when they are read; they expire by retention time, size or compaction.
This case study designs one end to end: requirements, estimates, the log, partitioning, replication, acknowledgements, and broker failure.
Why it exists
Services need to hand events to many other services without calling each of them: orders to billing, analytics, search and fraud. A database table polled by everyone does not scale, and a classic queue deletes a message once one consumer has it. A log broker gives each consumer group its own position in a shared, durable history. Groups can be added later, fall behind and catch up, or replay last week's data after a bug fix.
How it works
Requirements and estimates (illustrative). Peak ingress is 200 MB/s of 1 KB records, so about 200,000 records/s. Retention is 7 days: 200 MB/s × 604,800 s ≈ 121 TB per copy, ≈ 363 TB at replication factor 3, before compression and headroom. Three consumer groups reading everything means ≈ 600 MB/s of egress. If one consumer instance processes about 10 MB/s, a group needs at least 20 partitions to keep up, so you would pick more (say 48) for growth. All of these numbers are assumptions you state and adjust; the method is what matters.
The log. Each partition is a sequence of segment files. A write appends to the active segment and gets the next offset. Reads are sequential, usually served from the operating system's page cache, which is why one broker can serve many consumers cheaply. Consumer groups commit their offsets to an internal compacted topic, so a restarted consumer resumes where its group left off.
Partitioning. The producer picks a partition per record: by hashing the key (same key, same partition, so per-key order), or spread for records without a key. Each partition is read by at most one consumer per group, so the partition count caps a group's parallelism. See Kafka Partitions for hot keys and why changing the count remaps keys.
Replication. Every partition has one leader and, with replication factor 3, two followers on other brokers. Producers write to the leader; consumers read from the leader by default (rack-aware follower fetching exists). Followers pull from the leader with fetch requests, like consumers. Followers that keep up form the in-sync replica set (ISR); one that falls behind for longer than replica.lag.time.max.ms (30 s by default) is removed from it. Leadership is spread so that each broker leads some partitions and follows others.
Acknowledgements. acks=0 does not wait at all. acks=1 waits for the leader's own write. acks=all waits until every ISR member has the record, which the leader learns from the followers' next fetch offsets; then the high watermark advances. Consumers only see records below the high watermark. With min.insync.replicas=2, a write with acks=all is refused (NOT_ENOUGH_REPLICAS) when fewer than two replicas are in sync, rather than acknowledged on a single disk. Since Kafka 3.0, producers default to acks=all with idempotence enabled, so retries do not create duplicates within a partition.
Failure detection and failover. In current Kafka (KRaft mode, the only mode since Kafka 4.0) a small Raft quorum of controllers holds the cluster metadata. Brokers send it heartbeats; a broker that misses them for broker.session.timeout.ms (9 s by default) is fenced. For every partition that broker led, the controller picks a new leader from the ISR and increments the leader epoch. Producers get NOT_LEADER_OR_FOLLOWER or time out, refresh their metadata and retry to the new leader. Consumers do the same and resume from their committed offsets.
Rejoining. A restarted broker's replicas are followers. Using the leader epochs, each replica truncates its log to where it diverged from the current leader, then fetches until it is caught up and is added back to the ISR. A preferred leader election later restores the original, balanced leader placement.
When to use it
- Event streams with several independent consumers, or consumers added over time.
- When replay matters: rebuilding a read model, backfilling a new service, reprocessing after a bug.
- High-throughput pipelines (logs, metrics, clickstreams, change data capture) where sequential I/O and batching pay off.
- When per-key ordering is required and per-partition ordering is enough.
When not to
- Task queues where each message is one unit of work to be done once and forgotten, with per-message acknowledgements, delays or priorities. A classic queue (RabbitMQ, SQS) fits better. Kafka 4.x is adding queue-like share groups, but they are newer.
- Low volume with no replay needs: a managed queue or a database outbox table is less to operate.
- Request/response interactions that need an immediate answer.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Replication factor 3 instead of 2 | Survives one broker failure while still enforcing min.insync.replicas=2 |
50% more disk and replication traffic |
acks=all instead of acks=1 |
Acknowledged records survive a leader crash | About one extra replication round trip per write; writes refused when the ISR is too small |
| More partitions | More consumer parallelism, spreads load over brokers | More files, memory and metadata; longer failover with many leaders per broker; repartitioning remaps keys |
| Longer retention | Longer replay window | Disk, unless old segments move to tiered (object) storage |
| Shorter session timeout | Faster failover | More false failovers from GC pauses or network blips |
Alternatives
- Classic message queues (RabbitMQ, ActiveMQ, Amazon SQS): per-message acknowledgement, routing, delays and dead-lettering; messages are gone once consumed.
- Apache Pulsar: stateless serving brokers with storage in a separate layer (BookKeeper), so storage and serving scale independently.
- Managed streams (Amazon Kinesis, Azure Event Hubs, Google Pub/Sub): the same ideas with someone else running the cluster, with their own quotas and limits.
- Database outbox plus change data capture: when events come from one database and volume is modest.
Failure modes
- Leaderless partition: between a leader's death and the election, that partition accepts no writes. Producers bridge it only if
delivery.timeout.msis longer than detection plus election. - Lost acknowledged records: with
acks=1, a leader crash loses records the followers never fetched. Unclean leader election (an out-of-sync replica becoming leader, off by default) loses even more. - ISR shrinking to one: with
min.insync.replicas=1the cluster keeps accepting writes held on one disk. The next failure loses them. - Under-replication after a failure: until the broker returns or its partitions are reassigned, every affected partition has one copy fewer. A second failure in that window is the dangerous one.
- Consumer lag: consumers slower than producers fall behind. Once lag exceeds retention, unread records are deleted.
- Hot partitions and brokers: a skewed key or uneven leader placement concentrates load on one broker.
In production
Spread replicas across racks or availability zones (rack-aware placement). Use acks=all, min.insync.replicas=2 and replication factor 3 for data you cannot lose. Alert on under-replicated partitions, offline partitions, ISR shrink rate and consumer lag. Watch per-broker disk and network headroom so that a failure does not overload the survivors that take over its leaders. Plan partition counts ahead, since adding partitions remaps keys. Consider tiered storage for long retention, and quotas so that one client cannot saturate the cluster.
Common misconceptions
- "A consumer reading a record removes it." Consumers only move their own offset; other groups and replays still see the record.
- "acks=1 is durable because the record is on disk." It is on one broker's disk (often only in the page cache). If that broker dies before followers fetch it, the record is gone.
- "A broker failure takes the topic down." Only the partitions it led are unavailable, and only until new leaders are elected.
- "More partitions is always better." Past what consumers need, partitions add overhead and lengthen recovery.
- "Kafka gives exactly-once by default." Idempotent producers prevent duplicates from retries within a partition; end-to-end exactly-once needs transactions and consumers that read only committed records, or idempotent processing.
Interview angle
Start from requirements and numbers: ingress, record size, retention, replication factor and consumer groups give you throughput, disk and partition count. Draw producers, brokers with partition leaders and followers, a controller quorum and consumer groups. Then expect probes on where order is guaranteed, what acks and min.insync.replicas you choose and why, what happens when a broker dies (detection, election from the ISR, client metadata refresh, retries), what can be lost, and how a returning broker catches up. Mentioning the high watermark and leader epochs shows depth.
Model assumptions
The simulation is a simplified model, not a benchmark. One simulated record stands for one produce batch, and rates are scaled down (60–150 batches/s). Arrivals are random (Poisson) with uniformly distributed keys. The partitioner is a consistent-hash balancer without health checks, so a key keeps going to its partition even when that partition has no leader, as in Kafka for keyed records. Each partition replica is a queue placed in its broker's region, and only leaders receive produce traffic. Each partition's consumer has 2 slots × 20 ms (≈ 100 batches/s). Network hops take 3–8 ms. Producer retries use 100 ms backoff doubling to 1 s for 6 attempts (≈ 2.5 s), a compressed stand-in for delivery.timeout.ms (2 minutes by default). The model's queues drop a batch once its consumer has processed it; a real log keeps it until retention removes it. Follower fetches, acknowledgements (acks=1 and acks=all), controller heartbeats, the election, metadata refresh, truncation and catch-up are scripted illustrations, not simulated. Leader failover is a topology change at the start of the failover step. In the challenge, P2's records go through a one-backend metadata router so that a partition that is down from the start fails its records instead of being skipped. Numbers show behaviour and orders of magnitude only.