Message Queues and Asynchronous Processing

Decouple services with queues and event streams, learn delivery guarantees, idempotency, retries and dead-letter queues, and when to use Kafka vs a task queue.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Scaling Databases: Replication, Partitioning and Sharding

Not every piece of work should happen inside the user's request. Message queues let one service hand work to another asynchronously, smoothing traffic spikes and isolating failures.

When to go async

  • Slow or non-urgent work: sending emails, generating thumbnails, processing payments webhooks, updating search indexes.
  • Traffic spikes: the queue absorbs bursts while consumers work at a steady rate (load levelling).
  • Fan-out: one event (order placed) triggers many independent actions (email, analytics, inventory).

Models

  • Point-to-point task queues (RabbitMQ, SQS, Celery, BullMQ): each message is processed by one worker.
  • Publish-subscribe / event streams (Kafka, Pub/Sub, SNS): many consumer groups each read every event. Kafka keeps an ordered, replayable log split into partitions; ordering is guaranteed only within a partition.

Delivery guarantees

  • At most once: may lose messages.
  • At least once: may deliver duplicates (the common default).
  • Exactly once: very hard end to end; in practice you combine at-least-once delivery with idempotent consumers (processing the same message twice has the same effect, for example by storing processed message IDs).

Operating queues

  • Retries with exponential backoff and jitter.
  • Dead-letter queues for messages that keep failing, so they do not block others.
  • Backpressure and monitoring consumer lag.
  • The outbox pattern to reliably publish an event when a DB transaction commits.

Pitfalls

Assuming global ordering, making consumers non-idempotent, and adding queues where a simple synchronous call would do.

Good enough to move on: you can place a queue in a design, justify it, and explain how you make a payment consumer safe against duplicate messages.

Key concepts

  • Sync vs async communication
  • Task queues vs pub-sub
  • Kafka topics, partitions and consumer groups
  • Delivery guarantees
  • Idempotent consumers
  • Retries, backoff and dead-letter queues
  • Outbox pattern

Mini project

Build an image upload service where the API stores the file and enqueues a job, and a separate worker (using Redis-backed BullMQ, Celery or RabbitMQ) generates thumbnails with retries, a dead-letter queue and idempotency by job ID. Kill the worker mid-job and verify nothing is lost or duplicated.

Check yourself

Why is at-least-once delivery combined with idempotent consumers the usual practical answer to exactly-once processing?

Free resources