Django + Daphne + Celery: handling slow tasks without blocking

Overview

The problem

You have a Django app served by Daphne. A user triggers a slow task - fetching thousands of records from an external API and uploading them to object storage. The task takes minutes.

During those minutes:

  • Health checks get no response.
  • Other users get no response.
  • Kubernetes decides the pod is dead and kills it.

The fix is not more CPU or RAM. The fix is Celery.

See also: Concurrency refresher for the theory behind this.


Why more CPU does not help

Daphne is single-threaded. One process, one event loop.

 1Daphne pod:
 2
 3โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 4โ”‚ 1 Process                           โ”‚
 5โ”‚                                     โ”‚
 6โ”‚   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
 7โ”‚   โ”‚ 1 Thread (event loop)       โ”‚   โ”‚
 8โ”‚   โ”‚                             โ”‚   โ”‚
 9โ”‚   โ”‚  while true:                โ”‚   โ”‚
10โ”‚   โ”‚    check sockets            โ”‚   โ”‚
11โ”‚   โ”‚    handle request           โ”‚   โ”‚
12โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
13โ”‚                                     โ”‚
14โ”‚  CPU: uses 1 core max               โ”‚
15โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

If you give this pod 8 cores and 16 GB RAM:

 1โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 2โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”  BUSY (processing task)    โ”‚
 3โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                            โ”‚
 4โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”  IDLE                      โ”‚
 5โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                            โ”‚
 6โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”  IDLE                      โ”‚
 7โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                            โ”‚
 8โ”‚ ... 5 more idle cores ...           โ”‚
 9โ”‚                                     โ”‚
10โ”‚ Health check: still blocked         โ”‚
11โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Single-threaded code cannot use multiple cores. More resources are wasted resources.


Daphne vs the Django dev server

Both are single-threaded. But they handle requests differently.

1Dev server (runserver): WSGI - synchronous
2
3Request 1 โ”€โ”€โ–บ Process โ”€โ”€โ–บ Response 1
4                 โ”‚
5Request 2 โ”€โ”€โ–บ  wait...
6                 โ”‚
7Request 3 โ”€โ”€โ–บ  wait...
8
9One at a time. Blocks immediately on slow code.
1Daphne: ASGI - asynchronous event loop
2
3Request 1 โ”€โ”€โ”
4Request 2 โ”€โ”€โ”ผโ”€โ”€โ–บ Event loop โ”€โ”€โ–บ Responses
5Request 3 โ”€โ”€โ”˜    (juggling)
6
7Many quick requests at once. Still blocks on slow synchronous code.
Feature Dev server Daphne
Protocol WSGI (sync) ASGI (async)
WebSockets No Yes
Requests/sec ~50 ~1000+
Production Never Yes
Slow tasks Blocks Also blocks

Daphne is better at handling many quick requests. Neither is good at one slow request that blocks the thread.


The solution: Celery

Move the slow task to a separate process. Daphne queues the work and returns immediately. A Celery worker picks it up and does the blocking I/O on its own thread.

 1โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 2โ”‚ DAPHNE POD          โ”‚     โ”‚ CELERY WORKER POD   โ”‚
 3โ”‚                     โ”‚     โ”‚                     โ”‚
 4โ”‚ 1 process           โ”‚     โ”‚ 1 process           โ”‚
 5โ”‚ 1 thread            โ”‚     โ”‚ 1 thread            โ”‚
 6โ”‚                     โ”‚     โ”‚                     โ”‚
 7โ”‚ CPU: 0.5 core       โ”‚     โ”‚ CPU: 0.5 core       โ”‚
 8โ”‚ Mem: 200 MB         โ”‚     โ”‚ Mem: 200 MB         โ”‚
 9โ”‚                     โ”‚     โ”‚                     โ”‚
10โ”‚ Health check: OK    โ”‚     โ”‚ Blocking I/O: OK    โ”‚
11โ”‚ User requests: OK   โ”‚     โ”‚ (nobody cares)      โ”‚
12โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
13          โ”‚                           ^
14          โ”‚   Redis (message queue)   โ”‚
15          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Yes, Celery means more resources. But those resources are actually used.


Implementation

Install

1pip install celery redis

Configure Celery

1# myapp/celery.py
2import os
3from celery import Celery
4
5os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
6
7app = Celery("myapp")
8app.config_from_object("django.conf:settings", namespace="CELERY")
9app.autodiscover_tasks()
1# myapp/__init__.py
2from .celery import app as celery_app
3
4__all__ = ("celery_app",)
1# settings.py
2CELERY_BROKER_URL = "redis://localhost:6379/0"
3CELERY_RESULT_BACKEND = "redis://localhost:6379/0"

Define a task

 1# myapp/tasks.py
 2from celery import shared_task
 3
 4
 5@shared_task
 6def sync_data(user_id: int) -> dict:
 7    """Fetch records from external API and upload to object storage."""
 8    records = fetch_from_api(user_id)      # blocking I/O - fine here
 9    upload_to_storage(records)             # blocking I/O - fine here
10    return {"synced": len(records)}

Call the task from a view

1# myapp/views.py
2from django.http import JsonResponse
3from .tasks import sync_data
4
5
6def start_sync(request):
7    task = sync_data.delay(request.user.id)  # returns immediately
8    return JsonResponse({"task_id": task.id, "status": "queued"})

The view returns in milliseconds. Daphne is never blocked.

Check task status

 1from celery.result import AsyncResult
 2
 3
 4def task_status(request, task_id):
 5    result = AsyncResult(task_id)
 6    return JsonResponse({
 7        "task_id": task_id,
 8        "status": result.status,
 9        "result": result.result if result.ready() else None,
10    })

Run everything

1# Terminal 1: Redis
2docker run -p 6379:6379 redis:alpine
3
4# Terminal 2: Daphne
5daphne myapp.asgi:application
6
7# Terminal 3: Celery worker
8celery -A myapp worker --loglevel=info

Kubernetes deployment

Each component runs as a separate deployment.

 1# daphne-deployment.yaml
 2apiVersion: apps/v1
 3kind: Deployment
 4metadata:
 5  name: daphne
 6spec:
 7  replicas: 2
 8  template:
 9    spec:
10      containers:
11        - name: daphne
12          command: ["daphne", "myapp.asgi:application"]
13          resources:
14            requests:
15              cpu: "250m"
16              memory: "256Mi"
17            limits:
18              cpu: "500m"
19              memory: "512Mi"
 1# celery-deployment.yaml
 2apiVersion: apps/v1
 3kind: Deployment
 4metadata:
 5  name: celery-worker
 6spec:
 7  replicas: 2
 8  template:
 9    spec:
10      containers:
11        - name: celery
12          command:
13            - celery
14            - -A
15            - myapp
16            - worker
17            - --loglevel=info
18          resources:
19            requests:
20              cpu: "500m"
21              memory: "512Mi"
22            limits:
23              cpu: "1"
24              memory: "1Gi"

Scale Celery workers independently from Daphne. If the queue grows, add more Celery pods - not more Daphne pods.


Why horizontal scaling alone does not fix blocking

Adding more Daphne pods helps when you have many concurrent users. It does not help when one slow request blocks a pod.

11 user, 1 slow task:
2
3โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
4โ”‚ Pod 1   โ”‚  โ”‚ Pod 2   โ”‚  โ”‚ Pod 3   โ”‚
5โ”‚ BLOCKED โ”‚  โ”‚ idle    โ”‚  โ”‚ idle    โ”‚
6โ”‚ 10 min  โ”‚  โ”‚         โ”‚  โ”‚         โ”‚
7โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
8
9Two pods are idle. One pod is stuck. Health check on pod 1 fails.

Celery moves the blocking work to a process that is designed to block. Daphne pods stay free.


Summary

Approach Health check Resources Note
More CPU/RAM to Daphne Fails Wasted Can't use cores
More Daphne pods Fails Wasted Stuck pod stuck
Celery worker Passes Actually used This is the fix

The key insight: Daphne is a fast waiter. Celery is the kitchen. The waiter does not cook.