Why message queues

Topic 5 of 9 in Week 4: Caching, queues and content delivery9 min readBeginnerFree course

Overview

So far, components have talked to each other directly: a request comes in, the server calls the database or another service and waits. Some work doesn’t need to happen while the user waits, and some services can’t keep up with bursts. A message queue sits between them and holds work until it can be done. It’s one of the most useful tools in system design.

How a queue works

A message queue between services. Producers such as a web app, a mobile API and a partner API add messages to a queue. Workers 1 to 3 take messages when they are ready. Decoupling: producers don’t wait for, or even know about, consumers. Buffering: a spike becomes a longer queue instead of an outage, and workers drain it at their own pace. Scaling: add workers when the queue grows; a failed worker’s message is retried by another.

  • A producer sends a message, such as {"type": "resize_image", "image_id": 981}.
  • The queue (or broker) stores it durably.
  • A consumer (worker) receives it, does the work and acknowledges it. Only then is the message removed.
  • If a consumer crashes before acknowledging, the message becomes visible again and another consumer retries it.

Popular choices: Amazon SQS, RabbitMQ, Google Cloud Pub/Sub, Azure Service Bus, Kafka (a log, covered next lesson) and Redis-based queues for simple cases.

Why use one

1. Faster responses

Move slow work out of the request path. Sign-up can return immediately while a worker sends the welcome email, resizes the profile photo and updates analytics.

2. Absorb spikes

Traffic arrives in bursts: a flash sale, a push notification, an end-of-month batch. Without a queue, the downstream service must handle the peak or fail. With a queue, the spike becomes a temporarily longer queue that workers drain at a steady pace. This is called load levelling.

3. Decoupling

The producer doesn’t need to know which service handles the message, how many workers there are or whether they’re up right now. If the email service is down for ten minutes, messages wait and are processed when it returns; checkout keeps working.

4. Independent scaling

Scale workers by queue length: more workers when the queue grows, fewer when it’s empty. CPU-heavy work (video encoding) can run on different machines from the web servers.

5. Reliability through retries

A failed task isn’t lost; it’s retried, and repeatedly failing tasks go to a dead-letter queue for inspection (a later lesson).

What you give up

  • Immediacy: work happens “soon”, not now. The user may see “processing” for a while.
  • Complexity: another system to run, monitor and secure.
  • Duplicates: most queues deliver at least once, so the same message can be processed twice. Consumers must be idempotent.
  • Ordering: many queues don’t guarantee order, or only within a partition or group.
  • Debugging: a request now spans several asynchronous steps; you need tracing and correlation IDs.

Sync or async?

A useful rule: keep the steps that decide whether the operation succeeded synchronous, and queue the side effects. For an order, reserving stock and charging the card decide success; emails, analytics and recommendations are side effects.

If the user needs the result of slow work, use the async request pattern: return 202 Accepted with a job ID, process via a queue, and let the client poll a status endpoint or receive a notification when it’s done.

What to monitor

  • Queue depth: how many messages are waiting.
  • Age of the oldest message: how far behind consumers are. Often more useful than depth.
  • Processing rate and error rate of consumers.
  • Dead-letter queue size.

Alert when the oldest message is older than the business can tolerate (“emails more than 10 minutes late”).

In an interview

Use a queue whenever you see slow work, bursty traffic or fan-out to several services: “Uploads put a message on a queue; transcoding workers pick it up and autoscale on queue depth. The upload API returns immediately with a processing status.” Then mention idempotent consumers and a dead-letter queue.

Recap

A message queue holds work between producers and consumers, letting them run at different speeds and fail independently. It makes responses faster, smooths spikes, decouples services and allows independent scaling. In exchange, work completes later and consumers must handle retries, duplicates and ordering. Keep success-deciding steps synchronous and queue the side effects.

Exercise

What should be asynchronous?

When a user places an order on an e-commerce site, the system: (1) checks stock and reserves items, (2) charges the card, (3) saves the order, (4) sends a confirmation email, (5) updates the recommendation model, (6) notifies the warehouse, (7) updates sales dashboards. Which steps must finish before the user sees 'Order placed', and which should go through a queue? Explain the reasoning and one risk of the asynchronous part.

Text
Synchronous (before responding):

Asynchronous (via a queue):

Risk:

Summary

  • A message queue stores messages from producers until consumers process them, so the two don't have to be available or fast at the same time.
  • Queues decouple services, absorb traffic spikes, move slow work out of the request path and let you scale consumers independently.
  • The trade-off is eventual completion: work happens later, and you must handle retries, duplicates, ordering and monitoring.
  • Keep the steps that decide success synchronous; queue the side effects.
  • Watch queue depth and the age of the oldest message: they tell you when consumers are falling behind.