Full answer
Django exposes two entry points: project/wsgi.py (application = get_wsgi_application()) and project/asgi.py (get_asgi_application()).
WSGI (Web Server Gateway Interface) is one request in, one response out, synchronous. It is mature and simple. Use it when the app is fully sync, which most Django apps still are.
ASGI (Asynchronous Server Gateway Interface) supports async def views, WebSockets (with Django Channels), Server-Sent Events and long polling. Use it when you need these or want concurrent outbound I/O in views.
Process layout in production:
- A reverse proxy or load balancer (Nginx, a cloud load balancer) terminates HTTPS, enforces body size limits, buffers slow clients and forwards to the app servers. Configure Django to trust its forwarded headers:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https"), and only when the proxy sets that header itself. - Gunicorn manages worker processes, restarts crashed workers and recycles them (
--max-requests). For WSGI:gunicorn project.wsgi -w 4. For ASGI:gunicorn project.asgi -k uvicorn_worker.UvicornWorker -w 4, or Uvicorn alone with--workers. - A common starting point is
workers = 2 x CPU cores + 1for sync workers, then tune with load tests. Threads (--threads) help when views wait on I/O. - Static files:
collectstaticto a CDN or object storage, or WhiteNoise. - Background work in a separate worker process (Celery, RQ, or Django 6.0's tasks framework with a backend).
Release checklist: run manage.py check --deploy, run migrations as a separate step before switching traffic, keep migrations backward compatible so old and new code can run together during a rolling deploy, add a health check URL, and send logs to stdout for the platform to collect.
Containers: one process type per container (web, worker, scheduler), configuration from environment variables, and a non-root user.
import sys
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": ":memory:"}},
)
django.setup()
import asyncio
import httpx
from django.core.asgi import get_asgi_application
from django.core.wsgi import get_wsgi_application
from django.http import JsonResponse
from django.urls import path
def health(request):
return JsonResponse({"status": "ok", "scheme": request.scheme})
urlpatterns = [path("healthz/", health)]
settings.ROOT_URLCONF = __name__
settings.ALLOWED_HOSTS = ["api.example.edu"]
settings.SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
wsgi_app = get_wsgi_application() # what "gunicorn project.wsgi" loads
asgi_app = get_asgi_application() # what "uvicorn project.asgi:application" loads
with httpx.Client(transport=httpx.WSGITransport(app=wsgi_app), base_url="http://api.example.edu") as c:
print("WSGI:", c.get("/healthz/").json())
async def call_asgi():
transport = httpx.ASGITransport(app=asgi_app)
async with httpx.AsyncClient(transport=transport, base_url="http://api.example.edu") as c:
r = await c.get("/healthz/", headers={"X-Forwarded-Proto": "https"})
print("ASGI behind TLS proxy:", r.json())
asyncio.run(call_asgi())
# Typical commands (not run here):
# gunicorn project.wsgi:application --workers 5 --bind 0.0.0.0:8000 --max-requests 2000
# gunicorn project.asgi:application -k uvicorn_worker.UvicornWorker --workers 5
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. It loads the same WSGI and ASGI application objects a production server would load and calls them in-process with httpx; the Gunicorn commands are shown as comments and were not run. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, gunicorn 27.0.1, uvicorn-worker 0.4.0): WSGI: {'status': 'ok', 'scheme': 'http'} ASGI behind TLS proxy: {'status': 'ok', 'scheme': 'https'}
Key points
- WSGI = sync; ASGI = async, WebSockets, long-lived connections
- Reverse proxy terminates TLS and buffers clients
- Gunicorn manages workers; Uvicorn workers for ASGI
- Start with about 2 x cores + 1 workers and load test
- Run migrations as a separate, backward-compatible release step
Common mistakes
- Running manage.py runserver in production
- Setting SECURE_PROXY_SSL_HEADER when the proxy does not strip client-supplied headers
- Running migrations inside every web container at startup and racing each other
- Choosing ASGI for a fully sync app and adding thread-switch overhead
Follow-ups
- How would you do a zero-downtime deploy with a schema change?
- How do you choose the number of Gunicorn workers and threads?
- What changes when you add WebSockets with Django Channels?
Tips
- Draw the chain: client, proxy, app server, workers, database
- Explain when ASGI is worth it
- Mention backward-compatible migrations during rolling deploys