Celery Task Retry Backoff Jitter
Retry failing Celery tasks with exponential backoff and jitter, capping max delay, classifying retryable exceptions, and exposing stats.
Code
import random
from celery import Celery
app = Celery('shipping', broker='redis://localhost:6379/1')
app.conf.update(
task_acks_late=True,
worker_prefetch_multiplier=1,
task_reject_on_worker_lost=True,
)
class CarrierUnavailable(Exception):
pass
@app.task(
bind=True,
max_retries=5,
autoretry_for=(CarrierUnavailable,),
retry_backoff=2,
retry_backoff_max=600,
retry_jitter=True,
)
def book_shipment(self, order_id: str, carrier: str):
try:
if random.random() < 0.5:
raise CarrierUnavailable(f'{carrier} api warming up')
return {'order': order_id, 'carrier': carrier, 'tracking': 'TRK-88'}
except CarrierUnavailable as exc:
countdown = min(2 ** self.request.retries * 2, 600)
countdown += random.uniform(0, countdown * 0.3)
raise self.retry(exc=exc, countdown=countdown)
@app.task
def shipment_stats():
inspector = app.control.inspect()
active = inspector.active() or {}
reserved = inspector.reserved() or {}
return {
'active_tasks': sum(len(w) for w in active.values()),
'reserved_tasks': sum(len(w) for w in reserved.values()),
}What the code does
Count the class CarrierUnavailable and the functions book_shipment and shipment_stats as the entire surface area of Celery Task Retry Backoff Jitter.
The import line is the dependency contract: Celery comes from celery and nothing else. A CarrierUnavailable and self is raised inside an except block, so it is conditional on that failure being handled in the first place.
The result is a fresh construction, so callers can keep their originals.
Watch out for
- Plan for an install step:
celeryis a real dependency, resolved by the package manager. - The guard
random.random() < 0.5short-circuits the flow with an earlyraisewhen its condition holds.
Applying it
Entry signature: def book_shipment(self, order_id: str, carrier: str)
Import book_shipment from the file and call it — the rest of the code is implementation detail.
Statements that matter
return {'order': order_id, 'carrier': carrier, 'tracking': 'TRK-88'}
countdown += random.uniform(0, countdown * 0.3)
raise self.retry(exc=exc, countdown=countdown)
@app.task
def shipment_stats():
inspector = app.control.inspect()
active = inspector.active() or {}
except CarrierUnavailable as exc:
countdown = min(2 ** self.request.retries * 2, 600)
countdown += random.uniform(0, countdown * 0.3)
raise self.retry(exc=exc, countdown=countdown)
Interactive Tools for This Topic
FAQ
- Does `book_shipment` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- When is the exception raised?
- Inside an `except` handler — the `CarrierUnavailable` and `self` fires only while that failure type is already being handled, not on its own trigger.
- Which packages must be installed first?
- Yes. The imports resolve to `celery`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.