A message queue is a buffer between two parts of a system. One part (the producer) drops messages in; another part (the consumer) takes them out and processes them later, at its own pace. The producer does not wait for the work to finish.
This one idea solves three problems at once: slow work no longer blocks the user, traffic spikes get absorbed instead of crashing the database, and a failing component no longer takes the whole system down. Almost every large design in an interview (notifications, video processing, analytics, order pipelines) uses a queue somewhere.
Detailed Notes
What is it?
A message is a small piece of data describing something that happened or something to do, for example {"type":"send_email","user_id":42}. A broker is the server that stores messages reliably and hands them to consumers. Examples: Apache Kafka, RabbitMQ, Amazon SQS, Google Pub/Sub.
Two delivery models:
Queue (point-to-point): each message is processed by exactly one consumer. Many consumers share the work, like cashiers sharing one line. Use it to distribute tasks.
Pub/sub (publish/subscribe): a producer publishes to a topic (a named stream of messages) and every subscriber gets its own copy. Use it to broadcast events: an "order placed" event goes to billing, inventory and email independently.
Kafka-style systems combine both with consumer groups: within a group each message goes to one member (queue behaviour), but every group gets all messages (pub/sub behaviour).
Why do we need it?
Without a queue, a service calls the next one directly and waits. Three things go wrong:
Slow work blocks users. Encoding a video takes minutes. The upload API should return in 200 ms with "we got it", and let a worker do the encoding.
Spikes crash the downstream. A sale sends 10,000 orders/s but the database handles 2,000/s. A queue absorbs the spike and consumers drain it at 2,000/s. The queue smooths the load.
Failures spread. If the email service is down for 10 minutes, a direct call fails the user's checkout. With a queue the messages simply wait and are sent when the service recovers. This is decoupling: producer and consumer need not be alive, fast or even written in the same language at the same time.
The price is eventual completion: the user gets the result later, not instantly, and you now run another piece of infrastructure.
How does it work?
Producers, brokers, partitions and consumer groups
A single machine cannot store or serve all messages for a large system, so a topic is split into partitions (the same sharding idea as the partitioning lesson). Each partition is an ordered, append-only log on one broker, and is replicated to other brokers for safety.
The producer picks a partition by hashing a partition key, for example order_id. All messages with the same key land in the same partition, so they stay in order for that key. Ordering is guaranteed only within a partition, never across the whole topic.
Each partition is read by at most one consumer within a group. So the number of partitions is the maximum parallelism: 12 partitions can feed up to 12 active consumers in one group.
Consumers track their position, the offset, saying "I have processed up to message 1,057 in this partition". After a crash they resume from the last saved offset.
Producer, Topic Partitions and Consumer GroupArchitecture
Key point. Partitions cap parallelism: three partitions can keep at most three consumers in one group busy.
The partition key decides the partition. Within a group, each partition has exactly one consumer.
Delivery semantics: how many times will a message be processed?
Networks fail. If a consumer processes a message and crashes before telling the broker, the broker cannot know and must decide what to do.
At-most-once: the offset is saved before processing. A crash loses the message; it is never repeated. Acceptable for lossy data such as metrics.
At-least-once: the offset is saved after processing. A crash causes the message to be delivered again, so duplicates are possible. This is the default in most systems.
Exactly-once: each message affects the result exactly once. Truly achieving it across systems is very hard; practical systems get effectively exactly-once by combining at-least-once delivery with idempotent consumers (processing the same message twice changes nothing the second time; see the retries and idempotency lesson). In an interview say: "at-least-once plus idempotent consumers".
Acknowledgements, retries and the dead letter queue
A consumer acknowledges (acks) a message after finishing it. If no ack arrives within a visibility timeout (say 30 seconds), the broker makes the message available again. If processing keeps failing, for example because the message is malformed, it would loop forever, blocking healthy work. The fix is a dead letter queue (DLQ): after N failed attempts (commonly 3 to 5), the broker moves the message to a separate queue for humans or a repair job to inspect. Alert on DLQ depth.
Failure, Redelivery and the Dead Letter QueueRequest flow
BrokerConsumerDead letterqueue1deliver msg 7 (attempt 1)2crash or error: no ack3redeliver after 30 sattempts 2, 3, 4 repeat4ack msg 8healthy messages continue5msg 7 failed 5 times: movealert, inspect, fix, replay
A message that keeps failing is parked after N attempts so it cannot block the rest.
Backpressure and lag
If producers outpace consumers, the queue grows. Consumer lag (messages waiting, or time since the oldest waiting message) is the number to monitor. Options when lag rises:
Scale out consumers, up to the partition count.
Backpressure: tell producers to slow down, for example by rejecting with HTTP 429 or blocking when the queue hits a size limit. Better a controlled "try later" than unbounded growth and memory exhaustion.
Shed or delay low-priority work, using separate queues per priority.
Worked sizing:
text
Peak incoming: 10,000 messages/s
One consumer: 500 messages/s
Consumers needed: 10,000 / 500 = 20 (plus 30% headroom = 26)
Partitions: at least 26 -> choose 32
Spike of 60 s at 10,000/s while consumers handle 6,000/s:
backlog = (10,000 - 6,000) x 60 = 240,000 messages
drain time after the spike at 4,000/s spare = 60 s
Queue versus log
Classic queues (SQS, RabbitMQ) delete a message once acked. Log-based brokers (Kafka) retain messages for days regardless of consumption, so a new consumer can replay history from the start, which is valuable for rebuilding state and for analytics. Pick a queue for simple task distribution; pick a log when many independent consumers or replay matter.
Classic Queue versus Log-Based BrokerComparison
Classic queue
SQS, RabbitMQ
1
Producer enqueues message
2
One consumer receives it
hidden from others
3
Consumer acks
message is deleted
Simple task distribution
Per-message retry and DLQ
No replay
One logical consumer of each message
Background jobs and work queues
Log-based broker
Kafka, Kinesis
1
Producer appends to a partition
2
Each group tracks its offset
reads independently
3
Messages kept for N days
replay by resetting offset
Many independent consumer groups
Replay and reprocessing
Very high throughput
Ordering only within a partition
More to operate
Event streams, analytics, many subscribers
What happens to a message after a consumer reads it.
Interview tip. Do not say "Kafka guarantees exactly-once" and stop. Say what is delivered (at-least-once) and what you do about duplicates (idempotent consumers or dedupe by message ID). Also mention ordering: "per key, not global", and choose the partition key on purpose.
Real-world example
When you place an order on a shopping site, the checkout API writes the order and publishes an order_placed event, then returns "Order confirmed" in 150 ms. Separate consumer groups handle email receipts, inventory updates, fraud checks and analytics. If the email service is down for an hour, receipts queue up and go out later, and the shopper never noticed.
System design example
A notification system must send 50 million push notifications in 10 minutes after a flash sale starts.
text
50,000,000 / 600 s = about 83,000 notifications/s
One sender worker = about 1,000/s (limited by the push provider)
Workers needed = 83 -> run about 100
Design: the campaign service publishes one message per user to a notifications topic with 128 partitions, keyed by user ID (so one user's messages stay ordered). A group of about 100 workers consumes and calls the push provider. Failures retry with backoff and, after 5 attempts, go to a DLQ. The producer is not blocked, a worker crash causes a replay from the last offset (so the send step uses a dedupe key), and the dashboards show consumer lag as the finish-time estimate.
Interview discussion. "I'll decouple the upload from the heavy work with a queue. The API returns immediately; workers in a consumer group process messages at their own speed. I'd partition by user ID to keep per-user order, use at-least-once delivery with idempotent consumers, a dead letter queue after 5 attempts, and alert on consumer lag."
Trade-off thinking. A queue buys resilience and smoothing, and costs latency (results arrive later), complexity (another system to run and monitor) and harder debugging (flow is no longer a single call stack). Use synchronous calls when the user needs the answer now, such as checking a password. Use a queue when work can finish later.
Key interview takeaway
Use a queue to take slow or spiky work off the request path. Know partitions (parallelism and per-key ordering), consumer groups, at-least-once plus idempotency, DLQs and lag-based scaling. Always say what happens when a consumer crashes and when the queue backs up.
Real World Example
Checkout writes the order, publishes an order_placed event and returns in 150 ms. Email, inventory, fraud and analytics each consume the event in their own consumer group. If email is down for an hour, receipts wait in the queue and nothing user-facing breaks.