Django has evolved. What started as a synchronous, request-response framework now supports async/await, native async views, and real-time WebSocket streaming. Paired with Celery, modern Django can power production-grade AI backends that stream LLM responses token-by-token, handle thousands of concurrent connections, and orchestrate complex AI workflows with the same developer productivity your team already has.
If you’re building AI-powered SaaS and wondering how to add real-time features to your Django backend, this guide shows you the patterns that work. We’ll walk through async views, WebSocket streaming, Celery task orchestration, and deployment practices that let you compete on latency and throughput without leaving the Django ecosystem.
Why Django for Real-Time AI?
Django’s synchronous roots made sense for traditional web apps. But with async/await support (Django 3.1+), native async views (Django 4.1+), and tight Celery integration, Django now handles real-time AI workloads elegantly.
The key advantages:
- Async views let you handle I/O-bound operations (API calls to LLM providers, database queries) without blocking worker threads.
- WebSocket support via Channels lets you stream token-by-token LLM responses directly to clients for better perceived latency.
- Celery handles long-running AI tasks (fine-tuning, batch inference, document processing) without blocking your request handlers.
- Connection pooling and middleware patterns keep memory and CPU usage predictable at scale.
- Your entire codebase, ORM, admin, and tooling remain unified and productive.
This matters because your team already knows Django. You can build streaming AI features without rewriting your backend in a different language or framework.
Async Views for Non-Blocking I/O
The foundation is async views. Instead of blocking on external API calls, you use async/await to yield control while waiting for responses.
Here’s a simple async view that calls an LLM API:
import asyncio
import httpx
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
@require_http_methods(["POST"])
async def generate_text(request):
prompt = request.POST.get("prompt", "")
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.openai.com/v1/chat/completions",
json={"model": "gpt-4", "messages": [{"role": "user", "content": prompt}]},
headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
timeout=30.0,
)
data = response.json()
return JsonResponse({"result": data["choices"][0]["message"]["content"]})
The key difference from sync views: you use await on the HTTP call, which means Django’s async runtime can handle other requests while this one waits for the API response. No thread pool exhaustion, no context switching overhead.
For database access, Django’s ORM now supports async queries (Django 4.1+):
from django.views.decorators.http import require_http_methods
from myapp.models import ConversationThread
@require_http_methods(["GET"])
async def get_conversation(request, thread_id):
thread = await ConversationThread.objects.aget(id=thread_id)
messages = await thread.messages.aall()
return JsonResponse({"messages": [m.content for m in messages]})
Use aget(), aall(), acount(), and acreate() instead of their sync counterparts. Django handles the async database connection pooling internally.
WebSocket Streaming for Token-by-Token Responses
Streaming LLM responses token-by-token improves perceived latency. Users see output appearing immediately instead of waiting for the entire response to complete.
Django Channels provides WebSocket support. Here’s a consumer that streams LLM output:
import json
import asyncio
import httpx
from channels.generic.websocket import AsyncWebsocketConsumer
from django.conf import settings
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def disconnect(self, close_code):
pass
async def receive(self, text_data):
data = json.loads(text_data)
prompt = data.get("prompt", "")
try:
# Stream LLM response
async with httpx.AsyncClient() as client:
async with client.stream(
"POST",
"https://api.openai.com/v1/chat/completions",
json={
"model": "gpt-4",
"messages": [{"role": "user", "content": prompt}],
"stream": True,
},
headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
timeout=60.0,
) as response:
async for line in response.aiter_lines():
if line.startswith("data:"):
try:
chunk = json.loads(line[6:])
delta = chunk["choices"][0].get("delta", {})
token = delta.get("content", "")
if token:
await self.send(text_data=json.dumps({"token": token}))
except (json.JSONDecodeError, KeyError):
pass
# Yield to event loop periodically
await asyncio.sleep(0)
await self.send(text_data=json.dumps({"done": True}))
except Exception as e:
await self.send(text_data=json.dumps({"error": str(e)}))
The client receives tokens as they arrive and can render them incrementally. This is far better UX than waiting for a full response.
To use this, configure Channels in your Django settings:
ASGI_APPLICATION = "myproject.asgi.application"
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
And route the WebSocket in your URL config:
from django.urls import re_path
from myapp.consumers import ChatConsumer
websocket_urlpatterns = [
re_path(r"ws/chat/(?P<room_name>\w+)/$", ChatConsumer.as_asgi()),
]
Celery for Long-Running AI Tasks
Not all AI work fits in a request-response cycle. Fine-tuning models, batch inference, document processing, and agent loops can take minutes or hours. Celery lets you offload these to background workers and keep your request handlers responsive.
Here’s a Celery task that processes documents and generates embeddings:
from celery import shared_task
from django.conf import settings
import httpx
import json
from myapp.models import Document, Embedding
@shared_task(bind=True, max_retries=3)
def process_document_embeddings(self, document_id):
try:
doc = Document.objects.get(id=document_id)
except Document.DoesNotExist:
return
chunks = doc.chunk_text(chunk_size=512)
for i, chunk in enumerate(chunks):
response = httpx.post(
"https://api.openai.com/v1/embeddings",
json={"input": chunk, "model": "text-embedding-3-small"},
headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
timeout=10.0,
)
embedding = response.json()["data"][0]["embedding"]
Embedding.objects.create(
document=doc,
chunk_index=i,
chunk_text=chunk,
vector=embedding,
)
doc.status = "embedded"
doc.save()
Trigger it from a view:
from django.http import JsonResponse
from myapp.tasks import process_document_embeddings
from myapp.models import Document
def upload_document(request):
file = request.FILES.get("file")
doc = Document.objects.create(file=file, status="processing")
process_document_embeddings.delay(doc.id)
return JsonResponse({"id": doc.id, "status": "processing"})
The request returns immediately. The task runs in a background worker pool. You can check status with a separate endpoint or use WebSockets to push updates to the client.
Connection Pooling and Resource Management
At scale, you’ll be making hundreds of concurrent requests to external APIs. Without proper pooling, you’ll exhaust sockets and connections. Here’s a production-ready setup:
import httpx
from django.conf import settings
# Shared async HTTP client with connection pooling
api_client = httpx.AsyncClient(
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
timeout=30.0,
)
# Use in your views
async def call_llm(prompt):
response = await api_client.post(
"https://api.openai.com/v1/chat/completions",
json={"model": "gpt-4", "messages": [{"role": "user", "content": prompt}]},
headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
)
return response.json()
Reuse the same client across requests. Create it once at startup and keep it alive. This reduces connection overhead dramatically.
For database connections, use PgBouncer or your database’s built-in connection pooling. Django’s async mode doesn’t auto-pool connections, so explicit pooling is essential at scale:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mydb",
"USER": "postgres",
"PASSWORD": "secret",
"HOST": "localhost",
"OPTIONS": {
"connect_timeout": 10,
},
}
}
Note: In async mode, disable CONN_MAX_AGE and rely on connection pooling instead. This prevents stale connections and improves concurrency.
Structured Outputs for AI Models
Modern LLM APIs support structured outputs (JSON schemas). This guarantees your AI responses parse correctly and contain the fields you expect. Integrate this into your views:
import json
from typing import TypedDict
import httpx
from django.conf import settings
class ExtractedData(TypedDict):
title: str
summary: str
tags: list[str]
async def extract_from_text(text: str) -> ExtractedData:
schema = {
"type": "object",
"properties": {
"title": {"type": "string"},
"summary": {"type": "string"},
"tags": {"type": "array", "items": {"type": "string"}},
},
"required": ["title", "summary", "tags"],
}
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.openai.com/v1/chat/completions",
json={
"model": "gpt-4-turbo",
"messages": [{"role": "user", "content": text}],
"response_format": {"type": "json_schema", "json_schema": {"name": "extracted_data", "schema": schema}},
},
headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
timeout=30.0,
)
result = response.json()["choices"][0]["message"]["content"]
return json.loads(result)
The API guarantees the response matches your schema. No parsing errors, no missing fields. This is crucial for production systems where you can’t afford to crash on unexpected data.
Deployment Patterns
Running Django async at scale requires a few tweaks to your deployment:
Use Daphne for async ASGI: Gunicorn with synchronous workers won’t handle async views properly. Use Daphne, which is built for async Django.
pip install daphne
daphne -b 0.0.0.0 -p 8000 myproject.asgi:application
Scale workers based on CPU, not connections: With async, a single worker can handle thousands of concurrent connections. Don’t spawn 100 workers like you would with Gunicorn. Start with 2-4 Daphne workers and monitor CPU and memory usage.
Use a reverse proxy: Nginx in front of Daphne for load balancing, SSL termination, and connection pooling.
upstream django {
least_conn;
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://django;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Monitor latency and throughput: Track p50, p95, and p99 response times. Monitor WebSocket connection count and message throughput. Use tools like Prometheus and Grafana to alert on anomalies.
Putting It Together: A Real-Time Chat API
Here’s how these patterns work in concert. A user sends a message via WebSocket. Your consumer streams the LLM response token-by-token. Meanwhile, a Celery task stores the conversation and updates embeddings for future retrieval.
import json
import asyncio
import httpx
from channels.generic.websocket import AsyncWebsocketConsumer
from django.conf import settings
from myapp.models import Conversation, Message
from myapp.tasks import update_conversation_embeddings
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_id = self.scope["url_route"]["kwargs"]["room_name"]
await self.accept()
async def receive(self, text_data):
data = json.loads(text_data)
user_message = data.get("message", "")
try:
# Store user message
conv = await Conversation.objects.aget(id=self.room_id)
user_msg = await Message.objects.acreate(
conversation=conv,
role="user",
content=user_message,
)
# Stream LLM response
full_response = ""
async with httpx.AsyncClient() as client:
async with client.stream(
"POST",
"https://api.openai.com/v1/chat/completions",
json={
"model": "gpt-4",
"messages": [{"role": "user", "content": user_message}],
"stream": True,
},
headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
timeout=60.0,
) as response:
async for line in response.aiter_lines():
if line.startswith("data:"):
try:
chunk = json.loads(line[6:])
token = chunk["choices"][0].get("delta", {}).get("content", "")
if token:
full_response += token
await self.send(text_data=json.dumps({"token": token}))
except (json.JSONDecodeError, KeyError):
pass
await asyncio.sleep(0)
# Store assistant message
await Message.objects.acreate(
conversation=conv,
role="assistant",
content=full_response,
)
# Trigger background task to update embeddings
update_conversation_embeddings.delay(self.room_id)
await self.send(text_data=json.dumps({"done": True}))
except Exception as e:
await self.send(text_data=json.dumps({"error": str(e)}))
The entire flow is non-blocking. The WebSocket consumer streams tokens as they arrive. The database saves are async. The embedding update happens in the background without blocking the user’s response.
Common Pitfalls and How to Avoid Them
Mixing sync and async code: If you call a sync function from an async view without using sync_to_async, you’ll block the event loop. Always wrap sync code:
from asgiref.sync import sync_to_async
async def my_view(request):
# Sync ORM query wrapped
user = await sync_to_async(User.objects.get)(id=1)
return JsonResponse({"user": user.username})
Forgetting to yield control: Long-running loops can starve other requests. Use await asyncio.sleep(0) to yield periodically:
for item in large_list:
await process_item(item)
await asyncio.sleep(0) # Let other requests run
Not setting timeouts: External API calls can hang. Always set explicit timeouts:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.get(url)
Exhausting connection pools: Reuse HTTP clients and database connections. Don’t create new ones per request.
Conclusion
Django’s async capabilities, combined with Celery and WebSockets, give you everything you need to build production-grade AI backends that handle real-time workloads efficiently. You get token-by-token streaming, background task orchestration, and efficient resource usage without leaving the Django ecosystem.
The patterns shown here come from running these systems at scale. Async views handle thousands of concurrent I/O operations. WebSocket consumers stream LLM responses with minimal overhead. Celery tasks process long-running AI workloads without blocking requests. Connection pooling keeps resource usage predictable.
If your team already knows Django, these patterns let you build competitive AI backends. Apply them, and you’ll have a cohesive, productive backend that handles the demands of modern AI applications.
Can I use Django async views with my existing synchronous code?
Yes, but carefully. You can call sync functions from async views using sync_to_async from asgiref.sync. However, this blocks the event loop for the duration of the sync call. For high-concurrency scenarios, migrate your critical paths to async code. Start with I/O-bound operations like database queries and API calls.
Do I need Channels for WebSockets, or are there simpler alternatives?
Channels is the standard choice and works well at scale. If you want something lighter, you can use libraries like websockets directly with ASGI, but you’ll lose Django’s ORM integration and middleware. For most production apps, Channels is the right trade-off between simplicity and features.
How many Daphne workers should I run?
Start with 2-4 workers and monitor CPU and memory usage. With async, a single worker can handle thousands of concurrent connections, so you don’t need one worker per core like you would with synchronous Gunicorn. Scale based on CPU load, not connection count. Most apps max out at 4-8 workers on a single machine.
What’s the difference between Celery tasks and async views for calling LLM APIs?
Async views are for request-response work that completes in seconds. The user waits for the result and gets it in the HTTP response. Celery tasks are for long-running work (minutes or hours) that doesn’t need to block the request. Use async views for streaming chat responses, use Celery tasks for fine-tuning, batch processing, and background updates.
How do I handle connection drops in WebSocket consumers?
Implement proper cleanup in the disconnect method. Cancel any pending tasks, close external connections, and clean up database resources. Use try-finally blocks to ensure cleanup runs even if an exception occurs. Also implement reconnection logic on the client side with exponential backoff.
Are there limitations to Django’s async mode I should know about?
Yes. Transactions don’t work in async mode, so write transaction-critical code as a single synchronous function and call it via sync_to_async. Also, disable CONN_MAX_AGE in async mode and use explicit connection pooling instead. These are documented in the Django async documentation and are straightforward to work around.