Celery Task Retry With Backoff
Configure Celery tasks with retry backoff jitter and max attempts for resilient async jobs.
Code
from celery import Celery
from celery.exceptions import Retry
import random
app = Celery('tasks', broker='redis://localhost:6379')
@app.task(bind=True, max_retries=5)
def process_data(self, payload):
try:
return do_work(payload)
except Exception as exc:
raise self.retry(
exc=exc,
countdown=int(2 ** self.request.retries * (1 + random.random())),
)How the snippet works
The working surface is the function process_data — everything else is wiring.
The import line is the dependency contract: Celery, Retry come from celery and nothing else. self appears at a raise inside an except handler — it fires only while that failure type is already being handled.
Caveats
- Plan for an install step:
celeryis a real dependency, resolved by the package manager.
Applying it
Signature: def process_data(self, payload)
process_data is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def process_data(self, payload):
try:
return do_work(payload)
except Exception as exc:
raise self.retry(
exc=exc,
countdown=int(2 ** self.request.retries * (1 + random.random())),
)
Interactive Tools for This Topic
FAQ
- When is the exception raised?
- Inside an `except` handler — the `self` fires only while that failure type is already being handled, not on its own trigger.
- What does this need from the package registry?
- These are real dependencies: `celery`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.