Skip to content

Advanced Celery: mastering idempotency, retries & error handling

Blueprint drawing of a press on a conveyor of celery: sprigs loop back on the belt under retry_backoff, a gauge on top reads soft_time_limit, and the pressed bunches land tied together in a bin marked idempotency

A production-ready Celery task is idempotent and atomic, so it can run again without corrupting data. It retries failures of external services with exponential backoff, stops at a time limit, logs what it does and alerts your team when it fails. The difference between a working async task and a production-ready one comes down to how it handles network outages, race conditions and partial failures.

If you’ve got some experience under your belt, this post is tailored just for you. If you’re new to Celery, start with my previous post for a solid foundation; if your problem is tasks that disappear between Django, the broker and the worker, read how to stop losing Celery tasks. Here, I cover the habits that make each task safe to rerun, starting with two crucial concepts: idempotency and atomicity.

Key takeaways

Make tasks idempotent

Running a task twice should leave the same result as running it once, so a retry can’t corrupt your data.

Make tasks atomic

Make the external call first and save all changes together. Keep tasks short: one email per task, not one task for every user.

Retry with backoff

Retry failures from external services with autoretry_for and retry_backoff, so a struggling API gets time to recover. Keep retry_backoff_max low: a waiting retry lives in the worker’s memory.

Set time limits

Use soft_time_limit to clean up and time_limit to stop a task stuck on a bug or a slow network.

Monitor and alert

Log each task without sensitive data, send failures to Sentry or Slack, and tune alerts so real errors stand out.

Test the task, then the worker

Unit-test the task’s function directly and mock delay. Test with a real worker through celery.contrib.pytest. task_always_eager only emulates a worker, so keep it out of unit tests and production.

What is idempotency in Celery tasks?

In mathematics and computer science, idempotency refers to a remarkable property of certain operations. It’s all about the idea that you can apply these operations multiple times. The result remains unchanged beyond the initial application.

It is the math equivalent of multiplying a number by zero or one. No matter how often you do it, the result stubbornly stands.

For instance, consider the simple operation of multiplying by zero, f(x) = x × 0. Applying it once or many times gives the same result:

Text
f(3) = 0    f(f(3)) = 0    f(f(f(3))) = 0

It’s the same story with multiplication by one, g(x) = x × 1:

Text
g(3) = 3    g(g(3)) = 3    g(g(g(3))) = 3

Now, let’s shift our focus to the realm of HTTP, where we’re faced with different methods, each with its own idempotent or non-idempotent nature.

  • GET: When you GET a resource, it should not produce any changes to it, making it an idempotent operation.
  • POST: POST is commonly used for resource creation. Unlike GET, it’s generally not idempotent. Every POST request may change the state of the application, meaning whoever uses POST shouldn’t count on its idempotency.
  • PUT: This is a prime example of an idempotent operation that’s not simply a read. The first PUT request produces a change in the state, but repeating the same request won’t introduce any further changes. It’s like a create-update operation in the same method.
  • DELETE: It’s idempotent too, even though the responses can differ: the first call might return a 204 status code, while subsequent calls might return a 404. In HTTP, idempotency is about the server’s state, not the response (RFC 9110), and the resource is gone after one call or many.

Diagram of HTTP methods: PATCH, CONNECT and POST are unsafe; GET, TRACE, OPTIONS and HEAD are idempotent; PUT and DELETE are both unsafe and idempotent

How to make a Celery task idempotent

For a Celery task, idempotency means that running it twice with the same arguments leaves the same result as running it once. Celery can run a task more than once: a retry, a redelivery after a worker shuts down, or someone rerunning a failed task by hand. A few ways to make that safe:

  • Let the database refuse duplicates. A unique constraint on the rows the task creates, written with get_or_create or update_or_create, turns a second run into a no-op instead of a duplicate.
  • Give each operation an idempotency key. Identify the operation (an order ID, say), record it when the work is done, and skip the work when the record already exists. Some APIs, such as Stripe’s, accept the same kind of key, so a repeated call doesn’t charge twice.
  • Lock the row while you check it. Two copies of a task can run at the same time. Read the row with select_for_update() inside transaction.atomic(), so the second copy waits for the first and then sees the work is done.
Python
from django.db import transaction
from django.utils import timezone

@app.task
def charge_order(order_id):
    with transaction.atomic():
        order = Order.objects.select_for_update().get(pk=order_id)
        if order.charged_at:
            return  # an earlier run already charged it
        payment_api.charge(order.total, idempotency_key=f"order-{order_id}")
        order.charged_at = timezone.now()
        order.save(update_fields=["charged_at"])

Our guide to reliable Celery tasks covers side effects you can’t roll back, such as emails, in more depth.

What is atomicity in Celery tasks?

Atomicity is a concept with roots in database operations and various other contexts. It’s about an indivisible and irreducible series of operations in which either everything occurs successfully or nothing changes.

Consider a scenario where you have a Celery task called update_data. In this task, the user’s status is set to updated, then saved, followed by a request to an external profile API, and finally, the user’s name is updated and saved again. Sounds like a logical sequence, right? However, it’s not atomic.

If that request fails, you’re left with an inconsistent database state: a user with status=updated but an outdated name. To make this atomic, the right approach is first to make the request and then update the user’s status and name together.

Here’s the improved task:

Python
import requests
from django.db import transaction

@app.task
def update_data(user_id):
    response = requests.get(f"{PROFILE_API_URL}/users/{user_id}", timeout=10)
    response.raise_for_status()  # fail loudly, so the task can be retried
    profile = response.json()

    with transaction.atomic():
        user = User.objects.get(pk=user_id)
        user.name = profile["name"]
        user.status = "updated"
        user.save()

Now, it’s atomic: the request runs before any change, and transaction.atomic saves every change or none. A failed request raises an exception instead of returning quietly, so the failure reaches your monitoring and the task can be retried, as we’ll see below.

Another strategy to enhance atomicity is to keep your tasks short. Consider an example of sending newsletters to all users within a single task. If one fails, the entire task will fail, too, resulting in partial email delivery and no information about who missed out.

Instead of doing it all in one task, you can delegate the email sending to another task:

Python
@app.task
def send_newsletter(email):
    send(email, 'newsletter')

@app.task
def newsletter():
    users = all_users()
    for u in users:
        send_newsletter.delay(u.email)

This refactored approach ensures that if an email fails to send, it only affects one user. Moreover, it’s easier to identify and rerun the failed tasks. However, it’s essential to be mindful of task granularity, as overly fine-grained tasks can impact performance due to Celery’s overhead on each task execution. And newsletter itself still has to be safe to rerun: if it fails halfway and runs again, record each email sent and check that record, or some users get the newsletter twice.

If you queue tasks from code that runs inside a database transaction, such as a Django view with ATOMIC_REQUESTS, queue them with transaction.on_commit or, on Celery 5.4 or newer with its Django task class (DjangoTask), delay_on_commit(). Otherwise the worker can run the task before the data it needs is committed. Our reliability guide explains this race.

Now that we’ve established a solid grasp of idempotency and atomicity, let’s explore strategies and Celery-specific features to enhance our async task writing skills further.

The guidebook for software engineers ready to level up. Learn more about the book Strategic Software Engineering.

The guidebook for software engineers ready to level up. Learn more about the book Strategic Software Engineering.

How to retry Celery tasks with exponential backoff

Tasks fail, and that’s where the concepts of idempotency and atomicity come into play: tasks that embody both these principles can be rerun multiple times without any risk of introducing inconsistencies.

Diagram: a client request to the server fails and is retried, then the server writes to the database

Now, let’s delve into the primary reasons tasks might fail. There are two main culprits: bugs in your code and hiccups in your interactions with external systems.

When it comes to bugs in your code, you’re in control. You can deploy a fix and manually rerun the task to resolve the issue. However, when the trouble comes from external systems behaving unexpectedly, a different strategy is required. In such cases, it’s beneficial to keep retrying the task until the external service gets back on track.

For this purpose, Celery provides a handy retry functionality that can be employed within a task. This allows you to define the situations in which the task should be automatically re-executed.

Here’s a practical example:

Python
import requests

@app.task(bind=True, max_retries=4, default_retry_delay=10)
def fetch_user_likes(self, user_id):
    try:
        response = requests.get(f"{LIKES_API_URL}/users/{user_id}/likes", timeout=10)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise self.retry(exc=exc)
    return response.json()

In this example, we attempt to fetch a user’s likes from an external API. If the request fails, we introduce a 10-second delay and then retry it up to 4 times. self.retry() raises an exception itself, so write it as raise self.retry(...), which makes clear that no code after it runs.

If your tasks adhere to the principles of idempotency and atomicity, you can confidently use the retry method as many times as necessary until the task succeeds. However, be cautious, as retrying in non-idempotent and non-atomic tasks may result in inconsistencies or worse side effects, such as flooding your users with repeated emails.

When retrying tasks, there are a few considerations to keep in mind. In some cases, the failure might be due to an external service, such as a third-party API, being down. In such situations, it’s wise to implement a backoff mechanism, giving the external APIs some time to recover.

Furthermore, extending the interval between retries by an exponential amount can enhance the odds of completing the task successfully on the next attempt. Introducing a random factor to the retry delay can also help prevent overwhelming the external system.

Celery does both for you. autoretry_for lists the exceptions that retry a task, and retry_backoff, available since Celery 4.2, spaces the retries out exponentially:

Python
import requests

@app.task(
    autoretry_for=(requests.RequestException,),
    max_retries=5,
    retry_backoff=True,
    retry_backoff_max=60,
)
def fetch_user_likes(user_id):
    response = requests.get(f"{LIKES_API_URL}/users/{user_id}/likes", timeout=10)
    response.raise_for_status()
    return response.json()

With retry_backoff=True, the first retry waits up to 1 second, the second up to 2, then 4, 8 and so on, never more than retry_backoff_max. retry_jitter, on by default, picks a random delay between zero and that value, so tasks that failed together don’t all retry at the same moment. Set retry_backoff to a number, such as 3, to start from that many seconds instead.

Keep retry_backoff_max low. Its default is 600 seconds, but a retry is a task with a countdown, and it waits in the worker’s memory until it’s due: a deploy or a worker restart in the meantime can lose it. Our reliability guide explains why to keep countdowns short. If an API can be down for longer than a minute or two, let the task fail after its last retry, alert on it, and rerun it once the API is back.

When to enable late acknowledgment (acks_late)

A crucial aspect to be aware of is acks_late. By default, Celery acknowledges a task’s message to the broker right after the worker receives it, before running it. If the worker shuts down mid-task, the broker won’t deliver the task again, so it doesn’t run twice: a sound default behavior for non-idempotent tasks.

However, if you’re actively designing idempotent and atomic tasks, enabling the task_acks_late setting won’t harm your application. It will enhance its robustness against worker shutdowns caused by problems like cloud container restarts, deployments, or even random bugs in Celery or Python. You can also configure acks_late on a per-task basis.

Python
@app.task(acks_late=True)
def my_task():
    ...

Two details still apply with late acknowledgment. If the process running a task is killed, by an out-of-memory error or a SIGKILL, Celery acknowledges the task anyway unless you enable task_reject_on_worker_lost. And on Redis and SQS, a task that isn’t acknowledged within the broker’s visibility timeout is delivered again, even while it’s still running. Our reliability guide covers both.

How to set time limits on Celery tasks

Another common issue in async tasks is dealing with tasks that run for extended durations due to bugs or network latency. To prevent these lengthy tasks from adversely affecting your application’s performance, you can set task_time_limit (or time_limit on a single task). Celery terminates a task that exceeds the specified time limit.

If you need to perform some recovery operations before the task is terminated, you can also set task_soft_time_limit (soft_time_limit on a single task). When this soft time limit is reached, Celery raises a SoftTimeLimitExceeded exception, allowing you to perform cleanup operations.

Here’s an example of how to implement task time limits:

Python
from celery.exceptions import SoftTimeLimitExceeded

@app.task(time_limit=60, soft_time_limit=50)
def my_task():
    try:
        possibly_long_task()
    except SoftTimeLimitExceeded:
        recover()

How to monitor Celery tasks and get alerted

Monitoring async tasks requires a different level of vigilance compared to web applications. While web application errors are often noticeable because they lead to visible issues, async tasks don’t always have such an immediate impact on the user experience. This highlights the importance of robust monitoring to catch errors early, preventing them from snowballing into major problems.

Comprehensive logging is essential, starting with the basics. Proper logging provides a detailed record of what transpired during task execution, aiding in debugging. However, exercise caution to avoid exposing sensitive information in logs, as it can pose a security and privacy issue to your users’ data. Logging is a general recommendation for all applications, but it’s particularly critical for tasks, as there’s no user interface for debugging.

Here’s an example of setting up logging in a Celery task:

Python
from celery.utils.log import get_task_logger

logger = get_task_logger(__name__)

@app.task
def add(a, b):
    logger.info('Adds %s + %s', a, b)
    return a + b

Beyond logging, ensuring your team is promptly notified when tasks fail is imperative. Tools like Sentry can be easily integrated with Django and Celery to facilitate error monitoring. Integration with communication platforms like Slack ensures you receive notifications whenever something goes awry.

However, it’s crucial to fine-tune the notification settings to avoid excessive false positives, which might lead your team to overlook real errors. Establish a straightforward process for handling errors and ensure they are prioritized and included in your backlog whenever new ones arise.

Apart from these strategies, many other tools are available for monitoring tasks. Two examples commonly used in various projects are:

  1. Flower: This tool enables live monitoring of Celery tasks, allowing you to inspect running tasks and track completed ones. It’s a standalone application and particularly beneficial for larger systems.
  2. django-celerybeat-status: This tool integrates with the Django admin interface, providing a view of all scheduled tasks along with their next Estimated Time of Arrival (ETA). This can help reduce confusion and errors when working with crontab schedules.

How to test and debug Celery tasks

Testing and debugging async tasks can be more challenging than testing and debugging typical web applications. However, there are strategies to mitigate these challenges.

For unit tests, call the task’s function directly, as you would any other function: add(2, 3) runs it in the test’s process, with no broker or worker. In the code that queues the task, mock delay or apply_async and check that it was called with the right arguments. To test with a real worker, enable Celery’s pytest plugin (pytest_plugins = ("celery.contrib.pytest",)): its celery_worker fixture starts a worker in a separate thread for the test.

You may come across the task_always_eager setting. When it’s set to True, calling delay or apply_async runs the task synchronously instead of sending it to a worker. Celery’s testing guide calls it “by definition not suitable for unit tests”: it skips the broker and the worker, so it hides serialization errors, routing and acknowledgment, the behavior this post is about. It can help when debugging locally, together with task_eager_propagates = True so exceptions surface. Never turn it on in production.

Conclusion

In the end, building resilient async tasks is more art than science. It’s about anticipating what could go wrong and methodically preparing for it. By implementing the practices we’ve discussed, from idempotent task design to comprehensive monitoring, you’ll be well-equipped to handle the complexities of distributed systems.

Remember, it’s not just about writing code that works; it’s about crafting solutions that gracefully recover from the inevitable stumbles. Whether you’re dealing with network hiccups or system crashes, these battle-tested strategies will help ensure your async tasks remain reliable and maintainable in production environments. Building robust async architectures is a journey. If you’re looking to strengthen your Celery foundations, our Django + Celery articles are the perfect next step.

You may also like: Vinta promoted this workshop on how to boost Django projects with Celery.

Learn what truly makes a software engineer stand out. Learn more about the book Strategic Software Engineering.

Learn what truly makes a software engineer stand out. Learn more about the book Strategic Software Engineering.

References

Article · 16 min read

Reliable Celery tasks in Django: how to stop losing them

Where Celery tasks get lost in a Django app, and the settings and habits that keep them running through broker failures, crashes and deploys.

Flávio Juvenal16 min read

Article · 8 min read

What is Celery in Python? Brokers, workers and result backends

How Celery runs Python tasks in the background, from the broker and the workers to the backend that stores their results.

Filipe Ximenes8 min read

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.