← Back to Django, page 5

django-0081 · Medium mid

How do you integrate Celery with Django: configuration, defining tasks, calling them with delay(), retries and testing in eager mode?

Create a Celery app in the project, load its settings from Django settings with a CELERY_ namespace, define tasks with @shared_task, and call them with task.delay(args) or apply_async(). Tasks run in separate worker processes with a message broker such as Redis or RabbitMQ. Pass IDs, not objects, make tasks idempotent, use bind=True with self.retry() for transient failures, and run synchronously in tests with task_always_eager.

Full answer

Setup (conventional layout):

python
# proj/celery.py
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings")
app = Celery("proj")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()          # finds tasks.py in each installed app

# proj/__init__.py
from .celery import app as celery_app

Settings: CELERY_BROKER_URL, CELERY_RESULT_BACKEND (optional), CELERY_TASK_ACKS_LATE, time limits.

Tasks:

python
@shared_task(bind=True, autoretry_for=(ConnectionError,), retry_backoff=True, max_retries=3)
def send_receipt(self, payment_id):
    payment = Payment.objects.get(pk=payment_id)
    ...
  • @shared_task works without importing the app instance, so reusable apps can define tasks.
  • Call send_receipt.delay(payment.id); apply_async(args, countdown=60, queue="mail") gives control over delay and routing.
  • Arguments must be serialisable (JSON by default): pass primary keys and reload inside the task, so data is fresh and messages are small.
  • Queue after commit: transaction.on_commit(lambda: send_receipt.delay(payment.id)), otherwise the worker may run before the row is visible.
  • Retries: self.retry(exc=exc, countdown=...) or autoretry_for with retry_backoff. Tasks must be idempotent because retries and acks_late can run them more than once.
  • Do not wait for results inside a request; use the result backend only for tracking.

Testing: set CELERY_TASK_ALWAYS_EAGER = True so .delay() runs inline. CELERY_TASK_EAGER_PROPAGATES = True re-raises task exceptions in the test, but in the Celery version used for the snippet it also surfaced Retry instead of retrying, so leave it off when testing retry logic. Eager mode does not test serialisation, queues or concurrency, so also test task functions directly and run an occasional integration test with a real worker.

python
import sys

from celery import Celery, shared_task

app = Celery("demo")
app.conf.update(
    broker_url="memory://",
    task_always_eager=True,              # tests and demos: run inline, no worker or broker needed
)

attempts = {"n": 0}
SENT = []


@shared_task(bind=True, max_retries=3)
def send_receipt(self, payment_id):
    attempts["n"] += 1
    if attempts["n"] < 3:
        raise self.retry(exc=ConnectionError("mail server busy"), countdown=0)
    SENT.append(payment_id)
    return f"receipt sent for payment {payment_id}"


result = send_receipt.delay(42)
print(result.get(), "| attempts:", attempts["n"], "| sent:", SENT)


@shared_task
def add(x, y):
    return x + y


print(add.apply_async((2, 3), countdown=60).get(), add.delay(4, 5).get())
print(add.name, "| eager:", result.__class__.__name__)

import json
try:
    json.dumps({"student": object()})
except TypeError:
    print("task arguments must be JSON-serialisable: pass the id, not the object")

Standalone script. Needs `pip install celery`. It uses the in-memory broker with eager mode, so no Redis or worker is required; in a project the app lives in proj/celery.py and a worker runs with `celery -A proj worker`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, Celery 5.7.0): receipt sent for payment 42 | attempts: 3 | sent: [42] 5 9 demo.add | eager: EagerResult task arguments must be JSON-serialisable: pass the id, not the object

Key points

  • Celery app loads Django settings with the CELERY_ namespace
  • @shared_task plus delay() or apply_async()
  • Pass IDs, not objects; make tasks idempotent
  • Queue with transaction.on_commit()
  • Eager mode for unit tests; real worker for integration tests

Common mistakes

  • Passing model instances as task arguments
  • Queuing a task inside a transaction before commit
  • Writing tasks that are unsafe to run twice
  • Waiting for task results inside web requests

Follow-ups

  • What does acks_late change?
  • How do you route tasks to different queues?
  • How do you schedule periodic tasks?

Tips

  • Show the Django integration lines
  • Say pass IDs and use on_commit
  • Mention idempotency