Learnings

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.

Inline: the user waits for the mail server, and its outage becomes your outage.
Queued: the request returns at once, and the worker can retry without the user.
  • 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 messageDo not put in the message
Ids (transfer_id=7001) and small plain valuesORM objects or pickled classes
An idempotency keyLarge payloads: store the file, pass its key
JSON-friendly types onlySecrets, 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

The broker holds messages until a worker acknowledges them. The result store is optional.
  • 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.

Ack first: at-most-once. A crash after the ack loses the message.
Ack last: at-least-once. A crash between the work and the ack runs the task twice.
GuaranteeAckFailure modeUse for
At-most-onceBefore the workLost tasksMetrics, cache warm-ups
At-least-onceAfter the workDuplicate runsAlmost everything
"Exactly-once"After the workNone visibleAt-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

A delivered message is hidden, not deleted. Only an ack deletes it.
TermMeaning
Ack"Done, delete it"
Nack / reject"Failed, give it to someone else (or dead-letter it)"
Visibility timeoutHow long a delivered message stays hidden before the broker assumes the worker died
RedeliveryThe 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

Build one on Redis

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

Build one on Redis

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

Build one on Redis

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.

A job is deleted only after the work. A dead worker's job goes back to the queue.
  • 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: BLMOVE and ZADD are two commands. Production code joins them in a Lua script, or uses a Stream.

The same with a Stream consumer group

Build one on Redis

A Stream consumer group has the processing list built in: it is called the pending entries list (PEL). XAUTOCLAIM is the reaper.

An unacked entry stays pending under its consumer's name until another consumer claims it.
  • 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 XTRIM or MAXLEN.

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 NX then 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 row and the message commit together. The relay publishes at-least-once.
  • 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).

Retry a few times, then move the message aside with its error.
  • 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

Order, time and flow

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.

Per-key ordering: one account always maps to one partition, and one worker owns a partition.
  • 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

Order, time and flow

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.

ProblemFix
Long tasks starve short onesSeparate queues and worker pools by duration
Reserved tasks stuck behind a slow onePrefetch 1 for long tasks
Urgent work waits behind bulk workA "high" queue that workers drain first, not in-queue priorities
One customer floods the queuePer-tenant queues or a per-tenant rate limit

Delayed tasks with a sorted set

Order, time and flow

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.
  • ZREM returning 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

Order, time and flow

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

Order, time and flow

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.

Backpressure protects you from producers. A rate limit protects the downstream from you.
Response to a growing queueWhen
Add workers (autoscale on depth or age)Workers are the bottleneck, downstream has room
Reject or slow the producerThe 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 workersThe downstream API has a quota

Celery in practice

Part 5 of 6 · a real worker on the Redis broker

Tasks and a worker

Celery in practice

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

Celery in practice

task_routes picks the queue by task name. One worker can consume several queues.
CallUse
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

Celery in practice

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.

OptionEffect
autoretry_for=(TimeoutError,)Retry only these exceptions. Never Exception.
retry_backoff=1Delays of 1, 2, 4, ... seconds (retry_backoff_max caps it, default 600)
retry_jitterOn by default. Turned off here only so the log shows exact delays.
max_retries=3Then the task fails for good. Celery has no DLQ: log it or route it yourself in on_failure.

acks_late and a killed worker

Celery in practice

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 in tasks.py for this demo.
  • Trap: a countdown or eta longer 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, unless task_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

Celery in practice

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).

PoolGood forNote
prefork (default)CPU work, general useOne process per slot, uses every core
threadsI/O-bound tasksShares the GIL
gevent / eventletThousands of waiting network callsLibraries must cooperate
  • 'acknowledged': True on 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 events for a live feed from workers started with -E.
  • For long tasks set worker_prefetch_multiplier=1, and --max-tasks-per-child if tasks leak memory.

Choosing and operating

Part 6 of 6 · brokers, metrics, shutdown, deploys, recap

Choosing a broker

Choosing and operating

Redis lists / streamsRabbitMQSQSKafka
Delivery modelPop, or consumer group with acksPush with acks, routing by exchangePoll, visibility timeout, deleteConsumers read a log and commit offsets
GuaranteeAt-most-once (plain pop), at-least-once (streams)At-least-onceAt-least-once (FIFO queues deduplicate)At-least-once
OrderingPer list or streamPer queue, with one consumerBest effort, or per group in FIFO queuesPer partition
ReplayStreams onlyNo (classic queues)NoYes, by offset, for the retention period
Operational weightLow, and often already thereMediumNone to runHigh
Typical useSmall and medium task queuesTask queues with routing needsTask queues on AWSEvent 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

Choosing and operating

Task queueEvent streamPub/Sub
Message means"Do this""This happened""Heads up, right now"
Who gets itOne workerEvery consumer group, each at its own paceEvery subscriber connected now
After processingDeletedKept for the retention periodNever stored
If nobody is listeningWaitsWaitsLost
ExampleSend this receiptTransfer 7001 completedInvalidate this cache key

The Pub/Sub column is covered in Redis Pub/Sub.

What to measure

Choosing and operating

MetricTells youAlert when
Age of oldest messageHow late the work is. The best single signal.Above the delay users can accept
Queue depthBacklog sizeGrowing for several minutes
Processing time (p50, p99)Slow tasks, stuck downstreamsp99 near the visibility timeout
Failure and retry rateBad deploys, broken dependenciesAbove the normal baseline
DLQ depthWork that gave upAbove 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

Choosing and operating

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

Choosing and operating

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.

Adding an argument: workers learn it first, producers use it second, cleanup comes last.
ChangeSafe way
Add an argumentGive it a default. Deploy workers, then producers.
Remove an argumentStop sending it, let the queue drain, then remove it from the task
Change meaning or typeNew task name (send_receipt_v2), keep the old one until its queue is empty
Rename or move a taskKeep 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

Choosing and operating

IfThen
Losing a task is acceptableAt-most-once: early ack, simplest setup
Losing a task is not acceptableAt-least-once (late ack) plus an idempotency key
The message must match a database writeOutbox
The error is permanent, or attempts ran outDead-letter queue and an alert
Order matters per accountPartition by account, one consumer per partition
Long and short tasks share a queueSplit queues and pools, prefetch 1 for long ones
The queue keeps growingScale workers, then bound the queue and push back
Several services react to the same factAn event stream, not a task queue
Python service, Redis already thereCelery on Redis, acks_late on idempotent tasks

Interview questions

Choosing and operating

QuestionShort 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.