Queues and Event Streams in Depth
This lesson is for software engineers who already put a queue in their diagrams and now need to defend it when the interviewer pushes. It assumes you know what a queue is for, as covered in Core Building Blocks. By the end you will be able to choose between a message queue and an event log, state exactly what delivery guarantee your design gives, size partitions and consumers, and handle failures without losing or double-processing work.
How this comes up in the interview
You draw an arrow from a service to a queue, and the deep dive starts with one of these:
"What happens if the consumer crashes halfway through a message?"
"Can the same message be processed twice? What does that cost you?"
"Do messages for one user arrive in order?"
"Traffic triples during a sale. What happens to the queue?"
These probe deep dive and scalability and trade-offs. A strong answer names the delivery semantics, the ordering scope and the failure path without being asked, and backs the size with numbers.
Two different tools: queues and logs
A message queue (RabbitMQ, Amazon SQS) hands each message to one consumer, and the message is deleted once that consumer acknowledges it. Think of it as a to-do list shared by workers. It shines for independent tasks: send this email, resize this image, charge this invoice. Workers can be added freely, and a slow message does not block the others.
A log-based event stream (Kafka, Amazon Kinesis, Redpanda) appends events to a partitioned log and keeps them for a retention period, whether or not anyone has read them. Each consumer group tracks its own position (offset) in each partition. Several independent services can read the same events, a new service can start from the beginning, and a broken consumer can rewind and replay.
The interview test: if one event must trigger work in several services, or you may need to replay history, use a log. If you just need a pool of workers to drain tasks, use a queue. Saying "Kafka" for a simple task queue is not wrong, but you should be able to explain what the log buys you.
Delivery semantics
Every consumer does two things: process the message and record that it is done (acknowledge it, or commit its offset). The order of those two steps sets the guarantee.
At-most-once: record first, then process. A crash after recording loses the message. Acceptable only for data you can afford to drop, such as some metrics.
At-least-once: process first, then record. A crash after processing but before recording means the message is delivered again. This is the default you should design for.
Effectively-once: at-least-once delivery plus an idempotent consumer, so a redelivery has no additional effect.
"Exactly-once delivery" across a network and an external side effect such as sending an email or charging a card is not something a broker can promise. What you can build is exactly-once effect: give every event a unique id, and have the consumer record processed ids in the same database transaction as its write:
BEGIN;
INSERT INTO processed_events (event_id) VALUES ($1); -- fails on a repeat
UPDATE inventory SET reserved = reserved + $2 WHERE sku = $3;
COMMIT;If the insert fails on the primary key, the event was already applied and the consumer just acknowledges it. Some streams offer transactions that make read-process-write exactly-once within the stream itself, but the moment you touch an outside system you are back to idempotency.
Partitions, ordering and consumer groups
A stream is split into partitions. Ordering is guaranteed only within a partition, so you choose a partition key that groups the events that must stay in order. Key order events by order_id and every event for one order (placed, paid, shipped) lands in one partition in sequence. There is no ordering across different orders, and you usually do not need it.
In a consumer group, each partition is read by exactly one consumer at a time. Two consequences follow:
The partition count caps the group's parallelism. With 12 partitions, a 13th consumer sits idle.
When consumers join or leave, partitions are reassigned (a rebalance) and consumption pauses briefly. Frequent restarts cause frequent pauses.
Kafka's newer share groups relax the first rule: several consumers read one partition and acknowledge messages individually, queue-style, at the cost of per-key ordering. Mention them if the interviewer asks how to get queue semantics from a log, but design ordered consumers around the classic rule.
Choose more partitions than you need today, because increasing the count later changes which partition a key maps to and breaks per-key ordering during the change. Too many partitions has costs too (more open files, longer rebalances), so size from the numbers rather than picking a huge round number.
Queues have a parallel concept: plain queues give no ordering, while FIFO queues with a group id (SQS message groups) keep order per group, at lower throughput.
Backpressure and lag
A queue's main job under load is absorbing a burst so producers do not fail when consumers fall behind. The metric that matters is consumer lag: how many messages, or how many seconds, the consumers are behind the newest message. Alert on lag, and autoscale consumers from it rather than from CPU.
Absorbing is not the same as surviving. If consumers are slower than producers for long enough, the backlog grows until retention deletes unread events or the queue hits its size limit. Your options, in the order to propose them:
Scale consumers out, up to the partition count.
Make each message cheaper: batch database writes, drop work that can be skipped.
Push back on producers: reject or delay non-critical messages at the front door with
429or a "try later" response.Shed load: sample or drop low-value events, and say explicitly which ones.
Retention, replay and dead letters
Retention. A log keeps events for a fixed time (often 7 days) or size. Retention is your recovery window: if a consumer had a bug for three days, you can fix it and replay from three days ago, as long as its writes are idempotent.
Retries and dead-letter queues. Some messages fail every time: malformed data, a reference to a deleted record. Retrying forever wastes capacity, and in an ordered partition it blocks every message behind it. The standard design: retry a few times with exponential backoff, then move the message to a dead-letter queue, alert, and continue. Someone inspects the dead letters, fixes the cause and replays them. In an ordered stream, say what moving a message aside does to ordering for that key; sometimes the right answer is to pause that key, not skip it.
The dual-write problem. A service that writes to its database and then publishes an event can crash between the two, leaving the database updated and no event sent. The outbox pattern fixes it: write the event into an outbox table in the same transaction as the business change, and have a separate relay (or change data capture on the database log) publish outbox rows to the stream. Interviewers like this one, because it shows you see the gap.
When a queue is the wrong tool
The user is waiting for the answer. A checkout that must confirm payment before showing "Order placed" needs a synchronous call. A queue adds latency and a polling problem.
You need a transaction across the steps. A queue makes steps eventually consistent; if they must succeed or fail together, keep them in one database transaction or design compensation explicitly.
The scale does not justify it. A few hundred background jobs a minute can live in a database table with a
statuscolumn and a worker that polls it withSELECT ... FOR UPDATE SKIP LOCKED. One fewer system to run.
Worked example: order events for an online store
Prompt: "When a customer places an order, we need to reserve inventory, send a confirmation email, notify the warehouse and update analytics. Peak load is 2,000 orders per second."
A weak answer: "The order service puts a message on a queue and the other services read it." Which queue type, what if two services need the same message, what if the email is sent twice, what if inventory fails? None of it is answered.
A strong answer:
Tool. Four independent consumers need the same event, and we may need to replay analytics, so use a log-based stream with one
order-eventstopic and one consumer group per service.Publishing. The order service writes the order and an outbox row in one transaction; a relay publishes the outbox to the stream. No order exists without its event.
Key and ordering. Partition by
order_id, so placed, paid and cancelled events for one order are consumed in order.Sizing. Assume events average 1 KB. At a sustained 2,000 events per second that is 172.8 million events and about 173 GB per day; 7 days of retention is about 1.2 TB, or about 3.6 TB with three replicas. If one inventory consumer handles about 500 events per second (measure this; it depends on the database write), the group needs 4 consumers at peak. Use 12 partitions so it can triple without repartitioning.
Semantics per consumer. Inventory: idempotent by event id in the same transaction as the reservation. Email: check for a "confirmation sent for order X" record, call the provider with the order id as its idempotency key, then write the record. A crash between sending and recording means a redelivery sends again; the provider's idempotency key absorbs it, and without one the customer gets a rare duplicate, which is tolerable for an email. Recording before sending would turn that duplicate into a lost email, which is worse. Analytics: at-least-once with deduplication downstream.
Failures. Three retries with backoff, then the dead-letter topic with an alert. Lag per consumer group is the autoscaling signal and the paging alert.
Then state the trade-off: the customer sees "Order placed" before inventory is reserved, so the design needs a path for "reserved failed" (cancel and refund, or backorder). That is a product decision, and naming it scores on trade-offs.
Follow-ups to expect
"A popular product gets 90 percent of orders. Does one partition get hot?" Not with
order_idas the key; it would withproduct_id. The inventory row for that product is still hot in the database, which is a contention problem, not a queue problem."How do you change the event format?" Add fields compatibly, version the schema, and keep consumers tolerant of unknown fields. A schema registry enforces this in larger systems.
"How long would a replay of 3 days take?" Three days at a sustained 2,000 per second is about 518 million events. At 4,000 per second of consumer capacity that takes about 36 hours, and if the same consumers must also keep up with 2,000 per second of live traffic, the net catch-up rate halves and it takes about 72 hours. Numbers like this decide whether replay is a real recovery plan, or whether you need a faster bulk path.
Mistakes that cost points
Claiming exactly-once. Say at-least-once plus idempotent consumers, and show the idempotency.
No ordering scope. Say what is ordered (per key) and what is not.
More consumers than partitions as the scaling plan. The extras sit idle.
Ignoring poison messages. Without a dead-letter path, one bad message stalls a partition.
Publishing after the database commit with no outbox. A crash in between loses events silently.
Practice it
Take the chat system: decide whether message delivery to offline users goes through a queue or a log, pick the partition key, and state the delivery semantics in two sentences. Then test it under questioning:
Design a URL Shortener, where click analytics is a natural stream
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Design a URL ShortenerSystem Design · Medium
- Design a Rate Limiter ServiceSystem Design · Medium
- Design Live Score Alert FanoutSystem Design · Medium
- Design a Video Upload and Transcoding PipelineSystem Design · Medium
Read next
- Search and Geospatial Indexes in Depth
Explain inverted indexes, analyzers and ranking, keep a search index in sync with change data capture, support partial-word search, and size a find-nearby feature with geohashes or quadtrees.
8 min read
- How to Run a Deep Dive in a System Design Interview
Pick the riskiest part of your design and work through it in five steps (numbers, options, trade-off, decision, failure mode), with a chat message fan-out as the worked example.
9 min read
- Choosing and Scaling a Database
Choose a database from the data's access patterns, explain how indexes, replicas and shards change performance and what each costs, and walk through two storage decisions with numbers.
8 min read
- Caching in Depth
Place a cache, choose its read and write pattern, TTL and eviction, handle stampedes, hot keys and lookups for missing keys, and calculate how much load it takes off the database.
8 min read
