Skip to content

Reliable Celery tasks in Django: how to stop losing them

Celery tasks get lost at three points in a Django app: on the way from the web process to the broker, inside the broker, and on a worker that dies before the task finishes. Celery’s defaults favor speed over delivery, so a broker hiccup, a deploy or an out-of-memory kill can drop a task without an error anyone sees. To stop losing them, confirm every publish to the broker, queue tasks only after the database transaction commits, acknowledge tasks late, write tasks that are safe to run twice, and let the database, not the queue, decide what still has to run.

We’ve used Celery in production across dozens of client projects at Vinta and met almost every failure in this guide. Celery is still the most complete task queue for Python, so the practical choice is to learn how it fails before your users do. This guide is based on Flávio Juvenal’s talk at DjangoCon; the video above is a snippet of it.

For more on running Celery, see our Celery engineering insights.

Key takeaways

Make the broker keep them

Have RabbitMQ confirm every task it receives (confirm_publish), and never let Redis evict keys to free memory.

Queue them at the right time

Send a task only after its data is committed (transaction.on_commit), and pass IDs, not large payloads.

Make workers finish them

Let a task leave the queue only after it runs (task_acks_late=True), so a crash means a retry, not a loss.

Make them safe to run twice

Redelivery means repeats. Write idempotent tasks and wrap their database changes in a transaction.

Recover the ones that slip

Let the database decide what still has to run, and have a scheduled task queue it again.

Deploy without dropping them

Stop workers with a soft shutdown, and change a task’s arguments in two deploys.

Where Celery tasks get lost

Celery is a distributed system. A task leaves your web process, waits in a message broker such as RabbitMQ or Redis, and runs in a separate worker process. Every hop between them is a network connection that can fail, and when one does, the task can be lost, run twice or run against data that isn’t there yet.

Where a Celery task can get lost

Web process
Broker
Worker process
A task crosses two hops before it runs, and either one can drop it.

These failures are hard to catch because they’re intermittent. Unlike a bug you can reproduce, a lost task leaves no trace: a user signs up, the activation email task disappears, and the user waits for an email that never arrives. The sections below close each gap in the order a task meets them.

How to stop losing tasks between Django and the broker

Confirm that the broker received the task

If the broker is down or unreachable when you call my_task.delay(x=2, y=3), Celery raises an OperationalError. By default it retries publishing three times, 0.2 seconds apart, which covers short network blips.

A stable connection doesn’t guarantee delivery, though: the broker can still fail to store the message. On RabbitMQ, turn on publisher confirms with the broker_transport_options setting:

Python
broker_transport_options = {"confirm_publish": True}

Publishing gets slightly slower, but once delay() returns, the task is on the broker.

Keep task payloads small

Large arguments, such as big dictionaries or file contents, can slow a broker down or take it out. On one project, our RabbitMQ data directories grew to 100 GB because tasks carried whole XML documents as arguments.

Pass a reference to the data, not the data itself: a URL to a file in blob storage such as Amazon S3, or the primary key of a database row.

Python
# don't do:
my_task.delay(large_file)

# do:
my_task.delay(large_file_url)

The task fetches what it needs when it runs, and the broker only moves small messages.

Configure the broker so it doesn’t drop tasks

On RabbitMQ, make sure your server or cloud provider uses durable queues and persistent messages, so tasks survive a broker restart.

On a RabbitMQ cluster, consider quorum queues: RabbitMQ replicates each one across the cluster’s nodes, so queued tasks survive the loss of a node. Celery supports them from version 5.5: set task_default_queue_type = "quorum", or x-queue-type: quorum on a single queue. Celery’s notes on quorum queues list two caveats. They need global QoS turned off, so worker autoscaling stops working and ETA and countdown tasks move to RabbitMQ’s native delayed delivery. And from RabbitMQ 4.0, a quorum queue drops a message after 20 redeliveries without logging it, so the task stays PENDING: raise the limit with x-delivery-limit, or send those messages to a dead letter exchange.

On Redis, check the maxmemory policy. The allkeys-lru, allkeys-lfu and allkeys-random policies evict old or random keys when memory runs out, which silently drops queued tasks. Use a policy that rejects new writes instead (noeviction): an error when queuing is never welcome, but at least it is visible and easy to trace.

Give each Redis role its own instance: one for the application cache, one for the Celery broker and one for the result backend. We’ve seen a single shared Redis fail and take down the cache and the task queue together, which made recovery much harder.

Queue tasks only after the transaction commits

Queue a task from inside a database transaction and the worker can pick it up before the transaction commits. With ATOMIC_REQUESTS=True, the whole view runs in one transaction, so this happens on every request:

Python
class SignUpView(BaseSignUpView):
    def form_valid(self, form):
        response = super().form_valid(form)
        user_pk = self.request.user.pk
        task_send_activation_email.delay(user_pk)
        # the worker can run the task right now...
        return response  # ...but the commit only happens after this

The worker runs in a separate process, outside the view’s transaction, so it can’t see the new user yet and fails with User.DoesNotExist. This is a race between Django transactions and Celery tasks. Queue the task with transaction.on_commit so it’s sent only after the commit:

Python
class SignUpView(BaseSignUpView):
    def form_valid(self, form):
        response = super().form_valid(form)
        user_pk = self.request.user.pk
        transaction.on_commit(lambda: task_send_activation_email.delay(user_pk))
        return response

How to recover tasks that never reached the broker

transaction.on_commit fixes the ordering, but it opens a different gap. The user is now committed to the database, so from the business side the sign-up is done. If the broker is down at that moment, the activation email task is lost, and none of the settings above can bring it back. The database says everything is fine, and the user never gets the email.

Many apps leave this to the user, with a “resend activation email” button. A better fix is to make the database the source of truth for work that must happen, and let a periodic task requeue whatever is missing.

Recovering lost tasks from the database

Broker
Worker process
Database
A periodic task polls the database for work that should have happened and queues it again.

For the activation email, a Celery Beat task can look for users who haven’t received it yet:

Python
@celery_app.task
def task_ensure_activation_emails():
    qs = User.objects.filter(is_activation_email_sent=False)
    for user_pk in qs.values_list("pk", flat=True):
        task_send_activation_email.delay(user_pk)

Schedule it every five minutes or so, and keep queuing task_send_activation_email from the sign-up view as well. When everything works, the email goes out right away; when something breaks, the periodic task sends it on its next run. For this to work, task_send_activation_email must set is_activation_email_sent to True once the email is sent. Recovery now depends on Celery Beat, so make sure your Beat tasks are running.

When Celery is the wrong tool: workflows and data pipelines

Celery fits most background jobs, but not long workflows or data-heavy pipelines. Say you need to process millions of orders in parallel and notify a logistics system only after all of them finish: tracking that state in the database, as above, quickly becomes impractical.

Celery’s Canvas primitives (chains, groups and chords) look like the answer, but we don’t recommend them. They lose tasks in ways that are hard to detect, exceptions inside them are hard to handle, and Celery’s issue tracker keeps collecting Canvas bugs. We’ve helped several clients move off Canvas after it failed them in production.

For workflows, use a dedicated orchestrator. These tools give you better monitoring, error handling and retries, and run steps anywhere: pods, containers or serverless functions. They take more work to integrate with Django than Celery does, so weigh that against how complex the workflow is.

Prefect

Python-native: decorators turn your functions into flows and tasks. A good fit for data pipelines your Python team already writes. prefect.io

Temporal

Durable execution: a workflow’s state survives crashes and deploys, and it resumes where it stopped. Fits long business processes such as orders and payments. temporal.io

Apache Airflow

Scheduled pipelines written as DAGs in Python, with a large library of integrations. The usual choice for batch data and ETL jobs. airflow.apache.org

How to stop losing tasks between the broker and the worker

Acknowledge tasks late with task_acks_late

Workers stop without warning: deploys, power outages, out-of-memory kills. A task should leave the broker only once a worker has finished it.

Is everything alright?

Broker
eat_cake?

I can handle it!

Worker process
eat_cake
The broker hands the eat_cake task to a worker.

Acknowledging a task means the worker tells the broker, “I’ve got this one, remove it from your queue.” By default (task_acks_late=False), the worker acknowledges a task as soon as it receives it, before running it. If the worker dies halfway through, the task is gone from both sides.

I don't have eat_cake anymore

Broker
eat_cake✕

Not enough RAM!

Worker process
eat_cake✕
Early acknowledgment: the worker runs out of memory, and the broker no longer has the task.

Set task_acks_late=True and the worker acknowledges the task only after running it. If the worker shuts down mid-task, the broker still has it and delivers it again.

I still have eat_cake. I'll redeliver it.

Broker
eat_cake

Not enough RAM!

Worker process
eat_cake
Late acknowledgment: the worker runs out of memory, and the broker redelivers the task.

Why Celery drops tasks that crash a worker

Even with late acknowledgment, Celery drops tasks on purpose when the process running them dies, because task_reject_on_worker_lost defaults to False. That surprises most developers, since it seems to contradict task_acks_late=True.

The two cover different failures. task_acks_late=True redelivers tasks when the whole worker shuts down, as in a deploy or a power outage. task_reject_on_worker_lost=False acknowledges tasks whose child process hits a segmentation fault, runs out of memory or receives a SIGKILL: the parent worker process notices the child was killed and drops its task. Celery does this to avoid a “poison pill”, a task that crashes every worker it reaches and gets redelivered forever.

You can set task_reject_on_worker_lost=True to redeliver those tasks too, but use it with care: if a task keeps crashing workers, you can end up losing more tasks than before. Turn it on only when you’re confident the crashes are transient, such as rare out-of-memory kills, and that a redelivery will succeed.

How redelivery works on RabbitMQ, Redis and SQS

On RabbitMQ, redelivery is automatic. As long as the worker keeps a TCP connection with heartbeats to the broker, RabbitMQ notices when the worker dies and redelivers its unacknowledged tasks.

Redis and SQS have no such signal, so they use a visibility timeout: a task that isn’t acknowledged within that time is delivered again. The default is one hour on Redis and 30 minutes on SQS. Change it with broker_transport_options:

Python
broker_transport_options = {"visibility_timeout": 3600}

The catch is that the timeout fires even if the worker is still running the task. A task that takes longer than the timeout runs twice, which can cause race conditions, resource contention or deadlocks. Raising the timeout for long tasks delays redelivery after a real crash, so you’re trading fast recovery against support for long tasks.

Broker How it redelivers What to watch
RabbitMQ When the worker’s connection drops Durable queues, persistent messages, confirm_publish
Redis When the visibility timeout expires Tasks longer than the timeout run twice; eviction policy
SQS When the visibility timeout expires Tasks longer than the timeout run twice

A lost broker connection is the other way a task runs twice. A worker can’t acknowledge tasks it received over a connection that dropped, so the broker redelivers them while the worker may still be running them. Set worker_cancel_long_running_tasks_on_connection_loss=True to have the worker cancel those tasks instead. It was added in Celery 5.1, is off by default and logs a warning while off, and becomes the default in Celery 6.0.

If you can’t shorten your long tasks, use RabbitMQ, or keep those tasks out of Celery. Keeping task_acks_late=False also avoids duplicates from the visibility timeout, but then a worker crash loses the task, as described above.

Make tasks idempotent and atomic

Redelivery means a task can run more than once, so every task has to be safe to retry. An idempotent task gives the same result whether it runs once or several times with the same arguments.

  • Use idempotent ORM methods, such as get_or_create and update_or_create, so a second run doesn’t duplicate rows. Apply the same rule to calls to external APIs.
  • Wrap database changes in transaction.atomic. If a deploy or a crash interrupts the task, its changes roll back, and the redelivered task starts from a consistent state.
  • Tie side effects you can’t roll back to database state. An email can’t be unsent, so record that it was sent and check that record before sending.
  • Keep tasks short. A short task is less likely to be interrupted, and cheaper to run again.

For more on idempotency and retry patterns, read Advanced Celery: mastering idempotency, retries & error handling.

How to handle task exceptions and retries

Late acknowledgment covers workers that stop, not tasks that fail. If a task raises an exception, such as Cake.DoesNotExist from Cake.objects.get(name="Fantasy Cake"), Celery still acknowledges it and the task is gone. The task_acks_on_failure_or_timeout setting controls this and defaults to True. Leave it as it is, and decide in each task which exceptions to retry.

Handle exceptions in tasks with the same care you give to 500 errors in Django views. For tasks that call external APIs or fail intermittently, use Celery’s automatic retries:

Python
@app.task(
    autoretry_for=(EmailException,),
    max_retries=5,
    default_retry_delay=30,
)
def task_send_activation_email(user_pk):
    ...  # send the activation email

If the task raises EmailException, Celery retries it up to five times, 30 seconds apart, so a passing integration error doesn’t lose the email. To space retries out as failures repeat, retry with exponential backoff.

How to deploy without losing Celery tasks

Change task signatures in two deploys

Tasks already in the queue were serialized with the old arguments. Change task_eat_cake(cake_id) to task_eat_cake(cake_id, person_id) and the new workers fail on every old task still waiting, with errors that are hard to read.

Either drain the queues before you deploy a signature change, or deploy in two steps: ship the new task next to the old one, wait until no task with the old signature is left in the queue, then remove the old task in a second deploy.

Upgrading Celery itself can change the internal task payload format, with the same cryptic errors. Treat upgrades the same way.

Avoid long ETA and countdown tasks

Tasks scheduled with eta or countdown wait in the worker’s memory, not in the broker, until they’re due. A deploy that changes their signature or payload, or a worker that shuts down, can break or lose them. Keep eta and countdown to a few seconds. Retries are ETA tasks behind the scenes, so the same applies to them.

Shut workers down gracefully

When you deploy, you decide how to stop the old workers:

  • Warm shutdown (SIGTERM) waits for running tasks to finish.
  • Cold shutdown (SIGQUIT) tries to requeue unacknowledged tasks (running tasks, when task_acks_late=True) and stops at once. The requeue isn’t guaranteed: race conditions happen (search the Celery and Kombu issue trackers for “unacked”).
  • Soft shutdown, added in Celery 5.5, is a warm shutdown with a time limit. Set worker_soft_shutdown_timeout to the seconds the worker waits before a cold shutdown begins: short tasks get time to finish, and long ones are requeued. Also set worker_enable_soft_shutdown_on_idle so ETA and retry tasks aren’t lost. We recommend it if you can upgrade.

If your deploy sends SIGKILL to the worker processes before any of these shutdowns runs, task_reject_on_worker_lost=False applies and Celery drops the running tasks without redelivery. Sending SIGKILL to the parent worker process before its children keeps redelivery working, but it’s tricky to get right in a deploy script.

After every deploy, check that the old worker processes have stopped and that running and prefetched tasks were redelivered, with extra attention to ETA and retry tasks.

How to keep queues from clogging

Route priority tasks to their own queues

Route urgent tasks to dedicated queues with their own workers, so a backlog of slow work never delays them. We walk through routing slow and memory-heavy tasks, and tuning prefetch for them, in dealing with resource-consuming tasks on Celery.

Set time limits on slow tasks

A task that waits on a slow HTTP request can block a worker for minutes, when a retry would succeed in seconds. Without timeouts, those tasks pile up, stall workers and clog the queues. Set a timeout on every call to an external system, and handle the timeout exception, with a retry if it makes sense.

You can also set a time_limit on a task, or the global task_time_limit setting. Since task_acks_on_failure_or_timeout defaults to True, a task that times out isn’t redelivered.

Expire tasks that no longer make sense

Some tasks shouldn’t run after a certain time: nobody wants a reminder for an event that already happened. Set expires when you queue them, and Celery discards them once they’re stale.

How to monitor Celery tasks

Many teams underestimate how hard it is to monitor a distributed task system until a lost task reaches a customer. Track task performance and failures, alert on failures, and use task traces to find bottlenecks.

Datadog and New Relic integrate with RabbitMQ, Redis and Celery, with performance tracking and task tracing, and there are free and open-source options as well.

Add correlation IDs so you can follow a Django request to the Celery tasks it queued. The django-guid library does this.

Most of this guide comes down to a handful of settings:

Setting Recommended Why
broker_transport_options["confirm_publish"] True (RabbitMQ) The broker confirms it stored each task
task_default_queue_type "quorum" (RabbitMQ cluster, 5.5+) Queued tasks survive the loss of a broker node
task_acks_late True A task leaves the broker only after it runs
task_reject_on_worker_lost False, unless crashes are rare Avoids redelivering a task that crashes workers
task_acks_on_failure_or_timeout True (default) Retries stay an explicit decision in each task
broker_transport_options["visibility_timeout"] Longer than your longest task On Redis and SQS, avoids running a task twice
worker_cancel_long_running_tasks_on_connection_loss True (Celery 5.1+) A lost connection doesn’t leave a task running twice
task_time_limit Set it Stuck tasks don’t block workers
worker_soft_shutdown_timeout A few seconds or more (Celery 5.5+) Deploys let short tasks finish and requeue long ones
worker_enable_soft_shutdown_on_idle True (Celery 5.5+) ETA and retry tasks survive a deploy

For the complete list, with commentary on each setting, see our recommended Celery settings for Django projects.

None of these failures shows up in development, where the broker never restarts and no deploy interrupts a worker. Put these settings and habits in place before the first lost task reaches a user, and Celery stays the dependable task queue it is meant to be.

Frequently asked questions

What is Celery used for in Django?

Celery runs work outside Django’s request and response cycle: sending emails, calling slow external APIs, processing files and running scheduled jobs. Django queues a task on a broker such as RabbitMQ or Redis, and a separate worker process runs it, so the user doesn’t wait. Read how Celery’s brokers, workers and result backends fit together.

Why are my Celery tasks getting lost?

Usually for one of four reasons: the broker didn’t store the task (turn on confirm_publish on RabbitMQ), Redis evicted it under memory pressure, a worker died after acknowledging it (set task_acks_late=True), or the task raised an exception and Celery acknowledged it anyway. Deploys that kill workers without a graceful shutdown are a fifth common cause.

What does task_acks_late do in Celery?

It makes the worker acknowledge a task after running it instead of before. If the worker shuts down mid-task, the broker still has the task and delivers it again. The trade-off is that tasks can run more than once, so they must be idempotent.

What does task_reject_on_worker_lost do?

It decides what happens to a task when the child process running it dies from a segmentation fault, an out-of-memory kill or a SIGKILL. It only matters with task_acks_late=True. By default (False), Celery acknowledges and drops the task, so a task that crashes every worker can’t be redelivered forever. Set it to True to redeliver those tasks, but only when the crashes are rare and a retry will succeed.

Why does Celery run the same task twice?

Either a worker died before acknowledging the task and the broker redelivered it, or, on Redis and SQS, the task ran longer than the visibility timeout and the broker assumed it was lost. Make tasks idempotent, and set the visibility timeout longer than your longest task.

Is RabbitMQ or Redis more reliable as a Celery broker?

RabbitMQ, for reliability. It redelivers a task as soon as the worker’s connection drops, supports publisher confirms, and has no visibility timeout that can run long tasks twice. Redis works well too, with a non-evicting memory policy, an instance of its own and a visibility timeout longer than your longest task.

How do I queue a Celery task after the Django transaction commits?

Wrap the call in transaction.on_commit(lambda: my_task.delay(arg)), or, on Celery 5.4 or newer with DjangoTask, call my_task.delay_on_commit(arg). Either way, the worker can’t run the task before the data it needs is committed.

How do I deploy Django without losing Celery tasks?

Use a soft shutdown (Celery 5.5 or newer) or a warm shutdown, so running tasks finish or are requeued, never a bare SIGKILL. Ship task signature changes in two deploys, and avoid long eta and countdown tasks, which wait in worker memory.

Should I use Celery Canvas for complex workflows?

We don’t recommend it. Chains, groups and chords can lose tasks in ways that are hard to detect, and errors inside them are hard to handle. For long workflows or data pipelines, use an orchestrator such as Temporal, Prefect or Apache Airflow.

References

Book a call

Ready for software that finally fits?

Bring us your care model and find the right technical partner to build it with you.