Case study demo

Distributed message queue

Send events through a Kafka-like queue and watch partitions, consumer groups, replication and delivery.

An interactive demo of how this system behaves. It runs in your browser.

The whole system

How the parts fit together

appendcopyin ordercommitProducers, send messagesProducerssend messagesBroker, topic in partitionsBrokertopic in partitionsFollower replicas, copies of the logFollower replicascopies of the logConsumer group, one reader per partConsumer groupone reader per partOffsets, where each group isOffsetswhere each group is
  • Producers — send messages — healthy
  • Broker — topic in partitions — healthy
  • Follower replicas — copies of the log — healthy
  • Consumer group — one reader per part — healthy
  • Offsets — where each group is — healthy
  • Request/response
  • Replication link
  • Asynchronous

Producers add messages to the end of a partition, and followers copy them. Each consumer reads in order and saves how far it got, so it can carry on after a crash.

The demo below lets you try one part of this system.

The part you can try here is the lab Kafka: partitions, replication & delivery. It is the same live model.

Lab · Messaging

Kafka: partitions, replication & delivery

Producers append to a topic split into partitions. Each partition is copied to three brokers — one leader, two followers — and read by one consumer in the group. Break brokers and consumers, change acks and commit order, and see ordering, lag, data loss, duplicates, retention and replay.

Try it

Lab time 3.0 s
Producers, key = user idProducerskey = user id2/s · acks=allPartition 0, leader B1 · 3/3 in syncPartition 0leader B1 · 3/3 in synclag 0Partition 1, leader B2 · 3/3 in syncPartition 1leader B2 · 3/3 in synclag 3Partition 2, leader B3 · 3/3 in syncPartition 2leader B3 · 3/3 in synclag 1Consumer C1, reads P0, P2Consumer C1reads P0, P20 processedConsumer C2, reads P1Consumer C2reads P12 processedDead-letter queue, 0 messages parkedDead-letter queue0 messages parked
About each part:
  • Producers — key = user id — healthy — 2/s · acks=all
  • Partition 0 — leader B1 · 3/3 in sync — healthy — lag 0
  • Partition 1 — leader B2 · 3/3 in sync — healthy — lag 3
  • Partition 2 — leader B3 · 3/3 in sync — healthy — lag 1
  • Consumer C1 — reads P0, P2 — healthy — 0 processed
  • Consumer C2 — reads P1 — healthy — 2 processed
  • Dead-letter queue — 0 messages parked — healthy
  • Asynchronous
  • Event / message
  • Poison message

Producer

Acknowledged
6
of 9 sent
Produce latency
824 ms
send() → ack
Messages per request
1.0
9 requests
Retried / refused
0
Acked, then lost
0
Written twice
0

Consumers

Processed
2
Lag
4
visible, not yet processed
Received twice
0
redelivered after a crash
Applied twice
0
Transactions
—
exactly-once is off
Skipped
0
Deleted unread
0

Cluster

Under-replicated
0
partitions short of copies
Offline
0
partitions with no leader
Leader elections
0
Rebalances
0
Compacted
0
compaction is off
In
0

Numbers add up:sent 9 = waiting 0 + awaiting ack 3 + acknowledged 6 + failed 0; every partition: oldest kept ≤ committed ≤ high watermark ≤ end; one consumer per partitionThe lab checks this sum as it runs, so a counting mistake would show here.

Controls

Producers
2/s

Wait for every in-sync replica. Slower; acknowledged writes survive a leader failure.

0 ms
Topic & group
700 ms
Retention

Removes an older message once a newer one with the same key is 3 s old, so each key keeps its latest value. Needs keyed messages.

Rebalance

Every consumer stops while all partitions are handed out again.

Kafka can add partitions but never remove them.

Consumers
Commit the offset

At-least-once: a crash redelivers.

The result and the offset commit together. A crash aborts the transaction, so nothing is applied twice. Commit-before is ignored.

Failures

Click a consumer in the diagram, or a broker in the replica table, to crash or restart it.

Lag (messages visible but not yet processed)
01.32.53.851s2s3s
Show data table
TimeLag
1s0
1s1
2s3
2s2
3s2
3s4
Throughput (messages/s)
Sent by producersProcessed
02.557.5101s2s3s
Show data table
TimeSent by producersProcessed
1s40
1s20
2s00
2s22
3s42
3s60
Produce requests per second
02.557.5101s2s3s
Show data table
TimeRequests/s
1s4
1s2
2s0
2s2
3s4
3s6
Produce latency (ms, send() → ack)
025050075010001s2s3s
Show data table
Timep99
1s0
1s627
2s710
2s710
3s710
3s824

Brokers & replicas

Replicas of each partition on each broker
BrokerP0P1P2Action
B1upLeaderhas 0Followerhas 7Followerhas 1
B2upFollowerhas 0Leaderhas 7Followerhas 1
B3upFollowerhas 0Followerhas 7Leaderhas 1

“has N” is how many messages that copy holds. The in-sync replicas (ISR) are the copies that are caught up; only they can become leader.

Partition logs

user-1user-2user-3user-4user-5user-6
P0read by C1committed 0 · HW 0 · end 0lag 0
    P1read by C2committed 2 · HW 5 · end 7lag 3
    1. 0u3
    2. 1u3
    3. 2u6
    4. 3u3
    5. 4u3
    6. 5u3
    7. 6u6
    P2read by C1committed 0 · HW 1 · end 1lag 1
    1. 0u5

    Faded cells are committed. The outlined cell is next for the consumer. Dashed cells are above the high watermark: written to the leader but not yet on every in-sync replica, so consumers cannot see them. Cells marked "gone" were removed by compaction, because a newer message has the same key.

    What just happened

    Nothing yet. Start traffic or run an experiment.

    What this model simplifies
    • Three brokers, replication factor 3, and min.insync.replicas = 2 (the broker default is 1; 2 with 3 replicas is a common production choice). A controller notices a dead broker after 1.5 s.
    • Followers are dropped from the in-sync set only when their broker dies. Real Kafka also drops a follower that falls too far behind (replica.lag.time.max.ms).
    • Eager rebalancing hands partitions out round-robin and pauses the whole group. Cooperative rebalancing here moves only what must move in one step; real Kafka takes two rounds, and newer versions have a new group protocol.
    • Offsets are committed after every message. Real consumers commit in batches, which widens the window for duplicates after a crash.
    • Exactly-once transactions here cover one result and its offset. Real Kafka transactions write to output topics, which readers see only with read_committed. For effects outside Kafka, such as an email, you still need an idempotent consumer.
    • Failed messages are retried in place, blocking the partition. Many teams publish them to a retry topic with a delay instead.
    • Retention is by time only and deletes single messages. Real Kafka deletes whole log segments by time or size. Compaction here marks single entries removed once they are 3 s old; real Kafka cleans closed segments in the background, and deleting a key with an empty message (a tombstone) is not shown.

    Design walkthrough: Distributed message queue

    A message queue lets one service hand work to another without waiting for it. This walkthrough designs a queue built on a log, like Kafka. Messages are added to the end of a log and kept for a set time.

    Requirements

    What it must do

    • Producers add messages to a named topic.
    • Consumers read messages in order, and can read old ones again.
    • Several consumers share the work of one topic.

    How well it must do it

    • No confirmed message is lost when one broker fails.
    • Handle hundreds of thousands of messages a second.
    • Keep the order of messages that share a key, such as one user's events.

    Rough numbers

    • 100,000 messages a second at 1 KB each is 100 MB of writes a second.
    • Keeping 7 days is 100 MB × 86,400 × 7, about 60 TB, before copies.
    • With 3 copies of everything, plan for about 180 TB of disk.

    How a request flows

    Write pathPublish a message

    1. Producers
    2. Broker
    3. Partition log
    4. Follower replicas
    1. Producers to Broker

      A producer sends a message with a key, such as user:42. The key's hash picks the partition, so one user's messages stay together.

    2. Broker to Partition log

      The partition's leader adds the message to the end of its log on disk.

    3. Broker to Follower replicas

      Followers copy the new message into their own logs.

    4. Broker to Producers

      With acks=all, the leader confirms only after the in-sync followers have the message.

    Read pathConsume messages

    1. Consumer group
    2. Broker
    3. Offsets
    1. Consumer group to Broker

      A consumer asks for the messages after its last position. That position is called an offset.

    2. Broker to Consumer group

      The broker returns the next batch, in order.

    3. Consumer group to Offsets

      After it has handled the batch, the consumer saves the new offset.

    4. Offsets to Consumer group

      If the consumer crashes, another one takes over the partition and starts from the saved offset.

    Scaling it

    • Add partitions to raise throughput. Each partition is its own log on some broker.
    • Add consumers to a group, up to one per partition. Extra consumers sit idle.
    • Send messages in batches and compress them. Adding to the end of a file is the fastest kind of disk write.

    What breaks, and what happens then

    • The leader of a partition crashes

      What users see
      Writes to that partition pause for a few seconds.
      What the design does
      An in-sync follower becomes the leader. It has every confirmed message, so none is lost.
    • A consumer crashes after its work but before saving its offset

      What users see
      The next consumer receives the same batch again.
      What the design does
      This is at-least-once delivery. Make the work safe to repeat, for example by recording each message id.
    • A consumer is slower than the producers

      What users see
      It falls further behind, and old messages may be deleted before it reads them.
      What the design does
      Alert on how far behind it is. Add consumers and partitions, or make each message cheaper to handle.

    Trade-offs

    • Confirm a write after one copy, or after all in-sync copies
      A good default
      All in-sync copies, when losing a message is not acceptable.
      What it costs
      Each write waits for the slowest in-sync follower.
    • Few partitions, or many
      A good default
      Enough for the peak throughput and the number of consumers you need.
      What it costs
      More partitions mean more files and a slower recovery after a broker fails.
    • Save the offset before the work, or after it
      A good default
      After, so a crash repeats work and never skips it.
      What it costs
      Consumers must cope with duplicates.

    Common mistakes

    • Expecting order across a whole topic. Order holds only inside one partition.
    • Adding more consumers than partitions and expecting more speed.

    Questions an interviewer might ask

    How do you get exactly-once processing?

    You cannot stop a message arriving twice, so make its effect happen once. Store the message id with the result in one transaction, and skip ids you have seen.

    What happens to a message that always fails?

    After a few retries, move it to a dead letter queue so it does not block the partition. Someone looks at it later.

    When would you choose a classic queue such as RabbitMQ?

    When each message is a task for one worker and is confirmed on its own. Also when nobody needs to read old messages again.