Celery Retry with Exponential Backoff in Django
Learn Celery retry with exponential backoff in Django: autoretry_for, retry_backoff, jitter, max_retries, idempotency, failure handling, and common mistakes
Introduce
Background tasks fail. An email provider returns a 503, a payment API times out, the database drops a connection during a deploy, or a third-party service starts rate limiting you. Most of these failures are temporary, and the right response is not to give up. It is to try again.
But how you try again matters. Retry immediately and repeatedly, and you hammer a service that is already struggling, which can turn a small outage into a big one. The standard solution is exponential backoff with jitter: wait a little before the first retry, longer before the second, longer again before the third, and add some randomness so thousands of tasks do not all retry at the same instant.
This guide shows how to implement Celery retry with exponential backoff in Django, from the one-line built-in option to full manual control, and covers the mistakes that cause retry storms, duplicate side effects, and silently lost tasks.
Why Not Just Retry Immediately?
Imagine 5,000 tasks calling an API, and the API goes down for 30 seconds. With a fixed retry delay of 5 seconds, all 5,000 tasks fail together, wait 5 seconds, and all retry together. The API, which may be trying to recover, gets hit by the same spike again, and again, every 5 seconds. This is called a retry storm or the thundering herd problem.
Exponential backoff fixes two things:
- Increasing delays give the failing service time to recover. Waits grow like 1s, 2s, 4s, 8s, 16s, and so on.
- Jitter spreads the retries over time by adding randomness, so tasks that failed together do not retry together.
The Basic Tool: self.retry()
Celery's lowest-level retry mechanism is self.retry(). You mark the task with bind=True so it has access to itself, catch the exception, and ask Celery to run the task again later:
import requests
from celery import shared_task
@shared_task(bind=True, max_retries=5)
def sync_order_to_crm(self, order_id):
order = Order.objects.get(pk=order_id)
try:
response = requests.post(CRM_URL, json=order.to_payload(), timeout=10)
response.raise_for_status()
except requests.RequestException as exc:
raise self.retry(exc=exc, countdown=30)
Three details matter here:
raise self.retry(...): raising it makes sure the code after it does not keep running, and it signals Celery to reschedule the task.countdown: the number of seconds to wait before the next attempt.max_retries: the default is 3. When the limit is reached, Celery re-raises the original exception, if you passedexc=, so the task ends as failed and you can see why.
With a fixed countdown=30, though, every retry waits the same time. That is not backoff yet.
Manual Exponential Backoff with Jitter
To grow the delay, use self.request.retries, which holds how many times this task has already been retried:
import random
import requests
from celery import shared_task
@shared_task(bind=True, max_retries=6)
def sync_order_to_crm(self, order_id):
order = Order.objects.get(pk=order_id)
try:
response = requests.post(CRM_URL, json=order.to_payload(), timeout=10)
response.raise_for_status()
except requests.RequestException as exc:
base_delay = 2 ** self.request.retries # 1, 2, 4, 8, 16, 32
delay = min(base_delay * 10, 600) # scale up, cap at 10 minutes
delay = random.uniform(delay / 2, delay) # add jitter
raise self.retry(exc=exc, countdown=delay)
This gives waits that start around 5 to 10 seconds, then roughly 10 to 20, 20 to 40, and so on, never exceeding 10 minutes. The cap matters: without it, the sixth retry could wait many minutes and the tenth could wait hours.
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
Manual control is useful when you need custom rules, such as reading a Retry-After header from the API response. For most tasks, though, Celery can do all of this for you.
The Easy Way: autoretry_for and retry_backoff
Celery has built-in options that implement exponential backoff with jitter in a single decorator:
import requests
from celery import shared_task
@shared_task(
autoretry_for=(requests.RequestException,),
retry_backoff=True,
retry_backoff_max=600,
retry_jitter=True,
max_retries=6,
)
def sync_order_to_crm(order_id):
order = Order.objects.get(pk=order_id)
response = requests.post(CRM_URL, json=order.to_payload(), timeout=10)
response.raise_for_status()
There is no try/except and no self.retry(). Here is what each option does:
autoretry_for: a tuple of exception types that should trigger a retry. Any other exception fails the task immediately.retry_backoff:Trueuses a 1-second base, so delays follow 1, 2, 4, 8 seconds and so on. An integer sets the base factor, soretry_backoff=3gives 3, 6, 12, 24 seconds.retry_backoff_max: the largest delay allowed, in seconds. The default is 600 (10 minutes).retry_jitter: whenTrue(the default), Celery picks a random delay between 0 and the computed backoff value. This is "full jitter", and it spreads retries effectively, though an individual retry can happen sooner than the nominal backoff.max_retries: how many retries before giving up. The default is 3, andNonemeans retry forever, which is rarely a good idea.
You can set these defaults for every task in your project, then override them per task:
## celery.py
app = Celery("config")
app.conf.task_annotations = {
"*": {
"retry_backoff": True,
"retry_backoff_max": 600,
"retry_jitter": True,
"max_retries": 5,
}
}
Keep in mind that autoretry_for only applies to tasks that list the exceptions. Tasks without it still fail immediately.
Decide What Deserves a Retry
The most important design decision is not the delay formula. It is which failures to retry. Retrying a permanent error just wastes time and load.
| Retry (transient) | Do not retry (permanent) |
|---|---|
| Connection errors and timeouts | ValueError, bad input data |
| HTTP 429 (rate limited) | HTTP 400, 401, 403, 404 |
| HTTP 502, 503, 504 | Model.DoesNotExist for a deleted record |
| Temporary database errors, such as a dropped connection or a serialization failure | Validation and business rule errors |
| Lock contention | Programming bugs such as TypeError |
Be specific in autoretry_for:
@shared_task(
autoretry_for=(requests.ConnectionError, requests.Timeout),
retry_backoff=True,
max_retries=5,
)
def call_partner_api(payload):
...
requests.RequestException is broad, and it also covers HTTPError raised by raise_for_status() for 404 responses, which will never succeed on retry. If you need to retry only some HTTP errors, use the manual approach and inspect the status code:
@shared_task(bind=True, max_retries=5)
def call_partner_api(self, payload):
try:
response = requests.post(PARTNER_URL, json=payload, timeout=10)
except (requests.ConnectionError, requests.Timeout) as exc:
raise self.retry(exc=exc, countdown=min(2 ** self.request.retries * 5, 600))
if response.status_code in (429, 502, 503, 504):
retry_after = response.headers.get("Retry-After")
delay = int(retry_after) if retry_after and retry_after.isdigit() else min(2 ** self.request.retries * 5, 600)
raise self.retry(countdown=delay)
response.raise_for_status() # 4xx: fail now, do not retry
return response.json()
Respecting Retry-After is good etiquette and often the fastest way to recover, because the service tells you exactly how long to wait.
Make Retried Tasks Idempotent
A retry means the task body runs more than once. If the first attempt got halfway, for example it sent the request and the connection died before the response arrived, the retry may repeat a side effect. Charging a card twice or sending the same email twice are the classic examples.
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
The protection is the same as for any duplicate execution:
- Compute values from source data instead of incrementing them.
- Store a processed flag or an idempotency key and check it before acting.
- Pass an idempotency key to external APIs that support one, and reuse the same key across retries.
- Use a database unique constraint as a safety net.
@shared_task(
autoretry_for=(requests.ConnectionError, requests.Timeout),
retry_backoff=True,
max_retries=5,
)
def charge_customer(order_id):
order = Order.objects.get(pk=order_id)
if order.paid_at:
return # a previous attempt already succeeded
response = requests.post(
PAYMENTS_URL,
json={"amount": str(order.total)},
headers={"Idempotency-Key": f"order-{order.pk}"},
timeout=10,
)
response.raise_for_status()
order.paid_at = timezone.now()
order.save(update_fields=["paid_at"])
I covered this topic in depth in a separate guide, linked in the related reading section below. Idempotency is what makes retries safe.
Handle the Final Failure
Retries are not infinite. When max_retries is exhausted, the task fails, and if nothing watches for that, the work is silently lost. Plan for it:
from celery import Task
class NotifyOnFailureTask(Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
# Log it, alert your team, or mark the record as failed
Order.objects.filter(pk=args[0]).update(sync_status="failed")
@shared_task(
base=NotifyOnFailureTask,
autoretry_for=(requests.RequestException,),
retry_backoff=True,
max_retries=5,
)
def sync_order_to_crm(order_id):
...
Useful options for failures that exhaust retries:
- Record a "failed" status on the database row so users and admins can see it, and so you can requeue later.
- Send the error to Sentry or your logging system, with the task name and arguments.
- Store failed jobs in a table so a person or a scheduled job can replay them once the problem is fixed.
Retry Settings That Interact with Your Broker
Retries with a countdown are scheduled using an ETA, and how that behaves depends on your broker.
- Redis visibility timeout. With Redis, scheduled tasks are held by a worker until their time comes, and an unacknowledged message becomes visible again after the visibility timeout (one hour by default). If your backoff delays can exceed it, set
visibility_timeouthigher, or keepretry_backoff_maxcomfortably below it. Otherwise a task can be delivered twice. - Many waiting tasks. Large numbers of ETA tasks sit in worker memory. If thousands of tasks all retry with long delays, workers hold them all. Keep delays and the number of retries reasonable.
acks_lateand worker crashes. Withacks_late=True, a task whose worker dies is redelivered. That is a separate kind of "retry" that Celery does not count inmax_retries, which is one more reason to keep tasks idempotent.
CELERY_BROKER_TRANSPORT_OPTIONS = {"visibility_timeout": 43200} # 12 hours
Use transaction.on_commit() When Queuing
A subtle cause of pointless retries: a task starts before the data it needs is committed, fails with DoesNotExist, and retries until the commit lands. Queue after the commit instead:
from django.db import transaction
def create_order(request):
with transaction.atomic():
order = Order.objects.create(...)
transaction.on_commit(lambda: sync_order_to_crm.delay(order.pk))
Retrying a DoesNotExist as a way to wait for a commit works, but it wastes retries and hides the real problem.
Keep Retrying Tasks Cheap and Safe
A few habits keep retries from causing new problems:
- Set timeouts on every external call. A request with no timeout can hang forever and never reach your retry logic.
- Set time limits.
soft_time_limitandtime_limitstop stuck tasks from holding workers. - Do not hold database transactions open across network calls. Open connections during slow retries and waits add pressure on your pool.
- Retry the small unit. If a big job fails halfway, retrying the whole thing repeats work. Split big jobs into small chunks so only the failed chunk retries.
- Rate limit when appropriate.
rate_limit="10/s"on a task can keep retries from overwhelming a partner API.
Testing Retry Behavior
Test the logic without waiting for real delays. One approach is to call the task directly and mock the failing call:
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
from unittest.mock import patch
import requests
from celery.exceptions import Retry
def test_sync_retries_on_timeout():
with patch("orders.tasks.requests.post", side_effect=requests.Timeout):
with pytest.raises(Retry):
sync_order_to_crm.apply(args=[1], throw=True)
You can also use task.retry assertions with unittest.mock, and test the exhausted case by setting max_retries=0 or by simulating the retry counter. Whatever approach you choose, test at least three paths: success, a retryable failure, and a permanent failure that must not retry.
Common Mistakes to Avoid
- Retrying everything. Catching
Exceptionretries bugs and bad input along with transient errors. - Fixed delays without jitter. This invites retry storms.
- No cap on the delay. Exponential growth with no
retry_backoff_maxgives retries hours apart. max_retries=Nonewith no alerting. A permanently failing task retries forever and nobody notices.- Non-idempotent tasks. Retries repeat side effects.
- No handler for the final failure. The work disappears quietly.
- Retry delays longer than the Redis visibility timeout. This causes duplicate delivery.
- No timeouts on external calls. The task hangs and never retries.
Which Approach Should You Use?
| Situation | Approach |
|---|---|
| Simple tasks calling an API | autoretry_for + retry_backoff + retry_jitter |
| Need to retry only certain status codes | Manual self.retry() with checks |
Need to honor Retry-After |
Manual self.retry(countdown=...) |
| Same defaults across the whole project | task_annotations in Celery config |
| Need to react when retries run out | Custom Task with on_failure |
| Side effects that must not repeat | Idempotency keys and database constraints |
Related Reading: Build Reliable Background Jobs
Retries are one piece of reliable background processing. These guides cover the pieces around them:
- If a retry might repeat a side effect: Celery: How to Prevent Duplicate Task Execution explains idempotency, locks, and idempotency keys, which are exactly what make retried tasks safe.
- If your tasks process huge datasets: How to Process 5 Million Records with Django and Celery shows how to split work into small chunks, so only the failed chunk needs a retry instead of the whole job.
- If retries pile up database connections: Django Database Connection Pooling with PostgreSQL explains how to size connections across web and Celery workers, which matters when many tasks wait and retry at once.
- If tasks fail because queries are slow: Django ORM Optimization for Millions of Records covers the indexes and query habits that remove a common cause of timeouts.
- If a task fetches related objects in a loop: select_related vs prefetch_related: Practical Examples helps you avoid N+1 queries that make tasks slow and more likely to hit time limits.
A Quick Checklist
Before shipping a Celery task that retries, confirm that:
- Only transient errors are listed in
autoretry_for retry_backoff,retry_backoff_max, andretry_jitterare setmax_retriesis a sensible, finite number- The task is idempotent, or uses an idempotency key
- External calls have timeouts
- The final failure is logged, alerted, or recorded
- Backoff delays stay below the broker's visibility timeout
- The task is queued with
transaction.on_commit()when it depends on fresh data - You tested success, retryable failure, and permanent failure
Conclusion
Retries are what turn a flaky network into a reliable system, but only when they are done carefully. Retry only transient failures, increase the delay exponentially, add jitter so tasks do not retry in lockstep, cap the delay, and limit the number of attempts. Make every task safe to run twice, and make sure the final failure is visible instead of silent.
For most tasks, a few lines of autoretry_for, retry_backoff, and retry_jitter give you everything you need. Reach for manual self.retry() when you need finer control, such as honoring Retry-After or retrying only specific status codes.
Frequently Asked Questions
How do I add exponential backoff to a Celery task?
Use autoretry_for with the exceptions to retry, and set retry_backoff=True. Add retry_backoff_max to cap the delay, retry_jitter=True to randomize it, and max_retries to limit attempts. For manual control, call self.retry(countdown=...) using self.request.retries to grow the delay.
What is the default number of retries in Celery?
The default max_retries is 3. After that, Celery stops retrying and the task fails. Setting max_retries=None retries forever, which is rarely a good idea.
What does retry_jitter do in Celery? It adds randomness to the backoff delay. When enabled, Celery picks a random delay between 0 and the calculated backoff value, so many tasks that failed at the same time do not all retry at the same moment.
What is the difference between autoretry_for and self.retry?
autoretry_for is declarative: you list exception types and Celery retries automatically with backoff options. self.retry() is manual: you catch the exception yourself and decide the delay and conditions, which is useful for checking status codes or reading a Retry-After header.
Should I retry every exception in Celery? No. Retry transient failures such as timeouts, connection errors, and rate limiting. Do not retry permanent errors such as invalid input, missing records, or 4xx responses, because they will fail every time.
Why did my retried Celery task run twice?
Possible causes include retries repeating a side effect from a partially finished attempt, a Redis visibility timeout shorter than your retry delay, or a worker crash with acks_late enabled. Make tasks idempotent and keep backoff delays below the visibility timeout.
