Skip to content

Lesson 9 of 38Building blocks

Message Queues

Move slow work off the request path with queues, pub/sub, and logs, and handle leases, retries, dead letters, ordering, and backlogs.

25 min read0/8 questions

When a user uploads a video, they should not stare at a spinner while you transcode it into six resolutions. When an order is placed, the email, the warehouse, and the analytics pipeline should not all have to succeed before the user sees "thanks". Message queues let one part of a system hand work to another and move on. They are how real backends stay fast under load and keep working when a downstream service is having a bad day.

Sync vs async processing

In synchronous processing, the request waits for every step: the API resizes the image, sends the email, updates search, and only then responds. The user waits for the slowest step, and if any step fails, the whole request fails.

In asynchronous processing, the API does the minimum (validate, save, enqueue a job) and responds 202 Accepted right away. Workers pick jobs off a queue and do the slow part in the background, at their own pace.

Async gives you:

  • Fast responses: the user waits for a database write, not a 30-second transcode.
  • Decoupling: the producer does not know or care which service consumes the message, or whether it is up right now.
  • Load levelling: a spike of 10,000 uploads queues up and drains steadily, instead of crushing the workers.
  • Retries: a failed job goes back on the queue instead of failing the user's request.

Step through a job queue with workers, including a crash and a poison message.

A job queue with workers and a dead letter queue
ClientClientAPIAPIJob queue: SQSJob queueSQSWorker 1Worker 1Worker 2Worker 2Dead letter queueDead letter queueuploadenqueuereceivereceiveafter 5 fails

The API saves the upload, puts a resize image 812 message on the queue, and returns 202 Accepted in about 50 ms.

1/6
Quick check
Signup takes 4 seconds because the API sends a welcome email through a slow provider before responding. What is the best change?
Need a nudge? A hint rules out a wrong answer.

Queues, pub/sub, and logs

Three shapes of messaging cover nearly everything.

A queue (point to point): each message is processed by one consumer. Workers compete for jobs. Use it for tasks: resize this image, send this email.

Pub/sub (publish/subscribe): a producer publishes an event to a topic, and every subscriber gets its own copy. Use it for fan-out: "order placed" goes to email, inventory, and analytics, and none of them know about each other.

A log (stream): messages are appended to a durable, ordered log and kept for days or forever. Consumers track their own position (offset) and can replay from any point. Several independent consumer groups read the same log. Use it for event streams, analytics pipelines, and change data capture.

Fan-out with pub/sub
Order serviceOrder serviceorder.placed: topicorder.placedtopicEmail serviceEmail serviceInventoryInventoryAnalyticsAnalyticspublish

The order service publishes one event: {orderId: 77, items: [...]}. It does not know who is listening.

1/3
ToolShapeOrderingRetentionTypical use
Amazon SQSQueueNone (standard) or per group (FIFO)Up to 14 days, deleted on ackBackground jobs on AWS
RabbitMQQueues + exchanges (both queue and pub/sub)Per queueUntil consumedTask routing, RPC-style work
Amazon SNS / Google Pub/SubPub/subOptional, by keyShort; pushes to subscribersFan-out notifications
Apache KafkaPartitioned logPer partitionDays to forever; replayableEvent streams, analytics, CDC, millions of msgs/sec

A common AWS pattern combines them: SNS topic fans out to one SQS queue per consumer, so each consumer gets durable, retryable delivery.

Match the pairs0/4 matched

Match each need to the right shape.

Choose an item, then its match on the other side.

Delivery guarantees and idempotent consumers

Every messaging system offers one of these:

  • At-most-once: a message is delivered zero or one times. Ack before processing; a crash loses it. Rarely what you want.
  • At-least-once: delivered one or more times. Ack after processing; a crash or lost ack means it is redelivered. This is the default for SQS, RabbitMQ, and Kafka consumers.
  • Exactly-once: very hard end to end across systems. In practice you get effectively-once by combining at-least-once delivery with idempotent consumers.

An idempotent consumer can safely process the same message twice. The usual trick: each message has a unique id, and the consumer records processed ids in the same database transaction as its work, skipping any id it has seen.

Pythonconsumer.py
from collections import deque queue = deque([ {"id": "m1", "user": "ada", "points": 10}, {"id": "m2", "user": "sam", "points": 5}, {"id": "m1", "user": "ada", "points": 10}, # redelivered: the first ack was lost {"id": "m3", "user": "ada", "points": 7},]) points = {"ada": 0, "sam": 0}processed_ids = set() # in production: a DB table with a unique constraint while queue: msg = queue.popleft() if msg["id"] in processed_ids: print(f"skip {msg['id']} (duplicate)") continue points[msg["user"]] += msg["points"] processed_ids.add(msg["id"]) print(f"apply {msg['id']} -> {points}") print("final:", points)
Output
Press Run (⌘ Enter) to see what happens.

Delete the if block and run it again: Ada ends up with 27 points instead of 17.

Quick check
A worker charges a card, then crashes before acknowledging the message. With at-least-once delivery, what happens next, and what must the worker do?
Need a nudge? A hint rules out a wrong answer.

Visibility timeout: when the work outlives the lease

The first diagram showed SQS hiding a received message for a visibility timeout. That timeout is a lease: "this message is yours for 30 seconds" (the SQS default; it can be set from 0 seconds up to 12 hours). The queue does not know whether your worker is alive, busy, or dead. It only knows the lease expired without a delete, so it makes the message visible again.

That is exactly right when a worker crashes. It is a nasty bug when the worker is simply slow. Say a CSV export takes 70 seconds and the timeout is 30. At second 30 the message reappears, a second worker picks it up and starts the same export. At second 60 a third does. Now three workers are doing the same job, the customer may get three emails, and when the first worker finally calls delete, the others carry on. Under load this compounds: slow jobs cause duplicates, duplicates cause more load, more load makes jobs slower.

Pythonvisibility.py
VISIBILITY_TIMEOUT = 30 # seconds a received message stays hiddenJOB_SECONDS = 70 # how long the export really takesHEARTBEAT_EVERY = None # try 20: the worker extends visibility every 20 s visible_at = 0 # the message is visible right awaystarted = [] # (worker, start time) for every receive for t in range(JOB_SECONDS + 1): if t >= visible_at: worker = f"worker-{len(started) + 1}" started.append((worker, t)) visible_at = t + VISIBILITY_TIMEOUT print(f"t={t:>2}s {worker} receives the message") first, first_start = started[0] if HEARTBEAT_EVERY and t > first_start and (t - first_start) % HEARTBEAT_EVERY == 0: visible_at = t + VISIBILITY_TIMEOUT # ChangeMessageVisibility print(f"t={t:>2}s {first} extends visibility to t={visible_at}s") if t == first_start + JOB_SECONDS: print(f"t={t:>2}s {first} finishes and deletes the message") print(f"the export ran {len(started)} times")
Output
Press Run (⌘ Enter) to see what happens.

Set HEARTBEAT_EVERY = 20 and run it again: one worker, one export. Three ways to handle long jobs, in the order teams usually reach for them:

  1. Set the timeout from real data. Look at the p99 processing time, not the average, and add margin. For SQS triggering AWS Lambda, AWS recommends a visibility timeout of at least six times the function timeout, because Lambda retries and batching stretch the real time a message is held.
  2. Heartbeat. For jobs with unpredictable length, the worker calls ChangeMessageVisibility every so often to extend its lease while it is still making progress. If the worker dies, the heartbeats stop and the message comes back as intended. Other brokers have the same idea under other names: RabbitMQ holds an unacked message until the consumer's channel closes (with a configurable delivery acknowledgement timeout), and Kafka consumers must keep calling poll() within max.poll.interval.ms or the group rebalances their partitions away.
  3. Split the job. A 2-hour video transcode should not be one message. Break it into chunks, or have the message start a workflow whose state lives in a database or an orchestrator (Step Functions, Temporal) instead of in a lease.

Even with all three, assume a message can be processed twice. That is why the idempotent consumer from earlier is not optional.

Quick check
A worker takes about 90 seconds per message. The queue's visibility timeout is 60 seconds. Customers report getting their invoice PDF emailed twice. What is going on?
Need a nudge? A hint rules out a wrong answer.

Dead letter queues and poison messages

A poison message is one that can never succeed: malformed JSON, a reference to a deleted user, a payload that triggers a bug. Without protection it fails, reappears after the visibility timeout, fails again, forever. It burns worker time, fills your logs, and with FIFO queues it blocks every message behind it.

A dead letter queue (DLQ) is a normal queue that receives messages after too many failed attempts. In SQS you attach a redrive policy to the source queue with a maxReceiveCount. Each receive increments the message's receive count; once it passes the limit, SQS moves the message to the DLQ instead of making it visible again. RabbitMQ does the same with dead letter exchanges, and its quorum queues enforce a delivery limit (RabbitMQ 4.0 set a default of 20). Kafka has no built-in DLQ for consumers; teams publish failures to a separate retry or dead letter topic themselves (Kafka Connect has a built-in setting for this).

Getting the details right:

  • Pick the limit on purpose. Too low (1 or 2) and a brief outage in a dependency sends healthy messages to the DLQ. Too high and poison messages waste minutes of work each. Three to five is common for jobs that call other services.
  • Separate transient from permanent errors. A timeout calling the email provider is transient: let it retry, ideally with backoff. A validation error will fail every time: send it to the DLQ (or log and delete) on the first attempt instead of retrying five times.
  • Alert on DLQ depth. A DLQ nobody watches is a silent data loss bucket. Alert when its message count is above zero, or rising, and include the error that caused it.
  • Mind retention. For SQS standard queues, a message's age in the DLQ is counted from when it was first sent to the source queue, so set the DLQ's retention period longer than the source queue's, or messages can expire before anyone looks.
  • Redrive after the fix. Once you have fixed the bug, move the messages back to the source queue (SQS supports DLQ redrive from the console and API). Redriving before the fix just puts them back in the DLQ.
Predict the outputPython

A queue has maxReceiveCount = 4. A message fails every time it is processed. How many times does the handler run before the message lands in the DLQ?

max_receive_count = 4
runs = 0
receive_count = 0
while True:
  receive_count += 1
  if receive_count > max_receive_count:
      break          # moved to the DLQ instead of delivered
  runs += 1          # handler runs and fails
print(runs)
Need a nudge? Hints walk you through it.

Backpressure and backlogs

A queue absorbs spikes, but it cannot fix a system where work arrives faster than it is processed on average. The backlog then grows forever and every job waits longer. Backpressure is any way of pushing back on producers: bounded queues that reject new work, rate limits on the API, or slowing producers down.

The everyday answer is to autoscale workers on queue depth (or on the age of the oldest message), and alert when the backlog keeps rising.

Pythonbacklog.py
ARRIVALS_PER_SEC = 1_200 # jobs added to the queueJOB_SECONDS = 0.5 # each job takes a worker half a second def simulate(workers, minutes=10): capacity = workers / JOB_SECONDS # jobs per second the fleet can finish backlog = max(0, ARRIVALS_PER_SEC - capacity) * minutes * 60 wait = backlog / capacity if capacity else float("inf") print(f"{workers:>4} workers capacity {capacity:>5,.0f}/s backlog after {minutes} min {backlog:>8,.0f} newest job waits {wait:>5,.0f}s") for workers in [400, 550, 600, 700]: simulate(workers)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

Messages arrive at 120 per second and consumers finish 100 per second. How many messages are waiting after one minute?

print((120 - 100) * 60)
Need a nudge? Hints walk you through it.

Ordering

Ordering is expensive, so most queues do not guarantee it. SQS standard queues can deliver out of order; with several workers, even an ordered queue's messages finish out of order.

When order matters (a bank account's deposits and withdrawals, a chat's messages), you need order per key, not globally. Kafka keeps order within a partition, and you choose the partition by key (account_id), so all events for one account stay in order while different accounts process in parallel. SQS FIFO queues do the same with a message group id.

Put it in order4 steps

Put a safe at-least-once consumer's steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

SQS standard vs FIFO, and how they compare to RabbitMQ and Kafka

SQS comes in two types, and the choice is made when you create the queue (you cannot convert one to the other).

A standard queue gives you at-least-once delivery, best-effort ordering, and practically unlimited throughput. Occasionally a message is delivered twice even without a crash, because SQS stores copies on several servers and one may miss the delete. Design for it.

A FIFO queue adds two things:

  • Ordering per message group. Every message carries a MessageGroupId. Messages in the same group are delivered strictly in order, and only one batch per group is in flight at a time. Different groups run in parallel. Use the entity the order matters for: account_id, order_id, conversation_id.
  • Deduplication. A MessageDeduplicationId (or content-based dedupe, which hashes the body) makes SQS drop a repeat send with the same id within a 5-minute window. This protects you from a producer that retries a send after a timeout. It does not make your consumer exactly-once: if a worker processes a message and crashes before deleting it, the message is delivered again. Consumers still need to be idempotent.

The price of FIFO is throughput and head-of-line blocking. FIFO queues have per-queue limits on API calls per second (raised a lot by batching and by the high throughput mode; check the current quotas in the SQS docs for your region). And because a group is strictly ordered, one message that keeps failing blocks its whole group until it succeeds or reaches the DLQ. If all your messages share one group id, your FIFO queue is single-threaded. Pick a group key with many distinct values.

SQS standardSQS FIFORabbitMQ (quorum queues)Kafka
ModelQueue, consumers pollQueue, consumers pollBroker pushes to consumers (with a prefetch limit)Partitioned log, consumers pull
OrderingBest effortStrict per MessageGroupIdPer queue, for a single consumerStrict per partition
DuplicatesPossible, rareProducer dedupe in a 5-minute windowRedelivery on failureRedelivery after a rebalance or crash
After ackDeletedDeletedDeletedKept until retention expires; replayable
ParallelismUnlimited consumersOne in-flight batch per groupMany consumers per queueMax one consumer per partition per group (share groups, production-ready in Kafka 4.2, relax this)
Retries and DLQRedrive policy built inRedrive policy built inDead letter exchanges, delivery limitBuild it: retry and dead letter topics
DelaysUp to 15 minutesQueue-level onlyVia a plugin or TTL tricksNot built in
Run itFully managedFully managedYou (or a hosted service)You, or a managed service (MSK, Confluent)

A rough rule: on AWS, start with SQS standard for jobs, use FIFO only when order per entity truly matters, reach for RabbitMQ when you need rich routing between many queues, and use Kafka when you need high-volume streams, replay, or many independent consumers of the same events.

Match the pairs0/4 matched

Match each requirement to the best fit.

Choose an item, then its match on the other side.

Delayed, scheduled, and priority messages

Delays. Some work should happen later: retry a failed webhook in 5 minutes, send a reminder 10 minutes after an abandoned cart. SQS supports a delay of up to 15 minutes, either for the whole queue or per message (per-message timers work on standard queues only). The message is invisible until the delay passes. RabbitMQ needs a plugin or a TTL plus dead letter exchange trick, and Kafka has nothing built in.

Scheduling. For anything longer than a few minutes ("send the trial-ending email in 13 days"), do not hold a message in a queue. Store the job in your database with a run_at column and have a small scheduler poll for due rows (WHERE run_at <= now() ... FOR UPDATE SKIP LOCKED in Postgres lets several schedulers share the table safely), then enqueue them. A managed scheduler such as EventBridge Scheduler is the alternative on AWS. The database row is also where you cancel or reschedule, which a message already sitting in a queue cannot do.

Priority. Password reset emails should not wait behind 2 million marketing emails. RabbitMQ supports priority queues natively (quorum queues gained message priority in 4.0). SQS and Kafka do not, so the standard design is separate queues per priority with dedicated or weighted consumers. Watch for starvation: if workers always drain the high queue first, the low queue never moves when high traffic is steady.

Pythonpriority.py
from collections import deque def run(name, pick, seconds=60): high, low = deque(), deque() served = {"high": 0, "low": 0} oldest_low_wait = 0 for t in range(seconds): for _ in range(10): high.append(t) # 10 password-reset emails arrive per second for _ in range(2): low.append(t) # 2 weekly-digest emails arrive per second for slot in range(10): # workers send 10 emails per second in total q = pick(slot, high, low) if q is None: break q.popleft() served["high" if q is high else "low"] += 1 if low: oldest_low_wait = t - low[0] print(f"{name:<16} high sent {served['high']:>3} low sent {served['low']:>3} oldest digest waiting {oldest_low_wait}s") def strict(slot, high, low): return high if high else (low if low else None) def weighted(slot, high, low): first, second = (low, high) if slot % 5 == 4 else (high, low) # every 5th slot tries low first return first if first else (second if second else None) run("strict priority", strict)run("weighted 4:1", weighted)
Output
Press Run (⌘ Enter) to see what happens.

Strict priority sends zero digests in a minute. Weighted polling keeps both moving. Notice what neither strategy fixes: 12 emails arrive per second and only 10 go out, so something falls behind either way. Priority decides who waits. Only more capacity or less work fixes an overload, which is the backpressure point from earlier.

Key terms
message queue
A buffer where producers put messages and one of many consumers takes each one.
pub/sub
Producers publish to a topic and every subscriber gets its own copy. Used for fan-out.
log / stream
A durable, ordered, replayable sequence of messages, like Kafka. Consumers track their own offset.
at-least-once delivery
Messages may be redelivered after a crash or lost ack, so consumers must be idempotent.
dead letter queue
Where messages go after failing too many times, so they stop blocking the main queue.
backpressure
Pushing back on producers (rejecting, rate limiting, slowing) when consumers cannot keep up.
visibility timeout
How long a received SQS message stays hidden from other consumers. If it expires before a delete, the message is delivered again.
poison message
A message that fails every time it is processed, so it must be moved aside instead of retried forever.
message group id
The SQS FIFO key that defines an ordered stream. Messages in one group are in order; different groups run in parallel.
redrive
Moving messages from a dead letter queue back to the source queue once the bug is fixed.