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.
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.
The API saves the upload, puts a resize image 812 message on the queue, and returns 202 Accepted in about 50 ms.
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.
The order service publishes one event: {orderId: 77, items: [...]}. It does not know who is listening.
| Tool | Shape | Ordering | Retention | Typical use |
|---|---|---|---|---|
| Amazon SQS | Queue | None (standard) or per group (FIFO) | Up to 14 days, deleted on ack | Background jobs on AWS |
| RabbitMQ | Queues + exchanges (both queue and pub/sub) | Per queue | Until consumed | Task routing, RPC-style work |
| Amazon SNS / Google Pub/Sub | Pub/sub | Optional, by key | Short; pushes to subscribers | Fan-out notifications |
| Apache Kafka | Partitioned log | Per partition | Days to forever; replayable | Event 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 each need to the right shape.
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.
Press Run (⌘ Enter) to see what happens.Delete the if block and run it again: Ada ends up with 27 points instead of 17.
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.
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:
- 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.
- Heartbeat. For jobs with unpredictable length, the worker calls
ChangeMessageVisibilityevery 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 callingpoll()withinmax.poll.interval.msor the group rebalances their partitions away. - 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.
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.
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)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.
Press Run (⌘ Enter) to see what happens.Messages arrive at 120 per second and consumers finish 100 per second. How many messages are waiting after one minute?
print((120 - 100) * 60)
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 a safe at-least-once consumer's steps in order.
- Tap the steps below in the right order.
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 standard | SQS FIFO | RabbitMQ (quorum queues) | Kafka | |
|---|---|---|---|---|
| Model | Queue, consumers poll | Queue, consumers poll | Broker pushes to consumers (with a prefetch limit) | Partitioned log, consumers pull |
| Ordering | Best effort | Strict per MessageGroupId | Per queue, for a single consumer | Strict per partition |
| Duplicates | Possible, rare | Producer dedupe in a 5-minute window | Redelivery on failure | Redelivery after a rebalance or crash |
| After ack | Deleted | Deleted | Deleted | Kept until retention expires; replayable |
| Parallelism | Unlimited consumers | One in-flight batch per group | Many consumers per queue | Max one consumer per partition per group (share groups, production-ready in Kafka 4.2, relax this) |
| Retries and DLQ | Redrive policy built in | Redrive policy built in | Dead letter exchanges, delivery limit | Build it: retry and dead letter topics |
| Delays | Up to 15 minutes | Queue-level only | Via a plugin or TTL tricks | Not built in |
| Run it | Fully managed | Fully managed | You (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 each requirement to the best fit.
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.
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.
- 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.