Skip to content

Asynchronous Processing and Message Queues

Basic 27 min read Part 8 of 18

Why and how to do work asynchronously: producers, consumers, acks, visibility timeouts, retries, dead-letter queues, back pressure, ordering and queue tools.

Summary#

A message queue lets one part of a system (the producer) hand off work to another (the consumer) without waiting for it to finish. The producer puts a message on the queue and returns; consumers take messages, do the work and acknowledge them. This makes requests faster, smooths traffic spikes, and keeps work safe when consumers crash. Unacknowledged messages reappear after a visibility timeout, failed messages are retried and finally moved to a dead-letter queue. Queues provide back pressure by buffering, can be FIFO for ordering, and come in point-to-point, priority and delay flavours. Common tools: Amazon SQS, RabbitMQ, and task frameworks such as Celery and Sidekiq.

Why It Exists#

Some work is slow or unreliable: sending email, resizing images, calling a partner API. Done synchronously inside a web request, the user waits seconds and a slow dependency slows your whole service. Behind a queue, the request finishes in milliseconds and workers process at their own pace. This page builds on Scaling Up vs Scaling Out: queues are how you scale workers out independently.

How It Works#

Sync vs async#

Synchronous: the caller waits for the result; simple, but a slow or failed callee hurts the caller. Asynchronous: the caller hands off the work and continues; the result arrives later, and caller and worker are decoupled in time and failure. Use sync when the user needs the answer to continue (checking a password), async when work can finish later (the welcome email).

Sync vs async, in depth#

Why synchronous chains get slow and fragile. When service A calls B, which calls C, every caller waits for the slowest link, and the latencies add up. Availability multiplies: if each of five services in a synchronous chain is up 99.9% of the time, the chain as a whole is up about 0.999^5, or 99.5%, which is roughly 44 hours of failure a year instead of 9. A queue breaks the chain. The producer only needs the queue to be up, and the consumer can be down for an hour while messages wait. This is called temporal decoupling: the two sides do not have to be running at the same time.

The long-request problem. Consider generating a yearly activity report as a PDF. It queries millions of rows, renders charts and takes 45 seconds. Done inside the request, the browser waits with no feedback. Worse, load balancers and gateways usually cut requests off after 30 to 60 seconds, so the work may be thrown away just before it finishes, and the user retries, doubling the load. Video transcoding (minutes), image resizing into several thumbnail sizes, sending a newsletter to 100,000 users and importing a large CSV file are the same shape. All of them should be split into two phases:

  1. Accept: validate the request, store any input (for example in object storage), enqueue a job and return 202 Accepted with a job ID, all in tens of milliseconds.
  2. Process: a worker takes the job, does the slow work and records the result and status in a database.

The client then polls GET /jobs/{id}, holds a WebSocket or Server-Sent Events connection open, or receives a webhook or push notification when the job finishes.

Make it feel instant. Async work can still look synchronous to the user. When someone posts a message on a social network, the post appears on their own timeline at once, while delivery to followers' feeds happens in the background over seconds. The client shows the result optimistically and corrects it only if the background work fails. This trick is common for likes, comments and uploads.

Do work before anyone asks. Async is not only for user requests. Expensive aggregates, such as daily revenue per merchant or trending topics, can be computed periodically by scheduled jobs, so reads only fetch a ready answer.

Request-reply over a queue. Sometimes a caller does want an answer but still benefits from a queue's buffering, for example a pricing engine shared by many services. The caller sends a message with a correlation ID and a reply-to queue name, and the responder sends the answer to that queue with the same correlation ID. This keeps load levelling but adds latency and complexity, so use it only when the buffering matters. For simple calls, plain RPC with timeouts and retries is better.

A decision test. Ask three questions. Does the user need the result to take their next step? Must the work finish within the request's latency budget, typically under a second? Must the caller know right away whether it failed? If all three answers are "no", the work belongs behind a queue.

Producer and consumer#

  1. The producer sends a small message ({"type":"resize","image_id":123}); the broker stores it durably.
  2. A consumer receives it. Each message goes to one consumer, so more consumers means more throughput.
  3. The consumer does the work and acknowledges; the broker deletes it.

Keep messages small and put large files in object storage, sending a reference.

Producers, consumers and brokers, in depth#

Anatomy of a good message. A message is a small, self-describing record. A practical envelope includes:

  • a unique message_id, used for deduplication;
  • a type and a schema_version, so consumers can handle old and new formats during a rollout;
  • the payload, usually IDs plus the minimum data needed, not whole database rows;
  • created_at, so consumers can measure lag and drop expired work;
  • a trace_id, so distributed tracing can link the consumer's work to the original request;
  • optionally an idempotency_key derived from the business operation, such as invoice:991:send.

Claim check for large payloads. Brokers limit message size. SQS, for example, has historically capped messages at 256 KB, and large messages slow every broker down. The claim-check pattern stores the large payload in object storage and sends only its key, like a coat-check ticket. The consumer fetches the payload by key. Set a lifecycle rule to delete the payload after the message's retention period.

Competing consumers. Many identical workers reading one queue is called the competing consumers pattern. Each message goes to one worker, so throughput scales roughly linearly with workers until a shared dependency, often the database, saturates. Workers should be stateless, so any of them can take any message and the fleet can scale up and down freely.

Prefetch and fairness. A RabbitMQ consumer sets a prefetch count (basic.qos), the number of unacknowledged messages the broker may push to it at once. With unlimited prefetch, one fast-connecting worker can grab thousands of messages while the others sit idle, and those messages wait behind its slow ones. A prefetch of 1 gives the fairest spread but costs a round trip per message. Values between 10 and 100 usually balance throughput and fairness. SQS consumers pull instead: each receive call returns up to 10 messages.

Durability on the broker. A message is only as safe as the broker's storage:

  • SQS stores each message redundantly across several servers and availability zones before the send call returns.
  • RabbitMQ keeps messages durable only if the queue is declared durable and the message is published as persistent. Quorum queues, added in RabbitMQ 3.8, replicate each queue across nodes with the Raft consensus algorithm and are the recommended choice when losing messages is unacceptable. Older classic mirrored queues are deprecated.
  • Publisher confirms in RabbitMQ make the broker acknowledge each publish once it is safely stored. Without them, a producer cannot know if a message was lost in flight.
  • Redis used as a simple broker (lists, or pub/sub) is fast but can lose messages on a crash or failover. Pub/sub delivers only to subscribers connected at that moment.

Reliable producing. The producer has its own failure window. If it writes an order to the database and then crashes before publishing "order created", the event is lost. If it publishes first and the database write fails, consumers act on an order that does not exist. The transactional outbox solves this: write the message into an outbox table in the same database transaction as the business change, then let a relay or CDC process publish it. See Change Data Capture and the Outbox Pattern.

Message queue vs task queue#

  • A message queue (SQS, RabbitMQ) moves generic messages between services; the consumer decides what to do.
  • A task queue (Celery for Python, Sidekiq for Ruby, BullMQ for Node.js) is a framework on top of a broker (Redis or RabbitMQ) that sends function calls: "run send_email(user_id=42) later", with built-in retries, scheduling and result storage.

Task queues suit one codebase; message queues suit services in different languages.

Task queues and long-running jobs, in depth#

How a task framework is put together. Celery is a good model of the whole category. Application code calls send_report.delay(user_id=42), which serialises the function name and arguments into a message on a broker (RabbitMQ or Redis). Worker processes import the same code, pull messages and run the function. A result backend (Redis or a database) can store return values and states such as PENDING, STARTED, SUCCESS and FAILURE. A scheduler process (celery beat) enqueues periodic tasks, like cron. Sidekiq (Ruby) keeps jobs in Redis and runs many jobs concurrently in threads inside one process. Failed jobs are retried with exponential backoff, by default up to 25 times over about three weeks, before landing in a "dead" set. BullMQ offers similar features for Node.js on Redis.

Two framework defaults that surprise people.

  • Celery acknowledges a task when a worker receives it, before running it, unless task_acks_late is enabled. With the default, a worker crash loses the task. With late acks, the task is redelivered, so it must be idempotent.
  • With a Redis broker, Celery's visibility timeout defaults to one hour. A task that is scheduled further ahead, or runs longer, can be redelivered to a second worker while the first is still working on it.

The long-running task pattern, end to end.

The jobs table is the source of truth for status. Insert the job row before enqueueing, or use the outbox, so a status query never finds a missing job. Store progress (percentage or step name) so the client can show more than a spinner. A worker that runs for a long time should heartbeat: extend the message's visibility timeout every few seconds and update last_heartbeat_at, so a reaper can spot jobs whose worker died.

Orchestrating job dependencies. Real jobs are often a chain or a graph. A video upload is split into segments, the segments are transcoded in parallel, and the results are joined and published. Three ways to build that:

  1. Chained messages: each step enqueues the next when it finishes. Simple, but the overall state is scattered across queues, and a join ("wait for all 40 segments") needs a counter in a database.
  2. Framework primitives: Celery's canvas offers chains, groups (parallel) and chords (a group followed by a callback when all finish).
  3. A workflow engine: Temporal, AWS Step Functions or Airflow hold the graph and its state centrally.

How a durable workflow engine works (Temporal as the example). You write the orchestration as ordinary-looking code, the workflow, and every call to the outside world (charge a card, call a shipping API) as an activity. The engine records each activity's result in a durable event history. If a worker crashes, another worker re-runs the workflow code from the start, and the engine returns the recorded results instead of repeating finished activities. This is called replay. Replay only works if the workflow makes the same decisions every time, so workflow code must be deterministic: it reads time, random numbers and external data only through the engine's APIs or through activities. Durable timers let a workflow "sleep" for five days without a process running, because the engine stores the timer's deadline and wakes the workflow when it fires. Signals deliver outside events, such as a carrier webhook saying "delivered", into a waiting workflow. Under the hood, Temporal's History service owns workflow state across fixed shards and writes state changes together with internal tasks, an outbox, so a crash cannot separate them. A Matching service hands tasks to workers through named task queues, so payment activities, CPU-heavy activities and GPU activities can run on separate worker fleets. Workers poll for work, so you need worker capacity only for work that is ready to run, not for millions of workflows that are waiting.

Queue or workflow engine? A single independent job, such as sending an email, resizing an image or one notification, needs only a queue and a worker. Reach for a workflow engine when you find yourself building a state machine by hand: persisting which step finished, scheduling the next one, retrying, waiting for external events and recovering half-done work. Activities can still run more than once, so side effects must remain idempotent. A workflow engine is not a replacement for an event streaming platform for high-volume continuous streams. In an interview, check whether durable orchestration is the very thing being tested before you place it in one box.

Acknowledgements and visibility timeout#

What if a consumer crashes halfway? The message must not be lost.

  • In SQS, a received message is hidden for the visibility timeout (30 s default, up to 12 hours). If the consumer does not delete it in time, it becomes visible again for another consumer.
  • In RabbitMQ, a consumer acks after processing; if its connection drops first, the broker redelivers.

Set the timeout above normal processing time. Because a message can be delivered twice (crash after the work, before the ack), consumers must be idempotent: processing it twice must not charge a card twice. See Delivery Semantics.

Acknowledgements and visibility, in depth#

The moment of acknowledgement decides the guarantee. Acknowledge before doing the work, and a crash loses the message: at-most-once. Acknowledge after the work, and a crash between the work and the ack repeats it: at-least-once. Almost every system chooses at-least-once and makes consumers idempotent, because a lost order is worse than a duplicate that is detected and skipped.

SQS mechanics. ReceiveMessage returns up to 10 messages, each with a receipt handle that identifies this particular delivery. The message stays in the queue but is invisible until the visibility timeout ends. DeleteMessage with the receipt handle removes it. ChangeMessageVisibility extends the timeout, which is how a long job heartbeats: every 30 seconds, extend by 60. Every receive increments the message's receive count, which drives the dead-letter rule. A standard queue allows roughly 120,000 in-flight messages and a FIFO queue 20,000, so a fleet that receives far more than it processes can hit that ceiling. Messages are retained for 4 days by default, up to 14.

RabbitMQ mechanics. Consumers use manual acknowledgements: basic.ack after success, basic.nack or basic.reject with requeue=true to put a message back, or requeue=false to send it to a dead-letter exchange. There is no fixed visibility timeout. A message is redelivered when the consumer's channel or connection closes without acking, and it is marked with a redelivered flag. Recent RabbitMQ versions also enforce a consumer timeout (30 minutes by default), after which a channel holding an unacked message is closed, so a stuck consumer cannot hold messages forever.

Redis-based queues. A plain LPUSH and BRPOP list loses a message if the worker crashes after popping it. The reliable pattern moves the message atomically into a per-worker processing list (LMOVE or the older BRPOPLPUSH), removes it after success, and has a reaper return stale entries to the main list. Redis Streams build this in: consumer groups track a pending entries list per consumer, XACK confirms, and XAUTOCLAIM lets another consumer take messages that have been pending too long.

Choosing the timeout. Set the visibility timeout to several times the p99 processing time, not the average, or heartbeat for long jobs. Too short, and a second worker starts the same job while the first is still running, which doubles the load during an incident, exactly when the system can least afford it. Too long, and a crashed worker's messages sit invisible for the whole period before anyone retries them.

Retries and dead-letter queues#

Work fails: a dependency is down, data is bad, there is a bug.

  • Retry transient failures with exponential backoff (1 s, 2 s, 4 s...), often via delayed redelivery.
  • After a maximum number of attempts (say 5), move it to a dead-letter queue (DLQ), so a poison message that always fails does not block workers forever.
  • Alert on DLQ size, fix the bug, and redrive messages back.
# SQS: redrive policy on the main queue (illustrative)
RedrivePolicy:
  deadLetterTargetArn: arn:aws:sqs:us-east-1:123456789012:resize-dlq
  maxReceiveCount: 5        # after 5 failed receives, move to the DLQ
VisibilityTimeout: 120      # seconds; longer than the slowest normal job
MessageRetentionPeriod: 1209600   # 14 days, the SQS maximum

Retries and dead-letter queues, in depth#

Classify the failure before retrying.

Failure classExamplesRight response
TransientTimeout, 503 from a partner, deadlock, throttlingRetry with backoff and jitter
PermanentValidation error, 404 for a deleted entity, schema mismatchDo not retry. Record the error, then ack or dead-letter
PoisonMessage that crashes the worker every time (bad encoding, a bug)Dead-letter after a few attempts, alert
SystemicDatabase down for all messagesPause consumption or trip a breaker, instead of burning retries

Retrying a permanent error wastes capacity and delays everything behind it. A systemic failure that every message hits will march the whole queue into the DLQ unless consumers stop pulling. Use a circuit breaker on the dependency, or scale consumers to zero, until it recovers. See Resilience Patterns.

Backoff with jitter. With pure exponential backoff, the delay before retry n is base x 2^n, capped at a maximum. If 10,000 messages failed in the same second, they all retry in the same second again. Full jitter picks a random delay between zero and that value, which spreads the retries out evenly. A typical schedule for a partner API: base 1 s, cap 5 minutes, at most 8 attempts, so the last attempt happens within about 10 minutes of the first.

Where the retry delay lives.

  • SQS: either leave the message invisible (ChangeMessageVisibility to the backoff delay) or delete it and re-send it with DelaySeconds, up to 15 minutes, carrying an attempt counter.
  • RabbitMQ: nack to a "retry" queue with a per-message TTL whose dead-letter exchange points back to the main queue, or use the delayed-message plugin.
  • Kafka: you cannot leave one message invisible in a partition, so teams use retry topics (orders.retry.1m, orders.retry.10m) and a final DLQ topic. This keeps the main partition moving.

Note that retrying in place, with an immediate nack and requeue, loops the same message at full speed. That is the worst option.

Running a DLQ well. A dead-letter queue is a holding area, not a trash can. Keep the original message and add the failure reason, the stack trace, the attempt count and the original queue. Alert on DLQ depth above zero for critical queues, and on the rate of messages arriving there. After fixing the cause, redrive the messages: SQS has a built-in redrive that moves messages back to the source queue. Redrive at a controlled rate, because 50,000 messages released at once are a load spike. Retain DLQ messages longer than the main queue, since investigations take days.

Preventing duplicate work. At-least-once delivery, retries and redrives all mean the same message can be processed more than once. Defences, from simplest to strongest:

  1. Naturally idempotent operations: "set status to SHIPPED" can repeat safely, while "add 1 to count" cannot.
  2. A dedupe table: insert message_id into a table with a unique constraint in the same transaction as the work, and if the insert fails, skip the message.
  3. Idempotency keys toward external systems: payment providers such as Stripe accept a key per request and return the original result for repeats.
  4. A job lock or lease for expensive jobs, so a duplicate delivery waits or exits while the first copy runs. Treat it as an efficiency measure and keep the database checks for correctness.

See Idempotency and Safe Retries for the full set of techniques.

Partial batch failures. Consumers that take 10 messages at once must not fail the whole batch for one bad message. AWS Lambda's SQS integration, for example, lets a function report only the failed message IDs, so the others are deleted. Without that, one poison message makes nine good ones repeat.

Back pressure#

Back pressure is how a system copes when producers outpace consumers. A queue absorbs bursts: 10,000 orders per minute against 2,000 processed means the queue grows and drains later. But queues are not infinite:

  • Watch queue depth and oldest message age.
  • Autoscale consumers on depth (Kubernetes KEDA, SQS metrics).
  • Limit producers when the backlog is too large (HTTP 429/503, drop low-value work).

Back pressure, in depth#

A queue buffers rate mismatches. It does not fix them. If producers send 10,000 jobs a minute for 10 minutes and workers finish 2,000 a minute, the backlog grows by 8,000 a minute to 80,000. Once the burst ends, draining it at 2,000 a minute takes 40 minutes. That is fine for a newsletter and unacceptable for password-reset emails. If the arrival rate stays above the service rate, the backlog grows without limit, and eventually storage fills, retention deletes messages, or the work is so late it is useless.

Little's law sets the latency. Time in queue equals backlog divided by throughput. 80,000 messages at 2,000 per minute means a new message waits 40 minutes. Turn the product's freshness target into an alert: if emails must go out within 2 minutes and workers do 2,000 a minute, page someone when the backlog exceeds 4,000, or better, when the age of the oldest message exceeds 2 minutes. Age is the metric users feel, and depth is its cause.

Big queues get slower, not just longer. Many brokers are fastest when the queue fits in memory. When it grows beyond that, messages are paged to disk, reads become disk reads and throughput drops just when you need it most. RabbitMQ, for example, raises a memory alarm and blocks publishers when memory crosses a threshold. A healthy design keeps queues short in steady state and treats a long queue as an incident.

Tools, from gentle to drastic.

  1. Autoscale consumers on backlog per worker or on message age, for example with KEDA on Kubernetes or target tracking on SQS metrics. Set a ceiling based on what the downstream can take, or the autoscaler moves the bottleneck from the queue to the database.
  2. Bound the queue: a maximum length or size, after which producers get an error. A rejected request tells the client to retry later with backoff, which is more honest than accepting work that will finish hours late. HTTP 503 or 429 with a Retry-After header is the usual signal.
  3. Shed by priority: drop or defer analytics events, recommendation refreshes and other low-value work first, and keep payments and password resets.
  4. Producer-side rate limits: a token bucket per tenant stops one customer's bulk import from filling the queue. See Rate Limiting.

Consumer-side back pressure protects the downstream. Consumers should pull only as fast as the thing they write to can absorb. Limit concurrency per worker (prefetch, thread pools) and in total (number of workers). If the partner API allows 100 requests per second, 50 workers each making 5 calls per second will be throttled, no matter how long the queue is.

Handling mixed workloads. If 10-second thumbnail jobs and 20-minute transcodes share one queue and one worker pool, a burst of transcodes occupies every worker and thumbnails wait behind them. This is head-of-line blocking. Split work by expected duration and by importance into separate queues, each with its own worker pool and scaling rule. Within a shared queue, per-tenant fairness (round-robin across tenant sub-queues, or weighted fair queueing) stops one big customer from starving the rest.

Autoscaling workers on a queue#

Scale on backlog per worker, not on CPU. CPU says how busy current workers are, not how far behind the queue is. A worker waiting on a slow partner API shows 5% CPU while the backlog grows. The usual rule is acceptable backlog per worker: if a job takes 2 seconds and the latency target is 60 seconds, each worker can have about 30 jobs waiting ahead of it. With 9,000 messages visible, you need 9,000 / 30 = 300 workers. The autoscaler computes visible messages / current workers and adds or removes workers to keep that ratio near 30.

Avoid flapping. Scale out fast and scale in slowly. Add capacity after one or two minutes above target, but remove it only after ten minutes below, so a sawtooth traffic pattern does not start and stop machines every minute. Keep a minimum fleet that can handle a typical burst while new workers boot, since cold starts take seconds for containers and minutes for virtual machines. Scale-to-zero is fine for rare batch queues, and wrong for queues with a latency promise.

Shut down gracefully. When a worker is removed, it should stop receiving, finish or release its in-flight messages (by setting their visibility to zero) and then exit. Otherwise every scale-in event leaves messages invisible until their timeouts expire, adding minutes of delay right after a burst.

FIFO ordering#

Most queues give best-effort ordering; many consumers and retries reorder messages. When order matters:

  • SQS FIFO queues keep strict order within a message group ID (say, per user), with deduplication, at lower throughput limits than standard queues.
  • RabbitMQ keeps order per queue, but multiple consumers and redeliveries break it.
  • For high-throughput ordering, use a partitioned log such as Kafka. See Pub/Sub and Event Streaming.

FIFO ordering, in depth#

Why order breaks even in a "queue". A queue may hand out messages in order, but three things reorder them before the work is done. Parallel consumers: message 1 goes to a slow worker and message 2 to a fast one, so 2 finishes first. Retries: message 1 fails, is redelivered a minute later, and lands after messages 2 to 50. Producer retries: a producer that times out and resends can put a copy after later messages. Strict global order therefore means one consumer handling one message at a time, which caps throughput at one worker's speed.

Order per key is what you usually need. Most systems need order per entity, not across all messages. "Account 42's debits in order" says nothing about account 43. SQS FIFO queues deliver messages with the same message group ID in order, one at a time per group, while different groups proceed in parallel. They also remove duplicates sent within a 5-minute deduplication window, using a deduplication ID or a hash of the body. Throughput is lower than standard queues: 300 operations per second per API action without batching, and 3,000 messages per second with batches of 10, with a high-throughput mode that raises the limits substantially. Kafka gives the same per-key property through partitions, and Azure Service Bus through sessions.

The cost of per-key order: a blocked key blocks its group. If one message in group account:42 keeps failing, every later message for account 42 waits behind it. That is correct, since processing a later debit before an earlier one could be wrong, but it means a poison message stalls one customer. Set a maximum number of receives so the message moves to the DLQ and the group continues. Then decide whether the rest of that group's messages are still valid without it.

Make order matter less. Ordering guarantees are expensive, and the cheapest fix is often to design consumers that tolerate disorder:

  • Version or timestamp checks: each message carries the entity's version, and the consumer applies an update only if its version is newer than the stored one: UPDATE ... WHERE id = 42 AND version < 17. Late, older messages become harmless no-ops.
  • Commutative operations: increments, set unions and "max" can be applied in any order and give the same result.
  • State instead of deltas: send "the order's status is SHIPPED", the full new state, rather than "advance one step".
  • Resequencing: if a consumer must apply in order, buffer messages by sequence number and release them when the gap fills, with a timeout for gaps that never fill.

Queue types#

TypeBehaviourExample use
Point-to-point (work queue)Each message to exactly one consumerImage resizing, emails, order processing
Priority queueHigher-priority messages delivered firstPaid users' jobs before free users'
Delay queueMessage becomes visible after a delayRetry in 5 minutes; send reminder in 24 hours
FIFO queueStrict order (per group)Per-account event processing

RabbitMQ supports priority queues natively; with SQS, use one queue per priority. SQS delays go up to 15 minutes; longer needs a scheduler.

Queue types and tools, in depth#

Point-to-point versus fan-out. In a work queue, each message is consumed once. Fan-out, where every interested service gets its own copy, is publish/subscribe. A common AWS pattern combines the two: an SNS topic fans out to several SQS queues, one per consuming service, so each service gets its own buffer, retries and DLQ. RabbitMQ builds both from exchanges that route to queues. A direct exchange routes by exact routing key, a topic exchange by wildcard patterns such as order.*.eu, a fanout exchange to every bound queue, and a headers exchange by message headers. See Pub/Sub and Event Streaming.

Priority queues and starvation. A strict priority queue always serves the highest priority first, so a steady flow of high-priority work can starve low-priority work forever. Remedies: weighted polling (take 8 from high, then 2 from low), aging (raise a message's priority the longer it waits) or a separate worker pool per priority with its own capacity. RabbitMQ supports a small number of priority levels per queue natively. Its documentation recommends few levels, because each level costs resources. SQS has no priorities, so you create one queue per level and have workers poll the high queue more often.

Delay and scheduled delivery. SQS supports delays up to 15 minutes, per queue or per message. RabbitMQ uses a per-message TTL plus a dead-letter exchange, which republishes the message when it expires, or the delayed-message plugin. For hours or days ahead ("send a reminder 24 hours before the event"), store the job in a durable table or a Redis sorted set scored by due time, and have a scheduler move due jobs onto the work queue every second. That scheduler must handle its own failover and must not enqueue a job twice. Workflow engines offer durable timers for the same need.

The main tools and their fit.

ToolModelStrengthsWatch out for
Amazon SQSManaged queue, pullNear-unlimited standard throughput, no servers, DLQ and redrive built inAt-least-once with occasional duplicates, tens of ms latency, FIFO limits
RabbitMQBroker using AMQP, pushRich routing, priorities, low latency, quorum queuesYou run the cluster, and clients must understand AMQP concepts
Redis lists or StreamsIn-memoryVery low latency, simple, already in many stacksMemory-bound, can lose messages on failover
Celery, Sidekiq, BullMQTask framework on a brokerRetries, scheduling and results for one codebaseTied to one language, framework defaults matter
Azure Service BusManaged brokerSessions for ordering, DLQ, scheduled messages, transactionsAzure only
Google Cloud TasksManaged task dispatchRate-limited HTTP task delivery to servicesPush to HTTP targets only
ActiveMQ, IBM MQJMS brokersLong enterprise history, transactionsHeavier operations, older protocols

Use SQS when you are on AWS and want the least operational work. RabbitMQ fits when you need routing patterns, priorities or sub-millisecond latency and can run a cluster. A task framework fits when the producer and the worker are the same application. When many independent consumers each need the full stream, or you need replay, an event log such as Kafka is the right tool, not a queue.

When a queue is the wrong answer#

  • The caller needs the result to continue. Login, checkout price, an availability check. Putting a queue in the middle only adds latency and a second failure mode.
  • The work is cheap. A 5 ms calculation done inline costs less than serialising it, sending it to a broker, receiving it and writing the result somewhere for the user to fetch.
  • Real-time interaction. A chat message or a game move must reach the other side in tens of milliseconds. Use a direct real-time channel, even if a log stores the messages too.
  • The steps must succeed or fail together. Moving money between two accounts in one database belongs in one transaction. Splitting it across a queue turns a simple ACID operation into a distributed saga with compensations.
  • Volume is tiny and latency tolerance is huge. A nightly job that processes 200 rows can read a database table directly. A queue would be one more system to monitor.
  • You actually need a log. If consumers must re-read history, join late, or many teams need the same events, use an event stream.

What async costs, even when it is right. Debugging spans several processes, so you need trace IDs carried in messages. Results are eventually consistent, so the UI must handle "processing". Every consumer must be idempotent, and every queue needs depth, age and DLQ alerts. When you propose a queue in an interview, name these costs and how you handle them. That is what separates a reasoned choice from a reflex.

Worked example: a video upload pipeline#

Requirements. 2 million uploads a day, peaking at 3 times the average. Each upload needs a virus scan (5 s), thumbnails (10 s) and transcoding into four resolutions (about 4 minutes of CPU per resolution). Thumbnails should appear within a minute, and the video should be playable within 15 minutes.

Rates. 2,000,000 / 86,400 is about 23 uploads per second on average and about 70 at peak. The API stores the file directly in object storage with a presigned URL, inserts a job row and publishes {video_id}, so the request finishes in under 100 ms.

Queues. Separate queues keep fast work away from slow work:

  • scan and thumbnail share a fast pool. At peak, 70 per second x 15 s is 1,050 concurrent jobs. With 8 jobs per worker, that is about 130 workers.
  • transcode gets one message per resolution, so 280 messages per second at peak. Each takes 240 s, so about 67,000 concurrent jobs, which is exactly why transcoding is split into segments and run on a large autoscaled fleet, often on cheaper spot instances.

Reliability settings. Visibility timeout of 10 minutes for transcodes, with heartbeats every minute. Five attempts, then the DLQ. Workers are idempotent by video_id plus resolution: an output file that already exists means skip. A job row records each step's status, so the client polls one place and support can see where any video is stuck.

Back pressure. If the transcode backlog's oldest message exceeds 10 minutes, the autoscaler adds workers up to the account's instance limit. Beyond that, free-tier uploads get only the 720p rendition first and the rest later, while paid uploads keep all four. That is priority shedding, written down before the incident instead of during it.

Operating queues in production#

The dashboard for every queue. Five numbers per queue tell you almost everything. Depth (visible messages) shows the backlog. Age of the oldest message shows the delay users feel. In-flight count shows work being processed, and a high value with low throughput means stuck workers. DLQ depth and inflow show failures. Consumer error rate and processing time show whether workers are healthy. Put the freshness target on the age graph, so the on-call engineer can see at a glance whether the queue is inside its promise.

Trace across the gap. A request that becomes a message and then a job crosses process boundaries, and logs alone will not join them. Put the trace ID in the message attributes, start a child span when the consumer picks the message up, and record the queue wait time as its own span. Then "why did this email take 20 minutes" has an answer: 19 minutes waiting in the queue and 1 minute sending.

Evolve message schemas safely. Producers and consumers deploy separately, so for a while old consumers see new messages and new consumers see old ones. Only add optional fields, never rename or repurpose a field, and carry a schema_version. Deploy consumers that understand the new version before producers start sending it. A schema registry with compatibility checks, common with Avro or Protobuf on Kafka, enforces this automatically.

Cost is per request, so batch. Managed queues charge per API call. SQS standard queues, for example, cost on the order of 40 cents per million requests. Each send, receive and delete counts, and each 64 KB chunk of a payload counts as one request. Sending, receiving and deleting in batches of 10 cuts the request count by up to ten times. Long polling stops idle consumers from paying for thousands of empty receives. At 1,000 messages per second, unbatched traffic is about 260 million requests a month per operation type, so batching is worth the small extra code.

Rehearse the bad days. Kill a worker in the middle of a job and confirm the message comes back. Push a poison message and confirm it reaches the DLQ without stopping its neighbours. Pause consumers for an hour and measure how long the backlog takes to drain. Each of these turns a 3 a.m. surprise into a known number.

Telling the user the job is done#

Polling is the simplest option: the client calls GET /jobs/{id} every few seconds. It works through every proxy and needs no extra infrastructure, but most calls return "still running". Back the poll interval off (2 s, then 5 s, then 15 s) and serve status from a cache or a cheap primary-key read. Server-Sent Events or WebSockets push the update the moment it happens. That suits interactive pages, but needs a connection layer that can find the right connection when a worker finishes, usually through a pub/sub channel keyed by user or job. Webhooks suit server-to-server APIs. The caller registers a URL, and your system sends a signed HTTP request on completion. A webhook sender is itself a queue consumer: it retries with backoff for hours or days, signs each request (for example an HMAC of the body with a shared secret plus a timestamp, to stop replays), and lets the receiver deduplicate by event ID. Push notifications and email cover the case where the user has left the page.

Whatever the channel, the jobs table stays the source of truth. A lost notification is repaired by the next poll or page load. A notification is only a hint to look.

Queues inside well-known designs#

Payments meet asynchronous networks. Card networks and payment providers do not always answer within the request. A charge can come back "pending" and settle minutes later, and bank transfers take days. A safe payment flow therefore treats the external world as asynchronous. It records the payment as PENDING in its own database, then calls the provider with an idempotency key derived from the payment ID, so a retried call cannot charge twice. It learns the final outcome from the provider's webhook, which arrives on a queue and is processed idempotently by event ID. A scheduled reconciliation job compares the provider's settlement reports with the internal ledger every day and flags any mismatch. Each step's state change and its outgoing message are written together through an outbox. The queue makes the flow resilient, but correctness comes from the state machine, idempotency and reconciliation around it. See Distributed Transactions.

Notification fan-out. One event, say "your order shipped", becomes messages to several channels: push, email and SMS. Each channel gets its own queue and worker pool, because providers have different rate limits and failure modes. An outage at the SMS provider then fills only the SMS queue, and email keeps flowing. Per-user preferences and deduplication run before the fan-out. Priority queues let password resets overtake marketing campaigns.

Web crawler frontier. A crawler's frontier is a set of queues, typically one per host, so that politeness (at most one request per second to any single site) is enforced by when a host's queue may next be served. A priority layer in front decides which URLs matter most. Fetch results go onto further queues for parsing and indexing, with back pressure stopping fetchers when parsers fall behind.

Order processing at a flash sale. Accepting 100,000 orders in a minute into a queue protects the inventory database, which processes them at a steady rate. Only the reservation, a fast atomic decrement or conditional write, happens synchronously. Payment capture, emails and warehouse messages follow through queues.

When to Use It#

  • Slow work that the user does not need to wait for: emails, notifications, image and video processing, report generation.
  • Absorbing spikes so downstream systems see a smooth rate.
  • Decoupling services so one being down does not break the other.
  • Distributing work across many workers (crawling, batch jobs).

When NOT to Use It#

  • When the caller needs the result immediately (login, price check).
  • Fast, simple operations where a queue only adds moving parts.
  • When you need replay or many independent subscribers; use an event stream.

How to Implement It#

  1. Identify async work in the request path and define a small message schema with a unique ID.
  2. Pick a tool: SQS for managed simplicity on AWS, RabbitMQ for routing and priorities, a task framework inside one codebase.
  3. Make consumers idempotent (dedupe by message ID or use idempotent writes).
  4. Set visibility timeouts, retries with backoff and a DLQ; alert on DLQ depth.
  5. Autoscale workers on queue depth or message age.
  6. Return a job ID to the user and expose status, or notify on completion. See Pattern: Long-Running Tasks.
TechnologyFits when
Amazon SQSManaged, nearly unlimited standard queues; FIFO when order matters
RabbitMQFlexible routing (exchanges), priorities, self-hosted or managed
Celery, Sidekiq, BullMQBackground jobs within a Python, Ruby or Node.js app
Google Cloud Tasks, Azure Queue StorageManaged queues on those clouds

Trade-offs#

ChoiceGainCost
Async via queueFast responses, spike absorption, decouplingEventual results, more infrastructure, harder debugging
Standard (unordered) queueHighest throughputDuplicates and reordering possible
FIFO queueOrdering, deduplicationLower throughput; ordering only per group
Long visibility timeoutFewer duplicate deliveriesSlower recovery after a crash
Short visibility timeoutFast redeliveryDuplicates while work is still running
Ack after processing (at-least-once)No lost messagesDuplicates on crash, consumers must be idempotent
Task framework (Celery, Sidekiq)Retries, scheduling, results in one libraryOne language, defaults such as early acks to review
Workflow engine (Temporal, Step Functions)Durable multi-step state, timers, signalsAnother platform to run, deterministic-code rules
Separate queues per job sizeNo head-of-line blocking, simpler scalingMore queues to monitor and configure

Common Pitfalls#

  • Non-idempotent consumers, causing double emails or charges on redelivery.
  • No DLQ, so poison messages retry forever.
  • Putting large files in messages instead of references.
  • No monitoring of queue age, discovering a three-hour backlog from customer complaints.
  • Visibility timeout shorter than the slowest job, so two workers process the same message at once.
  • Retrying permanent errors, or requeueing immediately in a tight loop.
  • Autoscaling consumers past what the database or partner API can take.
  • One queue for fast and slow jobs, letting long jobs block short ones.
  • Publishing an event outside the database transaction instead of using an outbox.

Real-World Examples#

Amazon SQS was one of the first AWS services, launched in 2006 (in beta from 2004), and is used to decouple services across many AWS customers.

Resque, a Redis-backed background job library, was created at GitHub to run its background jobs, and inspired later tools such as Sidekiq.

Sidekiq's default retry policy, about 25 attempts with exponential backoff over roughly three weeks before a job is marked dead, is a widely copied example of "retry long, then park for humans". RabbitMQ's move from classic mirrored queues to Raft-based quorum queues shows the industry shift toward consensus-replicated queues when message loss is unacceptable.

In the Interview#

Interview playbook for queues#

Where a queue earns a box in your diagram. Draw one when a step is slow (transcoding, report generation), bursty (flash-sale orders, notification fan-out), unreliable (partner APIs, email providers) or independently scalable (crawler fetchers). Say why in one sentence: "Transcoding takes minutes, so the upload API enqueues and returns 202."

What to say next, in order.

  1. Message contents: an ID and references, not blobs.
  2. Delivery guarantee: at-least-once, so consumers are idempotent by the business key.
  3. Failure handling: visibility timeout above p99 with heartbeats, retries with jittered backoff, a DLQ with an alert.
  4. Ordering: only if needed, and per key, using FIFO message groups or partitions.
  5. Scaling and back pressure: workers autoscale on oldest-message age, capped by what the downstream can take, with load shedding for low-priority work.
  6. Status: a jobs table and a way to notify the client.

Probes and strong answers.

  • "The queue backs up to a million messages. What now?" Check whether consumers are failing, which shows in errors and DLQ inflow, or just too slow, which shows in processing time. Scale out if the downstream has room. Otherwise shed low-priority work and rate-limit producers. Compute the drain time from the backlog and the throughput.
  • "Can you guarantee exactly-once?" Delivery is at-least-once. Effects become exactly-once through idempotent processing, such as a dedupe table in the same transaction as the write. See Delivery Semantics.
  • "Why not Kafka?" Kafka is a log: it is right for replay, many consumer groups and very high throughput with per-partition order. A queue is simpler for independent jobs with per-message retries and DLQs.
  • "Why not do it in a cron job?" For periodic batch work, a scheduler is fine. For work triggered by user actions, a queue gives lower latency and natural load levelling.
Deep Dive: Little's law, long polling and queue sizingShow

Little's law links queue length, throughput and waiting time: L = λ × W. If messages arrive at 500 per second and each waits 4 seconds on average, about 2,000 messages are in the system. To keep waiting under 1 second at 500 per second, workers must keep the backlog under about 500.

Long polling. SQS consumers should set WaitTimeSeconds (up to 20) to avoid empty responses, cutting cost.

Worker count ≈ arrival rate × processing time ÷ concurrency per worker: 200 jobs/s × 0.5 s ÷ 10 = at least 10 workers, plus headroom.

Deep Dive: Queueing theory for worker poolsShow

Utilisation is the knob that controls waiting. Model a worker pool as a queue with arrival rate λ (jobs per second) and service rate μ per worker. Utilisation is ρ = λ / (c x μ) for c workers. For the simplest model, one worker with random (Poisson) arrivals and random service times, called M/M/1, the average time in the system is W = 1 / (μ - λ). Relative to the bare service time 1/μ, that is 1 / (1 - ρ). At 50% utilisation a job takes twice its service time, at 80% five times, at 90% ten times and at 95% twenty times. Latency does not grow linearly with load. It explodes near saturation, which is why a queue that was fine at 70% load "suddenly" falls hours behind at 95%.

Variability matters as much as load. Kingman's approximation ("The single server queue in heavy traffic", 1961) for a general single-server queue says the waiting time is roughly (ρ / (1 - ρ)) x ((Ca² + Cs²) / 2) x service time, where Ca and Cs are the coefficients of variation of inter-arrival and service times. Bursty arrivals or a mix of 1-second and 10-minute jobs (high Cs) raise the wait at the same utilisation. That is the mathematical case for separate queues per job size: each queue has low service-time variance, so each waits less.

Pooling helps. c workers sharing one queue wait far less than c workers each with a private queue at the same total load, because no worker sits idle while another has a backlog. The Erlang C formula gives the probability that a job has to wait in an M/M/c system. For a fixed utilisation, that probability falls as c grows, so large pools can run hotter safely. A pool of 100 workers at 85% utilisation makes fewer than 1 job in 10 wait at all, while a single worker at 85% makes the average job wait more than five service times. This is why one shared queue with competing consumers beats sharding work to fixed workers, and why routing every job of a key to one worker (for ordering) costs latency.

Little's law ties it together. Little's law (J. D. C. Little, "A Proof for the Queuing Formula: L = λW", 1961) says the average number of jobs in a stable system equals the arrival rate times the average time in the system, whatever the distributions. It gives three quick checks. Concurrency needed: 200 jobs/s x 0.5 s means 100 jobs in progress, so 10 workers of 10 threads each, at 100% utilisation, so plan for about 14. Drain time: a backlog of 60,000 at a spare capacity of 500 jobs/s drains in 2 minutes. Latency from depth: depth 3,000 at 1,000 jobs/s means a new job waits about 3 seconds.

A sizing rule that follows. Target 60 to 75% steady-state utilisation for latency-sensitive queues, so bursts land in the flat part of the curve. Batch queues can run near 100%, because nobody is waiting on any single job. Size the downstream for the worker ceiling, not the average, or the autoscaler will move the queue from the broker into the database's connection pool.

Key Takeaways#

  • Queues let producers hand off work and continue, decoupling services in time and failure.
  • Consumers acknowledge messages; unacknowledged ones reappear after a visibility timeout, so consumers must be idempotent.
  • Retry with backoff and park poison messages in a dead-letter queue.
  • Queues absorb bursts (back pressure); monitor depth and age and autoscale workers.
  • Use FIFO queues or partitions when order matters; avoid queues when the caller needs the answer now.
  • Split slow work into accept (202 plus job ID) and process (workers update a jobs table).
  • The ack timing sets the guarantee. Pick at-least-once and dedupe by business key.
  • Classify failures: back off transient ones with jitter, dead-letter poison ones, and pause on systemic ones.
  • Watch the oldest message's age, and size workers using Little's law and a utilisation target below 75%.