Setup ASGI for Async Deployment

A snippet showing how to configure ASGI for deployment.


# Install an ASGI server
pip install uvicorn[standard]

# (Alternative)
pip install daphne

      

# project/asgi.py

import os
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.prod")
application = get_asgi_application()

      

# Uvicorn (basic)
uvicorn project.asgi:application

# Bind host/port and set workers (for CPU-bound or high concurrency)
uvicorn --host 0.0.0.0 --port 8000 --workers 4 project.asgi:application

gunicorn project.asgi:application -k uvicorn.workers.UvicornWorker --workers 4 --bind 0.0.0.0:8000
      

# systemd service (Uvicorn) - /etc/systemd/system/uvicorn.service

[Unit]
Description=uvicorn daemon
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/srv/project
Environment="DJANGO_SETTINGS_MODULE=project.settings.prod"
ExecStart=/srv/venv/bin/uvicorn --host 0.0.0.0 --port 8000 --workers 4 project.asgi:application
Restart=on-failure

[Install]
WantedBy=multi-user.target

# Enable & start
sudo systemctl daemon-reload
sudo systemctl enable uvicorn
sudo systemctl start uvicorn
      

# Result
- Django runs on an ASGI server (Uvicorn/Daphne) for async views and WebSockets.
- You can mix sync and async views; Django handles thread offloading for sync code.
- Use Nginx as a reverse proxy in production; terminate TLS there.
      
Explanation:
  • ASGI enables concurrency-friendly features (long polling, SSE, WebSockets).
  • For WebSockets/Channels, configure a Redis-backed channel layer and routing.
  • Use Gunicorn + Uvicorn workers for better process supervision and log rotation.
  • Keep DJANGO_SETTINGS_MODULE set to your prod settings.
  • Category Deployment & Settings
  • Total Views 986
  • Last Modified 07 December, 2025
  • Tags #deployment #asgi #async #server
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.