Senior engineering skills
Task Queues and Messaging
How to get background work done reliably: delivery guarantees, a queue built by hand on Redis, idempotency, retries, ordering, scheduling, and Celery in practice. Every program here was run with redis-py 7 and Celery 5.6 against a local Redis 8, and its output is pasted from that run.
Why a queue, and what it promises
Part 1 of 6 · the moving parts and the three delivery guarantees
Slow request versus enqueue and return
Why a queue, and what it promises
A request should do only what the user is waiting for. Everything else becomes a message that a worker handles later.
- You gain: fast responses, retries, a buffer for spikes, workers that scale separately.
- You pay: the work is now asynchronous, can run twice, and can run late.
What belongs in a task
Why a queue, and what it promises
Queue what the response does not need: email and webhooks, reports and exports, calls to slow third parties. Keep validation and the write that makes the action true in the request.
| Put in the message | Do not put in the message |
|---|---|
Ids (transfer_id=7001) and small plain values | ORM objects or pickled classes |
| An idempotency key | Large payloads: store the file, pass its key |
| JSON-friendly types only | Secrets, and state that may be stale by run time |
Trap: a task runs later, so pass the id and re-read the row inside the task. A balance copied into the message is already history.
Producer, broker, worker, result store
Why a queue, and what it promises
- Broker: stores messages durably and hands each to one worker.
- Worker: a long-running process that takes a message, runs the function, acks.
- Result store: only if the producer needs the return value. Often it does not.
Delivery guarantees
Why a queue, and what it promises
The guarantee is decided by one thing: whether the worker acknowledges before or after doing the work.
| Guarantee | Ack | Failure mode | Use for |
|---|---|---|---|
| At-most-once | Before the work | Lost tasks | Metrics, cache warm-ups |
| At-least-once | After the work | Duplicate runs | Almost everything |
| "Exactly-once" | After the work | None visible | At-least-once delivery plus an idempotent task |
Interview point: no broker can deliver exactly once across a crash, because it cannot tell "work done, ack lost" from "work never done". You get exactly-once effects by making the second run harmless.
Acks, visibility timeouts, redelivery
Why a queue, and what it promises
| Term | Meaning |
|---|---|
| Ack | "Done, delete it" |
| Nack / reject | "Failed, give it to someone else (or dead-letter it)" |
| Visibility timeout | How long a delivered message stays hidden before the broker assumes the worker died |
| Redelivery | The same message handed out again, usually with a delivery count |
Trap: a task that runs longer than the visibility timeout is redelivered while it is still running. Set the timeout above your slowest task, or extend it from the worker (a heartbeat).
Build one on Redis
Part 2 of 6 · a queue that loses a job, then two that do not
Setup
Each program below is one file: run with no arguments it fills the queue and starts workers as child processes. A worker "crashes" with os._exit(1), which skips all cleanup like a power cut.
Database 15: every key here lives in Redis db 15 under a tq: prefix, away from real data. If lists and Pub/Sub are new, read fan-out versus a work queue first.
Naive: LPUSH and BRPOP
BRPOP removes the job from Redis and hands it to the worker. From that moment the only copy is in the worker's memory.
Result: job-2 is gone and nothing records that it ever existed. This is at-most-once delivery.
Reliable: a processing list and a reaper
BLMOVE moves the job to a second list in one atomic step, so it is always stored somewhere. A reaper returns jobs whose deadline passed.
- Nothing lost: job-2 ran after the reaper requeued it. This is at-least-once.
- Had w1 crashed after the work and before
LREM, job-2 would have run twice. - Gap left open:
BLMOVEandZADDare two commands. Production code joins them in a Lua script, or uses a Stream.
The same with a Stream consumer group
A Stream consumer group has the processing list built in: it is called the pending entries list (PEL). XAUTOCLAIM is the reaper.
- The PEL records owner, idle time and delivery count, so the delivery count doubles as the poison-message check.
- An acked entry stays in the stream (length is still 3): trim with
XTRIMorMAXLEN.
Running twice, failing, retrying
Part 3 of 6 · idempotency, the outbox, backoff and the dead-letter queue
Idempotency keys
Running twice, failing, retrying
A task runs twice when the ack is lost, the visibility timeout fires early, a producer retries its enqueue, or someone replays a queue. Give each logical action a key, and record the key in the same atomic step as the effect.
- The key comes from the action (
transfer-7001), never from the message id or a timestamp. SET NXthen the effect as two separate commands is a bug: a crash between them marks the transfer done without moving money.- With SQL: insert the key into a table with a unique constraint, inside the same transaction as the balance update.
The outbox pattern
Running twice, failing, retrying
Writing the database and then enqueueing is two systems and no shared transaction: a crash between them loses the message, and the reverse order sends a message for a row that rolled back. Write the message as a row in the same transaction instead.
- The relay can crash after publishing and before marking sent, so consumers still need idempotency.
- Relay options: a polling loop (
SELECT ... FOR UPDATE SKIP LOCKED) or change data capture on the outbox table.
Retries and backoff
Running twice, failing, retrying
Immediate retries hammer a service that is already down, and identical delays make every worker return at the same instant. Double the delay each attempt, cap it, and randomise it.
- Retry: timeouts, connection resets, HTTP 429 / 502 / 503, deadlocks.
- Do not retry: validation errors, HTTP 400 / 404, bugs. They fail the same way every time.
Rule: always set a maximum attempt count. A retry without a limit is an infinite loop with a delay.
Poison messages and the dead-letter queue
Running twice, failing, retrying
A poison message fails on every attempt. Without a limit it circles forever and blocks the jobs behind it, so after N attempts park it in a dead-letter queue (DLQ).
- Alert on: DLQ depth above zero, a rising retry rate, and the age of the oldest message.
- Store the error and attempt count with the dead message, and keep a replay tool.
Order, time and flow
Part 4 of 6 · ordering, prefetch, delayed and periodic tasks, backpressure
Ordering with parallel workers
A queue is FIFO only with one worker. Two workers take "deposit" and "withdraw" in order and may finish them in either order, and a retry reorders things again.
- Order holds per account, not across accounts, which is usually all the business needs.
- Same idea elsewhere: Kafka partition key, SQS FIFO message group id.
- Cheaper alternative: make order irrelevant, with a version number on the row and "ignore older than current".
Prefetch, priorities, separate queues
Prefetch is how many messages a worker reserves ahead of time. A high prefetch helps throughput on tiny tasks and hurts when a long task sits in front of reserved short ones while other workers are idle.
| Problem | Fix |
|---|---|
| Long tasks starve short ones | Separate queues and worker pools by duration |
| Reserved tasks stuck behind a slow one | Prefetch 1 for long tasks |
| Urgent work waits behind bulk work | A "high" queue that workers drain first, not in-queue priorities |
| One customer floods the queue | Per-tenant queues or a per-tenant rate limit |
Delayed tasks with a sorted set
Store the job in a sorted set with its run time as the score. A poller moves everything with a score up to "now" into the normal queue.
- The sorted set orders by time, whatever the insert order was.
ZREMreturning 1 is the claim, so two pollers never move the same job.- This is also how retry delays work: a failed job is a delayed job.
Periodic tasks and two schedulers
A scheduler only enqueues: "every day at 02:00, put an interest run on the queue". Run two copies for availability and every tick is enqueued twice, unless each tick is claimed with SET NX.
- Celery beat has the same rule: run exactly one beat process, or use a scheduler with a lock.
- Make the periodic task itself idempotent per period (key:
interest-2026-11-24). - If one run can outlast the interval, take a lock or skip when the previous run is still going.
Rate limits and backpressure
When producers outrun workers, an unbounded queue grows until memory runs out and every task is hours late. A bounded queue pushes the problem back to the producer, where it can be handled.
| Response to a growing queue | When |
|---|---|
| Add workers (autoscale on depth or age) | Workers are the bottleneck, downstream has room |
| Reject or slow the producer | The spike is larger than you can ever drain |
| Drop or expire stale tasks (TTL) | A late result is useless (an OTP message) |
| Rate limit the workers | The downstream API has a quota |
Celery in practice
Part 5 of 6 · a real worker on the Redis broker
Tasks and a worker
Celery is everything from parts 2 to 4 behind a decorator. Broker and result backend are both Redis db 15 here.
Trap: a worker consumes only the queues named in -Q (default: celery). A task routed to a queue nobody consumes waits forever, silently.
delay, apply_async, routing, results
task_routes picks the queue by task name. One worker can consume several queues.| Call | Use |
|---|---|
task.delay(a, b) | Plain enqueue |
task.apply_async((a, b), countdown=, eta=, queue=, expires=) | Any option per call |
result.get() | Blocks the caller: fine in a script, wrong inside a request or another task |
Results: most tasks write their outcome to the database, so nobody reads the return value. Set ignore_result=True (as send_receipt does) or run with no backend, and always set result_expires.
Retries with autoretry_for
post_to_ledger raises TimeoutError on its first two runs. The same task id comes back after 1 s, then 2 s, and may land on a different process.
| Option | Effect |
|---|---|
autoretry_for=(TimeoutError,) | Retry only these exceptions. Never Exception. |
retry_backoff=1 | Delays of 1, 2, 4, ... seconds (retry_backoff_max caps it, default 600) |
retry_jitter | On by default. Turned off here only so the log shows exact delays. |
max_retries=3 | Then the task fails for good. Celery has no DLQ: log it or route it yourself in on_failure. |
acks_late and a killed worker
By default Celery acks a task just before running it: at-most-once. acks_late=True moves the ack to after the task returns: at-least-once.
Each run below starts a worker with --concurrency=1, sends one 3 s report, kills the whole worker with kill -9 after 1.5 s, waits 6 s, and starts a new worker. Log lines are real; the left column and the unbracketed lines are annotations.
- With the Redis broker, an unacked task returns only after
visibility_timeout: 1 hour by default, 5 s intasks.pyfor this demo. - Trap: a
countdownoretalonger than the visibility timeout gets redelivered and runs more than once. Keep the timeout above your longest delay and longest task. - Not run for this page: if only the child process dies (out of memory), Celery's documented default is to ack and mark the task failed even with
acks_late, unlesstask_reject_on_worker_lost=True.
Rule: turn on acks_late only for tasks that are idempotent. You are trading "sometimes lost" for "sometimes twice".
Concurrency and inspecting
The default prefork pool has one main process that reserves messages and N child processes that run them. Prefetch is 4 × concurrency by default (8 here, from inspect stats).
| Pool | Good for | Note |
|---|---|---|
prefork (default) | CPU work, general use | One process per slot, uses every core |
threads | I/O-bound tasks | Shares the GIL |
gevent / eventlet | Thousands of waiting network calls | Libraries must cooperate |
'acknowledged': Trueon a running task is the early ack from the previous chapter, visible live.- Also:
inspect reserved,inspect stats, and (not run for this page)celery -A tasks eventsfor a live feed from workers started with-E. - For long tasks set
worker_prefetch_multiplier=1, and--max-tasks-per-childif tasks leak memory.
Choosing and operating
Part 6 of 6 · brokers, metrics, shutdown, deploys, recap
Choosing a broker
| Redis lists / streams | RabbitMQ | SQS | Kafka | |
|---|---|---|---|---|
| Delivery model | Pop, or consumer group with acks | Push with acks, routing by exchange | Poll, visibility timeout, delete | Consumers read a log and commit offsets |
| Guarantee | At-most-once (plain pop), at-least-once (streams) | At-least-once | At-least-once (FIFO queues deduplicate) | At-least-once |
| Ordering | Per list or stream | Per queue, with one consumer | Best effort, or per group in FIFO queues | Per partition |
| Replay | Streams only | No (classic queues) | No | Yes, by offset, for the retention period |
| Operational weight | Low, and often already there | Medium | None to run | High |
| Typical use | Small and medium task queues | Task queues with routing needs | Task queues on AWS | Event streams, many independent readers |
Approximate: each product has modes that blur these columns (RabbitMQ streams, SQS redrive, Kafka share groups). Treat the table as the default behaviour, not the limit.
Task queue, event stream, Pub/Sub
| Task queue | Event stream | Pub/Sub | |
|---|---|---|---|
| Message means | "Do this" | "This happened" | "Heads up, right now" |
| Who gets it | One worker | Every consumer group, each at its own pace | Every subscriber connected now |
| After processing | Deleted | Kept for the retention period | Never stored |
| If nobody is listening | Waits | Waits | Lost |
| Example | Send this receipt | Transfer 7001 completed | Invalidate this cache key |
The Pub/Sub column is covered in Redis Pub/Sub.
What to measure
| Metric | Tells you | Alert when |
|---|---|---|
| Age of oldest message | How late the work is. The best single signal. | Above the delay users can accept |
| Queue depth | Backlog size | Growing for several minutes |
| Processing time (p50, p99) | Slow tasks, stuck downstreams | p99 near the visibility timeout |
| Failure and retry rate | Bad deploys, broken dependencies | Above the normal baseline |
| DLQ depth | Work that gave up | Above zero |
Trap: depth alone misleads. A depth of 10 is healthy at 100 tasks a second and an outage if the workers are dead.
Graceful shutdown on SIGTERM
A deploy sends SIGTERM, waits a grace period, then sends SIGKILL. A worker should stop taking tasks, finish the one in hand, and exit.
- The handler only sets a flag. The loop checks it between tasks.
- Set the grace period (Kubernetes
terminationGracePeriodSeconds) above your longest task, or accept a redelivery. - Celery does this on SIGTERM and logs
worker: Warm shutdown (MainProcess), as it did when the worker above was stopped.
Deploys with tasks in flight
During a deploy, old and new code read the same queue, and messages written yesterday are run by code written today. Treat a task signature like a public API.
| Change | Safe way |
|---|---|
| Add an argument | Give it a default. Deploy workers, then producers. |
| Remove an argument | Stop sending it, let the queue drain, then remove it from the task |
| Change meaning or type | New task name (send_receipt_v2), keep the old one until its queue is empty |
| Rename or move a task | Keep the old name registered: queued messages carry the old name |
Trap: delayed and retrying tasks can sit in the broker for hours. "The queue is empty" must include them.
Decision table
| If | Then |
|---|---|
| Losing a task is acceptable | At-most-once: early ack, simplest setup |
| Losing a task is not acceptable | At-least-once (late ack) plus an idempotency key |
| The message must match a database write | Outbox |
| The error is permanent, or attempts ran out | Dead-letter queue and an alert |
| Order matters per account | Partition by account, one consumer per partition |
| Long and short tasks share a queue | Split queues and pools, prefetch 1 for long ones |
| The queue keeps growing | Scale workers, then bound the queue and push back |
| Several services react to the same fact | An event stream, not a task queue |
| Python service, Redis already there | Celery on Redis, acks_late on idempotent tasks |
Interview questions
| Question | Short answer |
|---|---|
| Is exactly-once delivery possible? | Not across a crash. Use at-least-once delivery and idempotent tasks for exactly-once effects. |
| Why does a task run twice? | Lost ack, visibility timeout shorter than the task, producer retry, manual replay |
| How do you make a transfer task safe to repeat? | An idempotency key stored atomically with the balance change |
What does BRPOP lose that BLMOVE keeps? | The job while a worker holds it. BLMOVE leaves a copy in a processing list. |
| Why jitter? | So failed clients do not all retry at the same instant |
| What is a poison message? | One that fails every time. Cap attempts and move it to a DLQ. |
| How do you keep order with many workers? | Partition by key so one consumer handles each key |
What does acks_late change? | Ack after the task instead of before: a killed worker's task is redelivered, so it must be idempotent |
| Which queue metric do you alert on first? | Age of the oldest message, then DLQ depth |
Back to Senior Skills.