Guide · Python backend
Celery Task Recovery: What Happens When Things Break
Key takeaways
- Late acks permit redelivery, but child-process loss needs separate policy and duplicates still need safe handling.
- Retries need exponential backoff and a cap; then a failed state someone actually monitors.
- Queues can't help with events that were never enqueued — downtime needs a backfill job.
- The database row is the source of truth for job state; Redis is just the broker.
By Prasanna Patil · published · updated
The failure modes, in order of how often they bite
- A worker dies mid-task. The default early acknowledgement already told the broker the task succeeded.
- A task fails repeatedly. Naive retries hammer a struggling third-party API and bury the real signal.
- Your service was down. Nothing was enqueued during the outage, so the queue is empty and the data is missing.
Each needs an explicit recovery policy. The settings below illustrate the trade-offs; they are not universal defaults. The WhatsApp ingestion work at Zuneko Labs also needed source backfills for missed events.
Worker-loss policy and duplicate handling
app.conf.task_acks_late = True # ack AFTER the task finishes
app.conf.worker_prefetch_multiplier = 1 # limits reservation; not a duplicate-execution guard
app.conf.task_reject_on_worker_lost = True # optional policy: can requeue a repeatedly crashing task forever
@app.task(bind=True, autoretry_for=(TransientError,),
retry_backoff=True, retry_backoff_max=600, max_retries=5)
def handle_message(self, message_id: str):
row = db.get(message_id)
if row.status == "done": # skips completed work, not concurrent execution
return
...
db.save_reply(message_id, reply, status="done")The status check above only skips work already marked done. Two workers can both pass it, and an external send can succeed before its result is saved. Use an atomic claim with abandoned-job recovery and provider idempotency where available; reconcile uncertain send outcomes. Late acks do not supply these guarantees.
Celery acknowledges a terminated child process by default even with late acks. Requeue-on-worker-loss changes that policy but can loop on a task that repeatedly crashes. Review the Celery task documentation and monitor worker-loss redeliveries separately from application retries.
The gap no queue setting fixes
If your service (or the network in front of it) is down, the provider's webhook never reaches you. The queue holds nothing because nothing was ever enqueued. For the WhatsApp document ingestion at Zuneko Labs I added a recovery job: on a schedule, it asks the source of truth what's missing — messages without a processed row in the window — and backfills them. The database is what makes this possible; this is a big part of why job state lives in PostgreSQL and not in Redis.
Redis visibility_timeout: redelivery while the task is still running
With the Redis broker, an unacknowledged message is not held forever. Celery relies on a visibility_timeout — if a message stays unacked longer than that, the broker makes it visible again and another worker picks it up. With late acks, "unacked" includes "still running". So a task that legitimately takes longer than the timeout is delivered a second time while the first copy is alive and working. Nothing has crashed; the broker simply can't tell slow from dead.
Two things follow. First, set the timeout comfortably above your longest realistic task, not above the average. Second, treat the idempotency guard as mandatory rather than defensive: the duplicate can arrive at any time, including mid-execution, so a plain "is it done yet?" check is not enough.
app.conf.broker_transport_options = {
"visibility_timeout": 3600, # seconds; must exceed the slowest task you expect
}
def claim(message_id: str) -> bool:
# Atomic claim: only one worker flips queued -> running.
updated = db.execute(
"UPDATE jobs SET status='running', started_at=now() "
"WHERE id=%s AND status='queued'", (message_id,)
)
return updated == 1The atomic claim means a redelivered copy finds the row already running and exits, while a genuinely dead worker leaves a row you can detect and reset (see the runbook below).
acks_late and reject_on_worker_lost: duplicates versus loss
These settings move you along a trade-off rather than removing it. Early acks risk loss: the broker forgets the task the moment it is handed over, so a crash drops it. Late acks risk duplicates: a task can run twice if the worker dies after finishing the work but before acknowledging it, or if the visibility timeout fires.
- Early ack (default). At-most-once in practice. Fine for work you can regenerate or that nobody notices missing.
- Late ack. At-least-once. Requires idempotent tasks; in return, a crashed worker no longer loses its task.
- reject_on_worker_lost. Applies when the worker process is killed (for example an out-of-memory kill). Without it, Celery treats the lost task as acked-late-and-failed; with it, the message is requeued. Pair it with a retry cap so a task that crashes the worker every time doesn't loop forever.
The practical rule: pick at-least-once plus idempotency for anything where losing the work costs more than doing it twice, and make the duplicate harmless instead of trying to prevent it.
A failed-task table that someone actually reviews
When retries are exhausted, the task should not just vanish into a log line. Write a row to a table that acts as a dead-letter queue you can query: enough to understand the failure and to replay it deliberately.
CREATE TABLE failed_tasks (
id bigserial PRIMARY KEY,
task_id text NOT NULL, -- Celery task id
task_name text NOT NULL,
payload_ref text NOT NULL, -- id of the source row, not a copy of the data
error text NOT NULL, -- last exception, truncated
attempts int NOT NULL,
state text NOT NULL DEFAULT 'new', -- new | investigating | replayed | ignored
created_at timestamptz NOT NULL DEFAULT now()
);Store a reference to the payload rather than the payload itself, so a replay always uses current data and sensitive content isn't copied around. Reviewing it is a routine: group rows by error text, fix the cause (a bad input, an expired credential, a provider outage), then replay the group and mark it replayed. Rows you decide not to process are marked ignored with a reason, so the new count stays meaningful.
Designing the backfill and recovery job
The recovery job from the previous section needs a few properties to be safe to run unattended.
- A cursor or high-water mark. Record the timestamp or id up to which the source has been reconciled, and start each run slightly before it. The overlap absorbs late-arriving records.
- Idempotent re-enqueue. Enqueue by a stable key (the source message id) and let the task's guard drop anything already
done. Running the job twice should change nothing. - Rate limiting. After an outage there may be a large backlog. Enqueue in bounded batches so recovery doesn't starve live traffic or hit a provider's limits.
- Advance the cursor last. Only move the high-water mark after a batch is safely enqueued, so a crash mid-run repeats work instead of skipping it.
BATCH = 200
OVERLAP = timedelta(hours=1)
def recover():
since = cursor.get() - OVERLAP
missing = source.messages_since(since).exclude(processed_ids())
for batch in chunked(missing, BATCH):
for m in batch:
handle_message.apply_async(args=[m.id], task_id=f"msg-{m.id}")
cursor.set(batch[-1].created_at) # advance only after enqueue
time.sleep(1) # crude rate limitMonitoring: what to alert on, and what to ignore
- Rows stuck in
queuedpast a threshold — a dead worker pool or a lost broker. - Tasks exhausted retries and entered
failed— needs a human, not another retry. - Backfill jobs finding work — a signal your ingestion path has a gap worth investigating.
- Queue age, meaning how long the oldest waiting message has been there. It reflects user impact better than queue length does.
- Worker heartbeat. If no worker has reported in for a few minutes, nothing is consuming, whatever the queue looks like.
Be careful with the rest. A single retry is the system working as designed, so alerting on individual task failures or on a briefly long queue after a burst trains people to ignore the pager. Alert on the conditions above persisting, and leave transient noise on a dashboard.
Runbook: a worker died mid-task
- Confirm the worker is actually gone (heartbeat missing, process or container exit reason) and restart it.
- Check whether the task was redelivered: look for the job row moving from
runningback through a new attempt. - Find rows stuck in
runninglonger than any task should take and reset them toqueued, or re-enqueue them by key. - Look at the exit reason. An out-of-memory kill on one input will repeat, so cap retries and send it to the failed table rather than looping.
- Run the recovery job to confirm nothing between the last cursor and now is missing.
- Record the cause. A repeated cause deserves a fix, not another reset.
Limitations of this guide
It covers Redis-broker Celery with a database-backed state model. Kafka-style event sourcing, exactly-once pipelines, and very long-running jobs (minutes to hours) need different machinery.
Frequently asked questions
Do late acks hurt throughput?
Slightly — with prefetch_multiplier=1 a worker holds one unacked task instead of hoarding a batch. For slow tasks (inference, LLM calls) that's what you want anyway; the hoarding was starving the other workers.
How long should the backfill window look?
Overlap it generously — look back past the longest outage you've had, not just since the last successful run. The idempotency guard makes reprocessing cheap; missing a window is what's expensive.
Redis or RabbitMQ as the broker?
Redis is fine for most workloads and is what I default to, with the caveat that it's not a durable log. If your requirements include broker-level durability guarantees you can't reconstruct from the database, that's the case for RabbitMQ.
Why did my task run twice when nothing crashed?
Most often the Redis visibility_timeout. With late acks, a task that runs longer than the timeout is redelivered to another worker while the first is still running. Raise the timeout above your slowest task and make the task claim its row atomically.
Should failed tasks be retried automatically forever?
No. Cap retries with backoff, then record the task in a failed table and let a person look at it. Endless retries hide the real problem and hammer whatever dependency is struggling.
What should a dead-letter table store?
The task id, task name, a reference to the source row rather than a copy of the data, the last error, the attempt count and a review state. That is enough to group failures by cause and replay them deliberately.
Losing tasks when workers die?
Describe the queue setup and what disappears.