Stage 2 · Building blocks · Medium · 24 min

Message queues and Kafka

A queue lets slow work run after the request is answered. Kafka keeps events in a log that many readers can replay. Learn partitions, consumer groups and lag.

What each interview level is expected to know

Learn first: API styles: REST, gRPC, WebSockets and SSE, Vertical and horizontal scaling

After this lesson you can:

  • Explain partitions, replicas, consumer groups and offsets in Kafka.
  • Predict what happens when a group has more consumers than partitions.
  • Handle lag, a poison message and a crash before the offset is saved.

Start here

See it in 60 seconds

How a key picks a partition

Kafka splits a topic into partitions, and an event's key picks its partition, so one user's events stay in order while the work spreads out.

Scene 1 of 6 · A topic, in partitions

The orders app sends events to a Kafka topic, a named log of events, split into 3 partitions.

Orders appOrders appsends eventsPartition 0Partition 0Partition 1Partition 1Partition 2Partition 2Consumer C1Consumer C1Consumer C2Consumer C2
  • Orders app — healthy — sends events
  • Partition 0 — healthy
  • Partition 1 — healthy
  • Partition 2 — healthy
  • Consumer C1 — healthy
  • Consumer C2 — healthy
  1. A topic, in partitions. The orders app sends events to a Kafka topic, a named log of events, split into 3 partitions.
  2. The key picks one. The key user-2 picks it: hash(user-2) % 3, the remainder after dividing by 3, is 1.
  3. Same key, same place. The next event for user-2 goes to partition 1 too, after the first, so their order is kept.
  4. Other keys spread out. Events for other users, such as user-1 and user-4, land on the other partitions, so the work spreads out.
  5. One reader each. In a consumer group, each partition has one reader: C1 reads partitions 0 and 2, and C2 reads 1.
  6. Order inside one only. Kafka keeps order only inside a partition, so events that must stay in order need the same key.
  7. Now you try. Pick the key on an event, and see which partition and consumer get it. For example: Key user-4 goes to partition 2, because hash(user-4) % 3 = 2; consumer C1 reads it. Every event keyed user-4 lands there, so C1 sees them in the order they were sent.

Scene 1 of 6: A topic, in partitions. The orders app sends events to a Kafka topic, a named log of events, split into 3 partitions.

Key points

  1. A topic is a named log of events, split into partitions that can be read in parallel.
  2. An event's key picks its partition: hash(key) % partitions, the same while the partition count stays fixed.
  3. Order is kept only inside one partition, so events that must stay in order share a key.
  4. In a consumer group, each partition has exactly one reader, so partitions cap how many can share the work.

Go deeper in the Kafka: partitions, replication & delivery lab →

In plain words

Say a shop's orders app must send an email after each order, and sending takes 2 seconds. With a , the orders app writes a short message, "order 81 paid", and answers the customer at once. A worker reads the message later and sends the email. Once the worker confirms it, a plain queue deletes the message. works another way. It adds each message to the end of a log and keeps it for a set time, read or not. Each reader remembers its own position in the log, called its . So several readers can each read every message, and a reader can go back and read old ones again.

In Kafka, a topic is split into partitions, and order holds only inside one . So all messages about one order use the same key, which sends them to the same partition. A group of workers shares the partitions, one worker per partition, so extra workers beyond the partition count sit idle. If a worker crashes before saving its offset, the next one reads those messages again, so the email code must cope with repeats.

The problem it solves

Say checkout calls email, inventory and analytics one after another and waits for each. Checkout is then as slow as the three together. If any one of them is down, checkout hangs or fails with it. A burst of orders also hits all three services at the same moment.

Why it matters

Many systems have work the user should not wait for: sending an email, updating a feed, counting a click. A queue or a log carries that work to the service that does it. Interviewers then ask what happens when it goes wrong: a message arrives twice, late, or out of order.

A worked example

A checkout service calls email, inventory, and analytics one after another, at 50 ms each. That takes about 3 × 50 = 150 ms before it can reply. A queue instead lets checkout reply in the time its own work takes, often under 10 ms. The three jobs then finish in the background.

Think of it like…

Think of the ticket rail in a restaurant kitchen. A waiter clips an order to the rail and goes back to the tables. A cook takes the next ticket when free.

Where this analogy stops working

Handing work over without waiting is the useful part. But a paper ticket is taken once. A queue can hand the same message out twice, when a worker crashes before it confirms. So workers must cope with repeats. Kafka also keeps each message after it is read, so other readers can read it too.

Try it

See it working

Live simulationOpen the full lab →

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.

    Also try: Queues & backpressure

    Mechanics

    How it works

    The steps below follow messages through Kafka. A producer writes each message to a partition, consumers in a group read them, and each consumer records how far it has got. The pictures use one topic with 3 partitions.

    1. Producers write to a partition

      Producer, the shop appProducerthe shop appPartition 0, kept in orderPartition 0kept in orderPartition 1, kept in orderPartition 1kept in orderPartition 2, kept in order, NOWPartition 2kept in order1 messageNOW
      • Producer — the shop app — healthy
      • Partition 0 — kept in order — healthy
      • Partition 1 — kept in order — healthy
      • Partition 2 — kept in order — healthy — NOW — 1 message
      • Message
      Step 1 of 4

      Step 1 of 4 · Partition 2

      Done: "user-2 added to cart" goes to partition 2

      What happens
      The producer hashes the key, user-2, and takes the result % 3. That gives partition 2.
      Why
      The key decides the partition, so the producer needs no table of where things go.
      What changes
      Partition 2 now holds 1 message, in the order they arrived.
      Next
      "user-1 signed up" goes to partition 1
      Partition 0
      0messages
      empty
      Partition 1
      0messages
      empty
      Partition 2
      1message
      user-2

      Step 1 of 4: Partition 2. "user-2 added to cart" goes to partition 2. The producer hashes the key, user-2, and takes the result % 3. That gives partition 2.

      A producer is a service that writes messages, and a topic is a named log of them. A topic is split into partitions. The producer picks one from the message's key: hash(key) % partitions. In the picture, the topic has 3 partitions.

      Step through four messages. Both messages keyed user-2 land on the same partition, in the order they were sent. So any reader sees "added to cart" before "paid".

      Kafka keeps order inside one partition only. Messages with different keys can be read in any order relative to each other. A key also keeps its partition only while the number of partitions stays the same. Adding partitions later sends some keys to a different one.

    2. Each partition is replicated

      Each partition is stored on several brokers, the servers that hold the log. One leads the partition and takes its writes, and the others, its followers, copy from it. The (ISR) are the plus the followers that have caught up. With the producer setting =all, a write is confirmed only after every in-sync has it.

    3. Consumers in a group share partitions

      Pick a case to follow below

      With this case: Consumer 1 reads 2 partitions and consumer 2 reads 1. Adding a consumer would spread the work, up to 3 consumers.

      Partition 0, kept in orderPartition 0kept in orderPartition 1, kept in orderPartition 1kept in orderPartition 2, kept in orderPartition 2kept in orderConsumer 1, billing, NOWConsumer 1billingreads P0NOWConsumer 2, billingConsumer 2billing
      • Partition 0 — kept in order — healthy
      • Partition 1 — kept in order — healthy
      • Partition 2 — kept in order — healthy
      • Consumer 1 — billing — healthy — NOW — reads P0
      • Consumer 2 — billing — healthy
      • Message
      Step 1 of 3

      Step 1 of 3 · Consumer 1

      Done: Consumer 1 reads partition 0

      What happens
      The group gives partition 0 to consumer 1.
      Why
      Inside one group, each partition has exactly one reader. That keeps its messages in order.
      What changes
      Consumer 1 reads partition 0.
      Next
      Consumer 1 reads partition 1
      Consumers in the group
      2
      Partitions each
      2, 1
      Idle consumers
      0
      all busy

      Step 1 of 3: Consumer 1. Consumer 1 reads partition 0. The group gives partition 0 to consumer 1.

      A consumer is a service that reads messages. Consumers that do the same job form a , and within a group each partition has one reader. Switch between 2, 3 and 4 consumers.

      With 2 consumers, one reads two partitions and the other reads one. With 3, each reads one. With 4, the fourth has nothing to read, because a partition cannot have two readers in the same group.

      So the number of partitions caps how many consumers in one group can work at once. Pick it with room to grow.

      A second group, such as analytics beside billing, reads every message again with its own offsets. Groups do not take messages from each other.

    4. Offsets record progress

      Pick a case to follow below

      With this case: The customer got 2 emails for order 81. Committing after the work is at-least-once delivery: nothing is skipped, but a crash can repeat work.

      Partition 0, the logPartition 0the logConsumer, billing, NOWConsumerbillingat offset 5NOWEmail serviceEmail service
      • Partition 0 — the log — healthy
      • Consumer — billing — healthy — NOW — at offset 5
      • Email service — healthy
      • Message
      • Send email
      • Commit offset
      Step 1 of 6

      Step 1 of 6 · Consumer

      Done: The consumer reads offset 5

      What happens
      The message at offset 5 says "order 81 paid".
      Why
      A consumer reads a partition in order, one offset after another.
      What changes
      Its job is to send the order email, then move on to offset 6.
      Next
      The consumer sends the order email
      Committed offset
      5
      the next read starts at 5
      Emails for order 81
      0
      not sent

      Step 1 of 6: Consumer. The consumer reads offset 5. The message at offset 5 says "order 81 paid".

      What these pictures simplify. These pictures use 3 partitions and a handful of messages. The key-to-partition table is a stated example, not a real hash. Real consumers read many messages per request and often commit offsets in batches. The Kafka lab above runs many messages together.

      A consumer saves how far it has read by committing an offset. In the picture, the consumer reads the message at offset 5, "order 81 paid", and has to send an email. Then it crashes. Switch between committing after the work and before it.

      after the work: the email goes out, the consumer crashes before it commits, and a new consumer starts again at offset 5. The customer gets the email twice. This is delivery: nothing is skipped, but work can repeat.

      Commit before the work: the offset moves to 6 first, the consumer crashes before sending, and the new consumer starts at 6. The email is never sent. This is delivery: no repeats, but a message can be skipped.

      Most systems choose at-least-once and make repeats harmless. For example, the consumer records which orders already have an email, and skips those. A consumer that can safely handle a message twice is called .

    5. Failures move work around

      If a consumer stops, the group rebalances: its partitions go to the consumers still running. If a broker stops, an in-sync takes over as leader of its partitions. Reading or writing pauses for a short time in both cases. Some messages may also be delivered twice, so consumers must expect repeats.

    6. Messages are kept, then deleted

      Kafka keeps each message for a set time, the period, whether or not anyone has read it. The default is 7 days. A reader can therefore go back and old messages. A consumer that falls further behind than the retention period misses the messages deleted before it reached them.

    Use it when

    • Slow work the user does not need to wait for, such as sending an email or resizing an image: the request can answer first.
    • One event that several services need: an order is placed, and billing, search and analytics each read it at their own pace.
    • Bursts of traffic: the queue grows during the burst and empties afterwards, so the workers keep a steady pace.
    • Reading old events again, for example after fixing a bug in a consumer: this needs a log that keeps messages, such as Kafka.

    Skip it when

    • The caller needs the answer now, such as a login or a profile read: use a direct call.
    • Every message must stay in one order at high volume: one partition gives that order, but only one consumer in a group can read it.
    • A few jobs a minute with simple needs: a managed queue, or a database table that a worker checks, is less to run.

    Check yourself

    Kafka keeps messages in order within what?

    Also

    More in 60 seconds

    Retry later with a delay queue

    A message that fails waits on a delay queue and comes back later, each wait longer, until it works or goes to the dead-letter queue.

    Scene 1 of 6 · A message arrives

    The email worker takes message email 7 from the main queue and tries to send it.

    Orders appOrders appMain queueMain queueEmail workerEmail workerDelay queueDelay queueDead lettersDead letters
    • Orders app — healthy
    • Main queue — healthy
    • Email worker — healthy
    • Delay queue — healthy
    • Dead letters — healthy
    Tries so far
    1
    Seconds since the first try
    0
    1. A message arrives. The email worker takes message email 7 from the main queue and tries to send it.
    2. It fails. Sending fails, so instead of retrying at once, the worker puts it on a delay queue for 1 s.
    3. Back after the wait. When the wait ends, the message goes back to the main queue; other messages kept flowing meanwhile.
    4. Longer each time. Each new failure waits longer, 1 s, 10 s and 60 s, giving a struggling email service time to recover.
    5. Then dead letters. After 4 failed tries it goes to the dead-letter queue for a person to check, instead of looping forever.
    6. Delays on purpose. The same kind of queue can also delay work on purpose, such as a reminder email sent a day later.
    7. Now you try. How many times in a row does sending email 7 fail? For example: It is sent on try 3, 11 s after the first try. It waited 2 times, longer each time. A retry can send an email twice, so skip message ids already done.

    Scene 1 of 6: A message arrives. The email worker takes message email 7 from the main queue and tries to send it.

    Key points

    1. A failed message is not retried at once; it waits on a delay queue first.
    2. Kafka has no per-message delay, so teams use one retry topic for each wait.
    3. Each new failure waits longer, here 1 s, 10 s and 60 s, like backoff for messages.
    4. After the last try, the message goes to the dead-letter queue for a person to check.

    Go deeper in the Kafka: partitions, replication & delivery lab →

    Judgement

    Trade-offs and how it fails

    What you give up

    Resilience
    The sender and the reader do not need to be up at the same time. If a consumer is down, its messages wait in the log until it returns, or until retention deletes them.
    Latency
    The work finishes after the request has been answered, so its result is not ready at once. With acks=all, each write also waits for the in-sync followers to copy it.
    Consistency
    A reader sees a change some time after it happened. It must also cope with a message that arrives twice, and with messages for different keys arriving in any order.
    Complexity
    A team that runs Kafka must watch , handle messages that keep failing, plan the partition count and change message formats with care.

    Failure modes

    • Consumer lag keeps growing: the group reads more slowly than producers write. Once the oldest unread messages pass the retention period, Kafka deletes them unread.
    • A poison message: one message fails every time it is tried, and the consumer cannot move past it. After a few , move it to a and carry on.
    • A consumer crashes after doing the work but before committing the offset. The message is delivered again, so a consumer that is not idempotent charges the card or sends the email twice.
    • acks=1 and the leader fails: the leader had confirmed a write that no follower had copied yet. The new leader does not have it, so the write is lost.
    • Adding partitions: hash(key) % partitions changes, so some keys move to another partition. A key's new messages can then be read before its older ones.
    • Frequent rebalances: a consumer that takes too long on a batch is removed from the group, and each deploy restarts consumers. In the older way of rebalancing, every pauses the whole group. The newer, cooperative way pauses only the partitions that move.

    In the real world

    • LinkedIn, where Kafka was created, wrote in 2019 that its Kafka clusters handled more than 7 trillion messages a day. Source: LinkedIn engineering: Kafka at 7 trillion messages a day (checked 14 October 2026)
    • Uber's engineering blog (2020) says its Kafka clusters carry trillions of messages a day, including events from the rider and driver apps.
    • Amazon's documentation for SQS, its queue service, says a standard queue delivers each message at least once and may deliver a copy again. It tells teams to make their consumers idempotent.

    Trade-offs to be ready to discuss: Queue vs pubsub · Kafka vs rabbitmq

    Check yourself

    A consumer crashes after handling a message but before saving its place. What happens?

    Interview

    What interviewers look for

    • Say what key you partition by, and why: "I key by order id, so one order's events stay in order." Then name the risk: one very busy key, a , overloads its partition.
    • State the delivery: "Kafka gives at-least-once delivery in the usual setup, so my consumer is idempotent. It skips a message id it has already handled."
    • Know the limit of . Kafka cover reading from one topic and writing to another. An email or a card charge happens outside Kafka, so it still needs an idempotent consumer.
    • For writes you cannot afford to lose, say acks=all, three copies and =2. Then give the cost: slower writes, and refused writes when fewer than two copies are in sync.
    • Pick the partition count for the most consumers you will need at peak. Adding partitions later is possible, but keys move, so per-key order breaks during the change.
    • Name what you would watch: consumer lag first. Add a dead-letter queue for messages that keep failing, and remember that retention limits how far behind a consumer may fall.

    Say it out loud: A consumer crashes after charging a card but before committing the offset. What happens, and how do you make it safe?

    A topic has 4 partitions and a consumer group has 6 consumers. What happens?

    Expected depth by interview level

    Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.

    JuniorUseful
    Queues move slow work out of the request, and let producer and consumer fail independently.
    MidCore
    Queue vs log, partitions and keys, consumer groups, retries and dead-letter queues, at-least-once delivery.
    SeniorCore
    Ordering per key, acks and replication, idempotent producers and consumers, lag, rebalancing, partition sizing.
    StaffExpected
    Retention and replay, schema evolution, exactly-once limits, and running an event platform other teams depend on.

    Practice

    Apply it

    Three harder questions

    The first two use the idea on a new case. The last asks you to judge a design.

    Apply it

    A topic has 6 partitions, and a consumer group has 3 consumers. How many partitions does each consumer read?

    Apply it

    Retention is 7 days. A consumer group is down for 9 days. What happens when it comes back?

    Judge a design

    A consumer charges a card, then commits the offset. A few times a month it crashes between the two, and a customer pays twice. What is the better design?

    Next: search indexes and autocomplete, the structures that find matching text without reading every row.

    Go deeper

    Sources and further reading

    First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.