← Back to Django, page 3

django-0047 · Hard senior

How do you run background work in Django? Compare Celery, the Django 6.0 tasks framework and simple alternatives, and explain how to queue tasks safely.

Slow or unreliable work (emails, reports, API calls) should leave the request cycle and run in a worker process. Celery with Redis or RabbitMQ is the long-standing choice; Django 6.0 added a built-in tasks API (django.tasks) with pluggable backends; RQ and Dramatiq are lighter options. Queue tasks with transaction.on_commit so workers never see missing rows, pass IDs not objects, make tasks idempotent and set retries with backoff.

Full answer

A request should finish in well under a second. Generating a 40-page report card PDF, sending 2,000 fee reminder emails or calling a slow SMS gateway does not fit. Background processing moves that work to separate worker processes that read jobs from a queue.

Options:

  • Celery: mature, feature-rich (retries, schedules with beat, chains, rate limits), with Redis or RabbitMQ as broker. More moving parts to run and monitor.
  • Django 6.0 tasks framework (django.tasks): a standard @task decorator and .enqueue() API. Django ships development backends (immediate and dummy); production execution needs a backend package such as django-tasks with a database or Redis worker. It standardises the interface so you can swap backends.
  • RQ, Dramatiq, Huey: simpler queues for smaller teams.
  • Cron plus a management command: enough for nightly batch jobs.

Rules that prevent most bugs:

  1. Enqueue after commit. If you queue inside a transaction, the worker can start before the commit and fail to find the row, or run for a row that was rolled back. Use transaction.on_commit(lambda: send_receipt.delay(payment.id)). Celery 5.4+ has delay_on_commit() for the same effect.
  2. Pass IDs, not model instances. The worker loads fresh data.
  3. Make tasks idempotent. Brokers deliver at least once, so a task may run twice. Check "already sent" flags or use unique keys.
  4. Retry with backoff for temporary failures, with a maximum count, and send final failures to a dead-letter queue or alert.
  5. Set time limits so a stuck task does not block a worker forever.
  6. Keep tasks small and observable: log task IDs and track queue length.

Async views are not a replacement: an async def view still holds the HTTP request open until the work finishes.

python
import sys
import tempfile
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": tempfile.mkdtemp() + "/school.sqlite3"}},
)
django.setup()

import queue
import threading

from django.db import connection, connections, models, transaction


class Payment(models.Model):
    student = models.CharField(max_length=30)
    amount = models.IntegerField()
    receipt_sent = models.BooleanField(default=False)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Payment)

jobs = queue.Queue()   # stands in for Redis or RabbitMQ
log = []


def send_receipt(payment_id):
    """Idempotent task: loads fresh data by ID and skips work already done."""
    updated = Payment.objects.filter(pk=payment_id, receipt_sent=False).update(receipt_sent=True)
    log.append(f"payment {payment_id}: " + ("receipt sent" if updated else "already sent, skipped"))


def worker():
    while (job := jobs.get()) is not None:
        func, arg = job
        try:
            func(arg)
        except Payment.DoesNotExist:
            log.append("worker could not find the row")
    connections.close_all()


def record_payment(student, amount, fail=False):
    with transaction.atomic():
        p = Payment.objects.create(student=student, amount=amount)
        transaction.on_commit(lambda: jobs.put((send_receipt, p.id)))
        if fail:
            raise ValueError("bank declined")
    return p


t = threading.Thread(target=worker)
t.start()
p = record_payment("lakshmi", 1500)
try:
    record_payment("manoj", 900, fail=True)   # rolled back, so no job is queued
except ValueError:
    pass
jobs.put((send_receipt, p.id))                # duplicate delivery
jobs.put(None)
t.join()
print(log)
print(Payment.objects.count(), Payment.objects.get(pk=p.id).receipt_sent)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. A thread and queue.Queue stand in for a real broker and worker so the example runs anywhere; with Celery the call would be transaction.on_commit(lambda: send_receipt.delay(p.id)). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['payment 1: receipt sent', 'payment 1: already sent, skipped'] 1 True

Key points

  • Move slow or unreliable work to worker processes
  • Celery, django.tasks (6.0+), RQ/Dramatiq, or cron
  • Enqueue with transaction.on_commit
  • Pass IDs; make tasks idempotent; retry with backoff
  • Async views do not replace a task queue

Common mistakes

  • Queueing a task inside a transaction so the worker cannot find the new row
  • Passing a model instance to a task and acting on stale data
  • Assuming each task runs exactly once
  • Retrying forever with no backoff or alerting
  • Doing slow work in an async view instead of a worker

Follow-ups

  • How would you send 50,000 emails without overloading the mail provider?
  • What does at-least-once delivery mean for task design?
  • How would you monitor a task queue in production?

Tips

  • Name the on_commit rule early, it is the most common production bug
  • Explain idempotency with a concrete check
  • Know that Django 6.0 added a tasks API and what it does and does not include