Message Queues and Async Processing

Use queues to move slow or unreliable work off the request path, smooth out spikes and decouple producers from consumers.

Intermediate · about 3 hours · difficulty 2/5

Learn first: Load Balancing

Not every piece of work must finish before you reply to the user. Sending an email, generating an invoice PDF or transcoding a video can happen asynchronously. A message queue sits between the code that creates work (producer) and the code that does it (consumer).

Why queues help

  • Faster responses: the API enqueues a job and returns "accepted" in milliseconds.
  • Load levelling: a Big Billion Days spike fills the queue; workers drain it at a steady rate instead of the database melting.
  • Decoupling: producers do not need to know who consumes or whether consumers are up right now.
  • Retries: failed jobs go back on the queue or to a dead letter queue.

Core concepts

  • Point-to-point queue: each message is processed by one consumer (a work queue).
  • Publish/subscribe: each message goes to every subscriber (order placed: notify user, update analytics, alert restaurant).
  • Acknowledgements: a consumer acks after finishing; unacked messages are redelivered after a visibility timeout.
  • Dead letter queue (DLQ): messages that keep failing are parked for inspection instead of blocking the queue.
  • Backpressure: if consumers fall behind, queue depth grows. Monitor it and autoscale workers.

Typical tools

RabbitMQ, Amazon SQS, Google Pub/Sub, Redis lists or streams for light use, and Kafka when you need a durable log (next topics).

Pitfalls

  • Using a queue for work the user must see succeed immediately, and then building fake "is it done yet?" flows.
  • No DLQ, so one poison message retries forever.
  • Ignoring queue depth until it is hours behind.

You are ready to move on when you can redraw a synchronous checkout flow so that only payment confirmation is synchronous and explain what happens when the email worker is down for an hour.

Key concepts

  • Producers, consumers and brokers
  • Point-to-point vs pub/sub
  • Acks and visibility timeout
  • Dead letter queues
  • Load levelling
  • Backpressure and queue depth
  • Delayed and scheduled jobs

Mini project

Build a signup API that enqueues a welcome-email job to a queue (Redis, RabbitMQ or SQS). Add retries with backoff and a DLQ, then kill the worker for five minutes and show that no emails are lost.

Check yourself

A consumer crashes after sending an email but before acking the message. What happens next, and what does that imply about your consumer code?

Free resources