Course contents

17. Real-World System Design Lesson 16 of 20

Distributed Message Broker

Design a Kafka-like broker: partitioned logs, leaders and followers, ISR and acks, consumer offsets, and what happens when a broker dies.

25 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Size a broker from bytes: ingress × retention × replication factor is the disk you need.
  • A partition is an append-only log; consumer groups only store offsets, so many groups can read and replay it.
  • Each partition has one leader and followers that pull from it; caught-up followers form the ISR.
  • acks=all with min.insync.replicas=2 means an acknowledged record is on at least two brokers; acks=1 can lose acknowledged records.
  • A dead leader makes only its partitions unavailable until the controller elects a new leader from the ISR.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.ms is 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=1 the 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. What the broker must do

    We are designing a Kafka-like broker for an order platform. Functional: producers append records to named topics; several independent consumer groups read them, in order per key, and can re-read old data. Non-functional: a peak of about 200 MB/s in, records kept for 7 days, no acknowledged record lost when a broker dies, failover in seconds.

    The estimates (illustrative): at 1 KB per record that is about 200,000 records/s. Seven days is 200 MB/s × 604,800 s ≈ 121 TB per copy, about 363 TB with three copies. Three consumer groups reading everything means about 600 MB/s going out.

    The model starts small: one log on Broker 1, written by the producers at 60 batches per second and read by one consumer. Each simulated record stands for a batch. The consumer keeps up easily and nothing fails.

    Scene: Producers send 60 batches per second to a single log, P0, on Broker 1. One consumer reads it and keeps up; brokers 2 and 3 are empty. Annotations show the estimates: about 200,000 records per second and about 363 TB of storage.

    Key idea: Size a broker from bytes, not messages: ingress × retention × replication factor is the disk you need.

  2. 2. An append-only log, read by offset

    A partition is an append-only log. Each new record gets the next offset. Consumers do not delete what they read. Each group simply remembers how far it got: it commits an offset, which Kafka stores in an internal compacted topic.

    Follow the packets. A record is appended at offset 1042. Billing fetches from 1042 and commits 1043. Analytics, a second group added after Billing, fetches from offset 980, far behind, to replay older data from the same log. Neither group affects the other, and the record stays until retention removes it.

    This is the big difference from a classic queue, and it is why reads are cheap: sequential disk reads, often served from the OS page cache. The packets are a scripted illustration, and traffic is turned down to 8 batches/s. The model’s own queue drops a batch once Billing has processed it; a real log keeps it.

    Scene: A record is appended to P0. Billing fetches it and commits offset 1043; then Analytics fetches from offset 980 to replay older records from the same log and commits its own offset.

    Key idea: Consumers own their position (offset), not the data: many groups can read and replay one log independently.

  3. 3. Partitions spread the log over brokers

    200 MB/s is far more than one disk and one network card should take, and one log can only be read by one consumer per group. So the topic is split into partitions, and each partition’s leader lives on a different broker: P0 on Broker 1, P1 on Broker 2, P2 on Broker 3.

    The producer’s partitioner hashes each record’s key to a partition, so one customer’s records stay in order. Traffic rises to 150 batches/s and each leader gets roughly a third; each partition has its own Billing consumer, and all of them keep up.

    Three partitions keep the picture readable. For 200 MB/s a real topic would have dozens: if one consumer handles about 10 MB/s, you need at least 20, plus headroom (illustrative). The Kafka Partitions lesson covers keys, hot partitions and repartitioning.

    Scene: The topic has three partitions whose leaders are on brokers 1, 2 and 3. The partitioner spreads 150 batches per second roughly evenly over them, and each partition’s Billing consumer keeps up.

    Key idea: Partitions are the unit of both scale and placement: each one is an independent log with its own leader broker.

  4. 4. Every partition has followers

    A broker can die, so every partition is replicated, here three times (replication factor 3). Each partition has one leader, which takes all writes (and, by default, all reads), and two followers on other brokers. Every broker leads one partition and follows two, which spreads the load.

    Followers pull: they send fetch requests to the leader, just like consumers, and append what they get to their own copy of the log. The packets show P0’s and P1’s followers fetching.

    The followers that are caught up form the in-sync replica set (ISR). A follower that stops fetching or falls behind for longer than replica.lag.time.max.ms (30 s by default) is dropped from the ISR. Only an ISR member may become leader. The fetches are a scripted illustration: in the model, followers receive no simulated traffic.

    Scene: Each partition now has a leader and two followers on the other brokers. Followers of P0 and P1 send fetch requests to their leaders and receive replication records. All replicas are in sync.

    Key idea: One leader per partition takes the writes; followers pull from it, and the caught-up ones (the ISR) are the only safe successors.

  5. 5. When is a write acknowledged?

    The producer chooses how much durability to wait for with acks:

    Record A, acks=1: the leader writes it to its log and acknowledges straight away. The ack is on its way back before either follower has fetched the record.

    Record B, acks=all: the leader acknowledges only once every replica in the ISR has the record. It knows when the followers’ next fetch requests ask for the following offset; then the high watermark advances and the ack goes out. That costs about one more replication round trip. Consumers only ever see records below the high watermark.

    Pair acks=all with the topic setting min.insync.replicas=2: if the ISR shrinks below two, the leader refuses writes (NOT_ENOUGH_REPLICAS) instead of accepting data held on a single disk. Since Kafka 3.0 producers default to acks=all with idempotence on. Scripted illustration; traffic is turned down to 10 batches/s.

    Scene: Record A goes to P0’s leader, which acknowledges it before the followers fetch it. Record B is acknowledged only after both followers have fetched it and their next fetch confirms it, so its round trip is longer.

    Key idea: acks=1 trades durability for latency; acks=all with min.insync.replicas=2 means an acknowledged record is on at least two brokers.

  6. 6. Broker 1 dies

    A second in, Broker 1 crashes, taking P0’s leader and two followers with it. Just before that, the producer had written record X with acks=1: the leader acknowledged it, but no follower had fetched it yet.

    P0 now has no leader. Its keys still hash to P0, so the producers keep sending those records to the dead broker. They retry with exponential backoff (100 ms doubling to 1 s), but nobody is there; after about 2.5 s of retrying, those records fail. That is about a third of all records. P1 and P2 are untouched and keep accepting writes: the outage is per partition.

    The brokers send heartbeats to the controller (a KRaft quorum in current Kafka). Broker 1’s heartbeats stop, and once its session times out (broker.session.timeout.ms, 9 s by default) the controller fences it. Traffic is 60 batches/s here; the retry budget is compressed for the demo (real producers keep retrying up to delivery.timeout.ms, 2 minutes by default). The heartbeats and record X are scripted.

    Scene: Record X is acknowledged by P0’s leader, then Broker 1 crashes. Records for P0 are retried and then fail, about a third of all records; P1 and P2 keep accepting writes. Brokers 2 and 3 keep sending heartbeats to the controller; Broker 1 stops.

    Key idea: A dead leader makes only its partitions unavailable, and only until a new leader is elected; producer retries bridge that gap if it is short enough.

  7. 7. The controller elects a new leader

    The controller picks a new leader for P0 from its ISR: the replica on Broker 2. It bumps the partition’s leader epoch and updates the cluster metadata. The producers’ next attempts get NOT_LEADER_OR_FOLLOWER, they refresh their metadata from any live broker and send P0’s records to Broker 2. The Billing consumer for P0 follows the same metadata and resumes from its last committed offset.

    Writes succeed again, and P0’s remaining follower on Broker 3 now fetches from the new leader. Every partition is under-replicated (two copies instead of three) until Broker 1 returns.

    And record X is gone. It was acknowledged with acks=1 but was never on Broker 2. Consumers never saw it either, because it was above the high watermark. Kafka refuses to make an out-of-sync replica leader by default (unclean.leader.election.enable=false); you only lose data you acknowledged with acks=1. The election and metadata packets are scripted; in the model, the new leader takes over at the start of this step.

    Scene: The controller makes P0’s replica on Broker 2 the leader. Producers refresh their metadata and P0’s records go to Broker 2; its Billing consumer reads from there. P0’s follower on Broker 3 fetches from the new leader. No records fail; record X is lost.

    Key idea: Failover is a metadata change: a new leader from the ISR, a higher epoch, clients re-routing. Only records outside the ISR can be lost.

  8. 8. Broker 1 comes back as a follower

    Half a second in, Broker 1 restarts. It does not take P0 back: Broker 2 is leader now, with a higher epoch. Broker 1’s copy of P0 first truncates its log to the point the new leader confirms (the leader epoch tells it where the logs diverged); that is where its stale copy of record X is thrown away.

    Then it catches up: its replicas fetch from the current leaders until they reach the end of the log, and the controller adds them back to the ISR. Later, a preferred leader election can move P0’s leadership back to Broker 1 so that leaders stay evenly spread.

    Producers notice nothing: P0’s records keep going to Broker 2, the restarted replica receives no produce traffic, and nothing fails. Catch-up is a scripted illustration.

    Scene: Broker 1 restarts. Its replicas fetch from the current leaders and catch up; P0’s leader stays on Broker 2. Producers keep writing without errors.

    Key idea: A returning broker is just a lagging follower: truncate to the leader’s history, fetch until caught up, rejoin the ISR.

  9. 9. The knobs that shape a broker

    Replication factor and acks buy durability with disk, network and latency: RF 3 triples storage and adds replication traffic; acks=all adds a replication round trip to every write.

    Partition count buys parallelism, but every partition is files, memory and metadata, and changing the count remaps keys. Retention is a disk bill: tiered storage moves old segments to object storage. Failover time is detection plus election, so session timeouts trade fast failover against false alarms.

    Alternatives: a classic queue (RabbitMQ, SQS) when messages are tasks to be done once and then deleted, not a history to replay; Pulsar if you want storage separated from serving brokers.

    Scene: All three brokers are up. P0 is led by Broker 2, P1 by Broker 2 and P2 by Broker 3; producers send 150 batches per second without errors.

    Key idea: A log broker is a replicated, partitioned file system for events: every guarantee is paid for in disks, round trips or partitions.