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
In AI systems: Retrieval and vector search in depth
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 app — healthy — sends events
- Partition 0 — healthy
- Partition 1 — healthy
- Partition 2 — healthy
- Consumer C1 — healthy
- Consumer C2 — healthy
- A topic, in partitions. The orders app sends events to a Kafka topic, a named log of events, split into 3 partitions.
- The key picks one. The key user-2 picks it: hash(user-2) % 3, the remainder after dividing by 3, is 1.
- Same key, same place. The next event for user-2 goes to partition 1 too, after the first, so their order is kept.
- 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.
- One reader each. In a consumer group, each partition has one reader: C1 reads partitions 0 and 2, and C2 reads 1.
- Order inside one only. Kafka keeps order only inside a partition, so events that must stay in order need the same key.
- 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
- A topic is a named log of events, split into partitions that can be read in parallel.
- An event's key picks its partition: hash(key) % partitions, the same while the partition count stays fixed.
- Order is kept only inside one partition, so events that must stay in order share a key.
- 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 (A waiting line for work. One part adds messages, and another takes them off and handles them later, at its own pace.), 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. (An open-source system that stores streams of messages in order on disk. Many services can read the same messages, each at its own pace.) 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 (A position counted from a start. In Kafka it is a message's place in its partition: 0, 1, 2 and so on. In a paged list it is how many items to skip.). 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 (One slice of the data. In Kafka, one ordered log inside a topic.). 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
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.
Producers write to a partition
Producer, the shop app Producer the shop app Partition 0, kept in order Partition 0 kept in order Partition 1, kept in order Partition 1 kept in order Partition 2, kept in order, NOW Partition 2 kept in order 1 message NOW - 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 4Step 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 00messagesemptyPartition 10messagesemptyPartition 21messageuser-2Step 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.
Each partition is replicated
Each partition is stored on several brokers, the servers that hold the log. One (A server that receives messages and passes them on to the services that read them. In Kafka, each broker stores some partitions and serves their reads and writes.) leads the partition and takes its writes, and the others, its followers, copy from it. The (The copies of a Kafka partition that are fully caught up with the leader.) (ISR) are the (The one copy that takes every write for its data. The other copies, the followers, copy from it. Kafka has one leader for each partition.) plus the followers that have caught up. With the producer setting (How many copies of a write a producer waits for before treating it as done: 0, 1 (the leader), or all (every in-sync replica).)=all, a write is confirmed only after every in-sync (A copy of a database kept on another machine.) has it.
Consumers in a group share partitions
Pick a case to follow belowWith 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 order Partition 0 kept in order Partition 1, kept in order Partition 1 kept in order Partition 2, kept in order Partition 2 kept in order Consumer 1, billing, NOW Consumer 1 billing reads P0 NOW Consumer 2, billing Consumer 2 billing - 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 3Step 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 group2Partitions each2, 1Idle consumers0all busyStep 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 (A set of workers that share a topic's partitions. Each partition is read by one worker in the group, and one worker may read several.), 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.
Offsets record progress
Pick a case to follow belowWith 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 log Partition 0 the log Consumer, billing, NOW Consumer billing at offset 5 NOW Email service Email service - Partition 0 — the log — healthy
- Consumer — billing — healthy — NOW — at offset 5
- Email service — healthy
- Message
- Send email
- Commit offset
Step 1 of 6Step 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 offset5the next read starts at 5Emails for order 810not sentStep 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.
(In Kafka: a consumer saving how far it has read, so after a restart it carries on from that point.) 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 (A delivery guarantee where a message may be processed more than once, but is never silently lost.) 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 (A delivery guarantee where a message is never processed twice, but may be silently lost.) 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 (Safe to repeat. Doing it twice has the same effect as doing it once.).
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 (A copy that takes its writes from the leader instead of from clients.) 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.
Messages are kept, then deleted
Kafka keeps each message for a set time, the (How long Kafka keeps a message before deleting it, whether or not it has been read.) period, whether or not anyone has read it. The default is 7 days. A reader can therefore go back and (Reading a saved log again from an earlier point, to rebuild state or process events again. In Kafka, this means resetting a consumer group's offsets.) 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
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 app — healthy
- Main queue — healthy
- Email worker — healthy
- Delay queue — healthy
- Dead letters — healthy
- Tries so far
- 1
- Seconds since the first try
- 0
- A message arrives. The email worker takes message email 7 from the main queue and tries to send it.
- It fails. Sending fails, so instead of retrying at once, the worker puts it on a delay queue for 1 s.
- Back after the wait. When the wait ends, the message goes back to the main queue; other messages kept flowing meanwhile.
- Longer each time. Each new failure waits longer, 1 s, 10 s and 60 s, giving a struggling email service time to recover.
- Then dead letters. After 4 failed tries it goes to the dead-letter queue for a person to check, instead of looping forever.
- Delays on purpose. The same kind of queue can also delay work on purpose, such as a reminder email sent a day later.
- 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
- A failed message is not retried at once; it waits on a delay queue first.
- Kafka has no per-message delay, so teams use one retry topic for each wait.
- Each new failure waits longer, here 1 s, 10 s and 60 s, like backoff for messages.
- 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 (How far behind a consumer group is: the gap between the last message written to a partition and the last one it has read.), 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 (A tree that stores words one letter per step, so words that start the same share a path.), move it to a (A separate place a message goes after it fails processing too many times, so it stops blocking the messages behind it.) 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 (Reassigning a topic's partitions across a consumer group's members, for example after one joins or leaves.) 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
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 (A single key that gets far more reads or writes than the others.), 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 (A delivery guarantee where the effect of a message is applied one time only, even after a retry. Systems get it by delivering at least once and skipping repeats. It holds only inside the parts that system controls.). Kafka (A group of database changes that succeed or fail together: either all of them are saved, or none are.) 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 (The fewest in-sync replicas a partition must have before it will accept a write sent with acks=all.)=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?
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
Apply it
Judge a design
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.
- Official docsApache Kafka documentationApache Software FoundationTopics, partitions, consumer groups, replication and delivery guarantees, as Kafka defines them.
- Research paperKafka: a Distributed Messaging System for Log Processing (2011)Kreps, Narkhede and Rao, NetDBWhy LinkedIn built Kafka as an append-only log, and how consumers track their own position.
- Official docsReliability guideRabbitMQ documentationAcknowledgements, confirms and what a queue does when a consumer or broker fails.