SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Message Queues
  • Pub/Sub
  • Message Brokers
  • Delivery Semantics
  • Dead Letter Queues
  • Kafka Deep Dive
  • Retries with Backoff
  • RabbitMQ and SQS
  • Event Streaming vs Message Queues
  • Message Ordering
  • Task Queues, Workers and Scheduled Jobs
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Asynchronous Communication

Message Queues

A line of tasks waiting for a worker, so users do not have to wait.

⏱ 13 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A message queue is a line of jobs. One part of the system (the producer) puts a message in the line. Another part (the consumer) takes it out later and does the work.

  • The user does not wait for slow work like sending an email or making a video thumbnail.
  • If there is a big rush, the line gets longer and workers catch up later. Nothing crashes.
  • Producer and consumer do not need to be online at the same moment.
  • Remember: a queue turns “do it now and wait” into “do it soon, and I will not wait”.

02Concept: What is it?

A message queue stores messages until a consumer is ready to process them. It works like a line at a ticket counter: the first message in is usually the first message out (FIFO).

The basic idea
📤Producercreates messages
→↓send
📬Queueholds messages
→↓receive
👷Consumerdoes the work
The producer drops a message and moves on. A worker picks it up when it is free.

Sync vs async

Synchronous
Do it now. Wait for it.
  • The user waits until the slow work ends
  • If the email service is down, the order fails too
  • A rush of users makes everyone slow
Asynchronous (queue)
Do it soon. Do not wait.
  • The user gets “Order placed” at once
  • If the email service is down, jobs wait in the queue
  • A rush only makes the line longer

Main parts

📤Producer
Creates a message and sends it to the queue.
📬Queue
Stores messages safely until someone takes them.
👷Consumer
Takes a message, does the work, then says “done” (ack).

03Real-Life Example

🍵The Tea Stall Token
At a busy tea stall, you pay and get a token number. You do not stand next to the stove. The cook makes teas in token order. You are free to sit down, and you are called when your tea is ready.
Tea stall
Message queue
Customer paying
Producer
Token slip
Message
Line of tokens
Queue
Cook making tea
Consumer / worker
Calling your number
Ack (job done)
Hiring a second cook at rush hour
Adding more consumers
Online shop: order placed
🛍️Userclicks Buy
→↓1. order
🖥️Web serversaves order
→↓2. job
📬Queue
→↓3. later
📧Email worker
🧾Invoice worker
The slow parts happen in the background, after the user already sees “Order placed”.

04Why Do We Need It?

⚡Fast replies
The user does not wait for slow background work.
🌊Handles spikes
A sale rush fills the line. Workers drain it at their own speed.
🛡️Survives failures
If a worker is down, messages wait safely and are not lost.
🔌Loose coupling
Producer and consumer do not need to know each other.
📈Easy scaling
Slow? Add more consumers. No change to the producer.
🧯Protects the database
The queue smooths traffic so the database is not hit all at once.
A queue lets the fast part of the system and the slow part of the system work at different speeds.

05Where Do We Use It?

📧Emails and SMS
Order confirmations, OTPs, reminders.
🖼️Media processing
Resize photos, convert videos after upload.
💳Payment follow-ups
Receipts, refunds, fraud checks.
📊Reports and exports
Make a big CSV file in the background.
🔔Notifications
Send push alerts to millions of phones.
🔄Data sync
Update search index or cache after a database change.
💡Good rule
Use a queue when the work is slow, can fail, or the user does not need the result right now.

06Types / Parts / How It Works

A message’s journey

  1. 1
    Producer sends
    The message is stored safely in the queue.
  2. 2
    Consumer receives
    The message becomes invisible to other consumers (visibility timeout).
  3. 3
    Consumer works
    Sends the email, makes the thumbnail, and so on.
  4. 4
    Consumer acks
    “Done!” The queue deletes the message.
  5. !
    If no ack comes
    After the timeout, the message becomes visible again and another worker tries.

Competing consumers

Many workers read from the same queue. Each message goes to one worker. This shares the work.

📤Producer
→↓
📬Queuem1 m2 m3 m4 m5 m6
→↓
👷W1m1, m4
👷W2m2, m5
👷W3m3, m6
Three workers compete for messages. More workers means the line empties faster.

Queue behaviours to know

TopicSimple meaning
Ack / nackAck = “done, delete it”. Nack = “I failed, try again or send elsewhere”.
Visibility timeoutWhile one worker holds a message, others cannot see it. If the worker dies, the message comes back after this time.
OrderingMany queues are roughly first-in-first-out. With many consumers, the finish order can still differ.
BackpressureWhen the queue grows too long, slow down producers or add consumers.
DurabilityMessages are saved to disk (often copied to other machines), so a restart does not lose them.
RetentionHow long unread messages are kept before the queue deletes them.
VisualizerOrders, a queue and workersSwitch between sync and async, move the sliders, then press Play. Try “Sale rush”.
How does the shop send the order email?
👥3 orders/scustomers
→↓place order
🖥️Web serverreplies at once
→↓email job
Queue of email jobs
empty
→↓
Email workers
👷W1
👷W2
Clock
0s
Jobs in queue
0
peak 0
Emails sent
0
of 0 orders
User waits
0.1 s
for 'Order placed'
Email arrives in
~1 s
user is not waiting
Orders arrive at 3/s but workers finish only 2/s, so the line grows by 1 every second. The user still sees 'Order placed' at once, but the emails get later and later. Add workers.

07How to Use It / Steps / Implementation

Adding a queue to a feature

  1. 1
    Find slow or failure-prone work
    Email, image resize, calling a partner API.
  2. 2
    Keep the user path short
    Save the order, put a job in the queue, reply “OK”.
  3. 3
    Write the message
    Keep it small: an id and what to do, not a huge file. Put big data in storage and send the link.
  4. 4
    Write a consumer
    Take a message, do the work, then ack. Make it safe to run twice (idempotent).
  5. 5
    Handle failures
    Retry with backoff. After a few tries, send it to a dead letter queue.
  6. 6
    Watch the queue
    Alarm on queue depth and on the age of the oldest message.
  7. 7
    Scale consumers
    If the line keeps growing, add workers (auto-scale on queue depth).
💡Outbox pattern (short idea)
Saving to the database and sending to the queue are two steps. If the app crashes between them, one is lost. Fix: write the message into an outbox table in the same database transaction, and let a small relay job copy it to the queue.

Common tools

☁️Amazon SQS
A managed queue in the cloud.
🐇RabbitMQ
A popular broker with flexible routing.
🔴Redis lists / streams
Simple, fast queues, often used for background jobs.

08Key Terms to Know

TermMeaning in easy words
ProducerThe part that creates and sends messages
Consumer / workerThe part that receives messages and does the work
QueueA line that stores messages in order
MessageA small piece of data that describes a job or an event
AckA reply from the consumer saying the job is done
NackA reply saying the job failed
Visibility timeoutHow long a received message is hidden from other consumers
FIFOFirst in, first out
Queue depthHow many messages are waiting
BackpressureSlowing down producers when consumers cannot keep up
Competing consumersMany workers sharing one queue
IdempotentSafe to run more than once with the same result

09Pros, Cons and Trade-offs

✅ Pros
  • Fast responses for users
  • Absorbs traffic spikes
  • Producer and consumer fail and scale on their own
  • Easy to add more workers
  • Work is not lost if a worker crashes
⚠️ Cons
  • Result is not instant (eventual)
  • More parts to run and watch
  • Messages can be delivered twice, so consumers must be idempotent
  • Harder to debug a flow across services
  • A very long queue means long delays

Trade-offs

ChoiceWe gainWe lose
Async instead of syncSpeed for the user, resilienceNo instant result, more complexity
Strict orderingPredictable orderLess parallel work, lower throughput
Many consumersMore throughputOrder can change, more care needed
Long retentionSafe if consumers are down for longMore storage cost

10Common Problems and Mistakes

Common mistakes

  1. Not making consumers idempotent. A retry then sends two emails or charges twice.
  2. Forgetting to ack (or acking before the work is done). Jobs repeat forever or get lost.
  3. Visibility timeout too short. A slow job is given to a second worker while the first is still working.
  4. No dead letter queue. One bad message blocks or loops forever.
  5. Huge messages. Send an id or a link, not a 50 MB file.
  6. Not watching queue depth. You only find out when users complain.
  7. Using a queue when you need an answer now. If the user must see the result at once, use a normal call.

Problems to expect

🐌Slow consumers
The line grows and delays pile up.
☠️Poison messages
One message always fails and keeps coming back.
🔀Out-of-order work
Two workers finish in a different order than they started.
👯Duplicates
A message is processed twice after a retry.

11Real-World Examples

🛒E-commerce
Order placed fast. Email, invoice and stock update happen in the background.
🎬Video platforms
After you upload, a queue feeds workers that convert the video into many sizes.
🚕Ride apps
Trip events (started, ended, paid) flow through queues to billing and receipts.
💬Chat and alerts
Push notifications are queued and sent in batches.
📝Note
These show the general idea. Each company designs its own details.
Mini case: photo upload
📱User uploads
→↓
🗂️Storagesaves original
→↓job
📬Queue
→↓
Worker pool
🖼️thumb
🖼️medium
🖼️large
User Queue Workers
The user sees “Uploaded” at once. Thumbnails appear a few seconds later.

12Related Topics to Read Next

Pub/Sub→

Instead of one consumer per message, every subscriber gets a copy.

Message Brokers→

The software that runs queues and topics (RabbitMQ, Kafka, SQS).

Delivery Semantics→

At most once, at least once and exactly once.

Dead Letter Queues→

Where messages go when they keep failing.

Idempotency→

Makes retries safe.

Scalability→

Queues help systems handle spikes and grow.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a line of messages between a producer and a consumer.
  • ✔Why: fast user replies, spike handling, failure isolation, easy scaling.
  • ✔Flow: send, receive, work, ack. No ack means it comes back after the visibility timeout.
  • ✔Scale: add consumers (competing consumers).
  • ✔Be safe: make consumers idempotent, add retries with backoff and a dead letter queue.
  • ✔Watch: queue depth and age of the oldest message.
  • ✔Do not use when the user needs the answer right now.
  • ✔One line: “A queue lets the fast part of the system and the slow part work at their own speeds.”
← Previous
MQTT
Next →
Pub/Sub