Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Django Async Views: When and How to Use Them

Django async views can improve throughput for I/O-bound work, but they require care with the ORM and other synchronous code. Learn when to use them and how to handle database access safely.

~6 min readPython
#Django#Async#ASGI#Python
Illustration of a Django async view processing requests concurrently with an event loop.

Django's async views allow a request handler to yield control while it waits on I/O, so the server can work on other requests instead of holding a dedicated worker thread. They also change how you interact with the ORM and other synchronous code. This article shows how to write async views in Django, when they help, and where they introduce extra complexity.

How Django Executes Views: Sync vs Async

A traditional Django view is a synchronous function: the server calls it, the function runs to completion, and the response is returned. Each request occupies a worker thread for its entire duration. If the view waits on a network call or a database query, that thread is blocked.

An async view is declared with async def instead of def. Under an ASGI server, Django runs it on an event loop, so the view can await other async operations without blocking the loop. This allows a single worker to handle many concurrent requests while they wait on I/O.

The key difference is not speed of execution but concurrency. Async views can interleave work from multiple requests, but they do not make CPU-bound code faster. In fact, CPU-bound code can slow down because of the overhead of the event loop.

Declaring an Async View

Writing an async view is syntactically simple. Use async def and await where needed:

python
# views.py import asyncio from django.http import JsonResponse async def async_view(request): await asyncio.sleep(1) # Simulate an async I/O operation return JsonResponse({"status": "ok"})

Routing works the same as for a sync view. On an ASGI server, Django recognizes the async keyword and runs the view in an async context, so the view can use await, async for, and async with.

Middleware also matters. Django can adapt synchronous middleware for async views, but any middleware that performs blocking I/O can still introduce stalls. Keep middleware light, and prefer async middleware or nonblocking operations for async request paths.

When Async Views Actually Help

Async views are beneficial when your view spends most of its time waiting on I/O that has an async implementation. Common examples include:

  • Calling an external HTTP API with an async client like httpx.AsyncClient
  • Reading from a WebSocket or SSE stream
  • Performing multiple independent I/O operations concurrently with asyncio.gather
  • Using Django's async ORM methods on a database backend with an async driver

If your view is CPU-bound—like heavy JSON serialization, image processing, or complex calculations—async will not help. It may even hurt because the event loop adds scheduling overhead. In those cases, a sync view running in a thread pool is usually better.

Consider this example where async shines:

python
import asyncio import httpx from django.http import JsonResponse async def fetch_multiple(urls): async with httpx.AsyncClient() as client: responses = await asyncio.gather(*(client.get(url) for url in urls)) return [r.json() for r in responses] async def aggregate_view(request): data = await fetch_multiple(["https://api.example.com/a", "https://api.example.com/b"]) return JsonResponse(data, safe=False)

Here, the two HTTP requests run concurrently, reducing total latency compared to sequential calls.

The Async ORM and Database Access

Django's ORM is synchronous by default outside its async interface. Attempting to evaluate a queryset, such as list(MyModel.objects.all()), directly inside an async view blocks the event loop and defeats the purpose of async. There are two safe approaches:

  1. Use sync_to_async to run the evaluation in a separate thread.
  2. Use Django's native async ORM methods, introduced in Django 4.1, if your database backend provides an async driver and supports the queryset operation you need.

sync_to_async works with any database backend. Because querysets are lazy, force the evaluation inside the thread pool by converting to a list:

python
from asgiref.sync import sync_to_async from myapp.models import MyModel async def my_async_view(request): items = await sync_to_async(list)(MyModel.objects.all()) return JsonResponse({"count": len(items)})

This passes the list() call to sync_to_async, so the queryset is evaluated in the thread and the event loop is not blocked by the database call.

Django's native async ORM also supports async for obj in MyModel.objects.all() on some backends and adds async methods such as acount() and aget(). However, support depends on the database backend and Django version, and not every queryset feature has an async equivalent. Check the Django documentation for your version to see the current limits.

Mixing Sync and Async Code Safely

You will often need to call sync code from an async view. The asgiref.sync module provides two helpers:

  • sync_to_async(func) converts a sync callable to an async callable. By default it uses thread_sensitive=True, which serializes calls through a shared thread; this protects thread-sensitive code but can limit concurrency.
  • async_to_sync(func) converts an async callable to a sync one, useful for calling async code from sync views or tests.

Be careful with sync_to_async. With the default thread_sensitive=True, slow work can serialize behind other sync calls. For independent blocking I/O that does not depend on thread-local state, you can set thread_sensitive=False to run work in the thread pool:

python
from asgiref.sync import sync_to_async # Run an independent blocking call in the thread pool. result = await sync_to_async(some_sync_function, thread_sensitive=False)()

Even with thread_sensitive=False, a long-running or CPU-bound function can exhaust the default thread pool, so keep heavy work out of request paths or move it to a dedicated task queue.

Another pitfall is using blocking libraries like requests directly in an async view. The requests library is synchronous, so it blocks the event loop. Use an async HTTP client instead, or wrap requests with sync_to_async if you must.

Performance Tradeoffs and Common Pitfalls

Async views can improve throughput for I/O-bound workloads, but they introduce complexity. Here are the most important tradeoffs:

  • Event loop blocking: Any sync operation that takes more than a few milliseconds blocks all other requests on that worker when run directly in the async view. Avoid raw sync ORM evaluation, time.sleep, or CPU-heavy loops in the view body. Wrap those calls with sync_to_async or move them out of the request path.
  • Thread pool exhaustion: sync_to_async uses a finite thread pool. If many requests call sync code simultaneously, they may queue up, increasing latency.
  • Middleware overhead: Django's middleware is sync by default. When a request goes through sync middleware and then an async view, Django may switch between sync and async contexts, adding overhead. Prefer async middleware for async paths where you can.
  • Database connection handling: A sync ORM call wrapped with sync_to_async relies on thread-local connection handling, so it behaves like a sync request in many deployments. Native async ORM support may require an async connection pool from the database driver. Check the backend documentation.

A common mistake is assuming async views are always faster. They are not. They are more efficient at handling many concurrent I/O-bound requests, but they can be slower for a single request due to context switching. Measure your actual workload before migrating.

Production Considerations for Async Views

To run async views and get the concurrency benefits, use an ASGI server such as Uvicorn, Daphne, or Hypercorn. A WSGI server with sync workers runs each request in a thread, so it cannot provide the same interleaving concurrency for async views. Configure your deployment accordingly.

bash
# Example with Uvicorn uvicorn myproject.asgi:application --host 0.0.0.0 --port 8000

When scaling, remember that each ASGI worker runs an event loop. The number of concurrent requests is limited by how many tasks the loop can handle, not by thread count. You may need fewer workers than with WSGI, but each worker uses more CPU for the event loop.

Monitor your application for event loop blocking. Tools like asyncio debug mode or custom middleware can log when a task takes too long. Also, if you use native async database access, verify that your database driver and connection pool are designed for async use.

Finally, consider the learning curve for your team. Async views require a different mental model and careful handling of sync code. If your views are mostly simple CRUD operations, sync views are likely sufficient. Reserve async for specific bottlenecks where you can measure a real benefit.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.