← Back to Django, page 5

django-0087 · Hard senior

What does running Celery safely in production with Django involve: idempotent tasks, acks_late, retry policy, time limits, queues and monitoring?

Celery delivers tasks at least once, so every task must be idempotent. Production settings include acks_late (acknowledge after the task finishes, so worker crashes cause redelivery), bounded retries with backoff and jitter, hard and soft time limits, separate queues for slow and urgent work, prefetch tuned to task length, result expiry, and monitoring of queue depth and failure rates. Deduplicate with a unique business key, a database constraint or a cache lock.

Full answer

Delivery semantics: with the default acks_early, a message is acknowledged when a worker receives it; if the worker dies mid-task, the task is lost. With acks_late=True, it is acknowledged after completion; a crash causes redelivery, so duplicates are possible. Neither gives exactly-once. Design for at-least-once plus idempotency.

Idempotency techniques:

  • Natural keys: Payment.objects.get_or_create(external_id=...) backed by a unique constraint; the second run finds the row.
  • State checks: if invoice.status == "sent": return, updated atomically (update(status="sent") on status="queued" rows returns the number changed).
  • Lock or dedupe key: cache.add(f"task:{id}", 1, timeout) returns False when someone else holds it (the add is atomic on Redis/Memcached).
  • External APIs: pass an idempotency key to the provider.

Reliability settings:

  • Retries: autoretry_for=(TimeoutError,), retry_backoff=True, retry_jitter=True, max_retries=5. Do not retry non-transient errors (validation).
  • task_time_limit (hard kill) and task_soft_time_limit (raises SoftTimeLimitExceeded so you can clean up).
  • worker_prefetch_multiplier=1 with long tasks so a worker does not hoard messages.
  • task_acks_on_failure_or_timeout, broker_transport_options (visibility timeout on Redis must exceed the longest ETA or acks_late task, or tasks are redelivered while still running).
  • Result backend only when needed; set result_expires.

Operations:

  • Queues: task_routes = {"app.tasks.mail.*": {"queue": "mail"}} and dedicated worker pools, so a slow report cannot starve password-reset mail.
  • Enqueue after commit with transaction.on_commit; or use a transactional outbox for must-not-lose events.
  • Monitor queue length, task latency, failure and retry rates (Flower, Prometheus exporters), and alert on age of oldest message.
  • Pass IDs, keep payloads small, and version task signatures when changing arguments (old messages may still be in the queue).
  • Graceful shutdown: warm shutdown on deploy, so running tasks finish.
python
from celery import Celery, shared_task

app = Celery("demo")
app.conf.update(
    broker_url="memory://",
    task_always_eager=True,
    task_routes={"demo.mail.*": {"queue": "mail"}, "demo.reports.*": {"queue": "slow"}},
    worker_prefetch_multiplier=1,
)

PROCESSED = set()          # stands in for a database table with a unique constraint
SIDE_EFFECTS = []


@shared_task(name="demo.mail.send_receipt", bind=True, acks_late=True, autoretry_for=(TimeoutError,),
             retry_backoff=True, retry_jitter=True, max_retries=5, soft_time_limit=30, time_limit=45)
def send_receipt(self, payment_id):
    if payment_id in PROCESSED:                     # idempotency: a redelivered message becomes a no-op
        return "duplicate ignored"
    SIDE_EFFECTS.append(f"email for {payment_id}")
    PROCESSED.add(payment_id)
    return "sent"


print(send_receipt.delay(7).get(), "|", send_receipt.delay(7).get(), "| side effects:", SIDE_EFFECTS)
print("acks_late:", send_receipt.acks_late, "| max_retries:", send_receipt.max_retries,
      "| soft/hard limits:", send_receipt.soft_time_limit, send_receipt.time_limit)
print("backoff:", send_receipt.retry_backoff, "| jitter:", send_receipt.retry_jitter)

route = app.amqp.router.route({}, "demo.mail.send_receipt")
print("routed to queue:", route["queue"].name, "|", app.amqp.router.route({}, "demo.reports.monthly")["queue"].name)

Standalone script. Needs `pip install celery`. Eager mode with the in-memory broker stands in for a worker; the printed attributes are the settings a real worker would honour. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, Celery 5.7.0): sent | duplicate ignored | side effects: ['email for 7'] acks_late: True | max_retries: 5 | soft/hard limits: 30 45 backoff: True | jitter: True routed to queue: mail | slow

Key points

  • At-least-once delivery means tasks must be idempotent
  • acks_late redelivers after crashes; duplicates become possible
  • Bounded retries with backoff and jitter; time limits
  • Separate queues and tuned prefetch prevent starvation
  • Monitor queue age; enqueue after commit or use an outbox

Common mistakes

  • Assuming exactly-once delivery
  • Setting acks_late without making tasks idempotent
  • Mixing slow and urgent tasks in one queue
  • Redis visibility timeout shorter than the longest task, causing duplicate runs
  • Changing task arguments without handling messages already queued

Follow-ups

  • How do you do exactly-once effects across a database and an external API?
  • What is the transactional outbox pattern?
  • How would you schedule periodic tasks safely with several beat instances?

Tips

  • State at-least-once clearly
  • Give two idempotency techniques
  • Name settings and queue separation