Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 77 ยท REST APIs

Async Django

Learn async Django: ASGI, async def views, the async ORM (aget, acreate, async for), sync_to_async, async middleware and where Channels fits in.

Most Django code is synchronous: a worker takes a request, runs your view from top to bottom and returns the response. While that view waits for a database query or an HTTP call, the worker does nothing else. That model is simple and scales well with more workers, but it is wasteful when a view mostly waits, for example when it calls three remote services.

Since Django 3.1 you can write asynchronous views with async def. While one request awaits a slow call, the same process can serve other requests. This lesson explains how async fits into Django: the ASGI server interface, async views, the async ORM methods, sync_to_async, async middleware and Channels. You will run the parts that need no threads live, and see the thread-based parts as read-only code.

Synchronous vs asynchronous in one picture

With async def and await, a function can pause at a slow operation and let an event loop run other work in the meantime. Nothing runs in parallel on the CPU here: it is cooperative multitasking, ideal for I/O-bound work (network calls, waiting) and useless for CPU-bound work (number crunching).

flowchart TD
    subgraph Sync["Sync: one worker, one request at a time"]
        S1["request A: wait for API"] --> S2["request B waits its turn"]
    end
    subgraph Async["Async: one loop, many requests"]
        A1["request A: await API"] -.->|"loop is free"| A2["request B runs"]
        A2 -.-> A3["request A resumes"]
    end

An awaiting coroutine hands control back to the event loop, which can run another request meanwhile.

WSGI and ASGI

Django talks to web servers through a standard interface. WSGI (the older one) is strictly synchronous: one call, one response. ASGI (Asynchronous Server Gateway Interface) supports async code, long-lived connections such as WebSockets, and still runs ordinary synchronous Django code. A new startproject creates both wsgi.py and asgi.py.

An ASGI application is just an async callable with three arguments:

  • scope: a dictionary describing the connection (type "http" or "websocket", path, method, headers).
  • receive: an async function that returns incoming events, such as the request body.
  • send: an async function that you call with outgoing events, such as the response start and body.

Django's get_asgi_application() returns such a callable. To make the protocol concrete, the first example below implements a tiny ASGI app by hand and calls it with a small test harness, which is exactly what servers like Uvicorn, Daphne or Hypercorn do over a real socket.

Python A hand-written ASGI application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Django's own ASGI handler does the same job but also builds an HttpRequest, runs your middleware chain, resolves the URL and sends the HttpResponse back as these events. You never write this by hand, but knowing it helps when you debug servers and deploy (see Deploying Django).

Async views

An async view is a view defined with async def. It receives the same HttpRequest and returns an HttpResponse:

Python
# read-only
from django.http import JsonResponse
import httpx


async def weather(request, city):
    async with httpx.AsyncClient() as client:
        reply = await client.get(f"https://api.example.com/weather/{city}")
    return JsonResponse(reply.json())

Django detects the coroutine function and awaits it. Under an ASGI server the view runs directly on the event loop. Under WSGI Django still runs it, but wraps it so each request blocks its worker, so you gain nothing there.

The real benefit appears when one view needs several independent slow calls. With asyncio.gather they wait at the same time instead of one after another. The example below uses asyncio.sleep(0) ticks instead of real delays so that the output is fully deterministic: every await asyncio.sleep(0) is a moment where the coroutine yields control. It runs the view directly with await, which avoids needing a thread or an ASGI server.

Python Concurrent work inside an async view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the two logs. With gather, all three tasks start before any finishes, and the one needing the fewest ticks (tax) finishes first. Awaiting them one by one runs each to the end before the next starts, so the total waiting time adds up. With real network calls the first version takes roughly as long as the slowest call, the second as long as all of them together.

Never call blocking code inside an async view: time.sleep(), the requests library, or a synchronous ORM query. A blocking call freezes the whole event loop, so every other request in that process stalls. Use await asyncio.sleep(), an async HTTP client such as httpx.AsyncClient, or the async ORM methods below.

The async ORM

Django's database layer is still fundamentally synchronous, and Django does not pretend otherwise. Instead, it offers async versions of the query methods, prefixed with a, and they run the real query in a worker thread for you:

Sync Async
get(), first(), last(), count(), exists() aget(), afirst(), alast(), acount(), aexists()
create(), get_or_create(), update(), delete() acreate(), aget_or_create(), aupdate(), adelete()
bulk_create(), in_bulk(), aggregate() abulk_create(), ain_bulk(), aaggregate()
obj.save(), obj.delete(), obj.refresh_from_db() await obj.asave(), await obj.adelete(), await obj.arefresh_from_db()
for x in queryset async for x in queryset

Building a queryset (filter(), exclude(), order_by()) does no database work, so those stay ordinary calls. Only the methods that hit the database have a variants. Here is a view that uses them:

Python
# read-only (needs a real database; see the note below)
async def note_list(request):
    created = await Note.objects.acreate(text="first")
    same = await Note.objects.aget(pk=created.pk)
    texts = [n.text async for n in Note.objects.order_by("text")]
    exists = await Note.objects.filter(text="missing").aexists()
    return JsonResponse({"first": same.text, "all": texts, "missing_exists": exists})

Two gotchas catch beginners. First, relations are not loaded lazily in async code: touching book.author on an unfetched foreign key raises SynchronousOnlyOperation, so use select_related() or prefetch_related() (see ORM Performance) or await aget() on the related model. Second, transaction.atomic() is not async-aware: wrap the transactional code in a normal function and call it with sync_to_async.

This tutorial cannot run the async ORM live. The a methods hand the query to a worker thread, and a browser tab cannot start threads. They also show a subtle pitfall on a real machine: each thread gets its own database connection, so an in-memory SQLite database (":memory:") appears empty inside the worker thread. Use a file-based SQLite database or PostgreSQL when you try this at home.

sync_to_async and async_to_sync

Sometimes you need to cross the boundary. The asgiref package, which Django depends on, provides two adapters:

  • sync_to_async(func) turns a blocking function into an awaitable that runs in a thread, so the event loop stays free.
  • async_to_sync(coro_func) does the reverse: it lets synchronous code call an async function and wait for the result.
Python
# read-only
from asgiref.sync import sync_to_async, async_to_sync


def slow_report():
    # blocking code, perhaps a library with no async support
    return build_pdf()


async def report_view(request):
    pdf = await sync_to_async(slow_report)()
    return HttpResponse(pdf, content_type="application/pdf")


def sync_helper():
    return async_to_sync(fetch_price)("tax", 1)

By default sync_to_async is thread_sensitive=True: all such calls share one thread, which keeps database connections and thread-local data safe. Leave it on unless you know the function is thread-safe and independent. Also remember that Django's synchronous views run just fine under ASGI: Django runs them in that shared thread automatically, which is slower than an async view because of the thread hop.

Async middleware

Middleware (see Middleware) can be sync, async or both. A class declares what it supports with sync_capable and async_capable. If the next layer in the chain is a coroutine function, the middleware should mark itself as a coroutine function too, using markcoroutinefunction. Django then calls it with await.

Python An async-capable middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real project you would list TraceMiddleware in MIDDLEWARE and Django would build the chain, adapting any sync-only middleware around it automatically. Each adaptation costs a thread hop, so when you run under ASGI, prefer middleware that supports async to avoid unnecessary switching.

Channels, WebSockets and what async is for

Async views make plain HTTP more efficient, but the feature that truly needs ASGI is a persistent connection. Django Channels is an official extension that adds WebSocket handling, background workers and group messaging (for chat, live notifications or dashboards) on top of ASGI. It routes WebSocket connections to consumers, classes with connect, receive and disconnect methods, and uses a channel layer (usually Redis) to send messages between processes. It needs a real server and Redis, so it is shown here as concepts only.

When should you go async? Choose it when views spend most of their time waiting on other services, for many concurrent connections, or for WebSockets. Stay synchronous for ordinary database-heavy pages: the synchronous ORM is mature, simpler to reason about, and adding workers scales it well. Many successful projects mix both, with a few async views next to many sync ones.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is an ASGI application at its simplest?

    ASGI defines an async callable that receives a scope describing the connection plus receive and send functions for incoming and outgoing events. Servers such as Uvicorn call it.
  2. 2. Why is calling time.sleep(5) inside an async view a problem?

    A blocking call never yields control to the event loop, so nothing else can run until it returns. Use await asyncio.sleep() or other async libraries instead.
  3. 3. Which statement about the async ORM is correct?

    filter() only builds a queryset and does no I/O, so it stays as is. aget(), acreate(), acount() and async for run the actual queries, and unfetched related objects raise SynchronousOnlyOperation unless you use select_related.
  4. 4. What does sync_to_async(func) do by default?

    With thread_sensitive=True, the default, blocking functions are run in one shared thread, which keeps database connections and thread-local state consistent while the event loop stays free.
  5. 5. Which feature really requires ASGI rather than WSGI?

    WSGI handles one request and one response. Long-lived connections such as WebSockets need ASGI, which is what Django Channels builds on.

Summary

  • Async views use async def and shine when a request mostly waits on other services; they do not speed up CPU-bound work.
  • ASGI servers call an async (scope, receive, send) application; Django's get_asgi_application() is one, and WSGI stays synchronous.
  • Use asyncio.gather for independent waits, and never block the event loop with time.sleep, requests or sync ORM calls.
  • The async ORM offers aget, acreate, acount, asave, async for and more; they run in a thread, and related objects need select_related or an await.
  • sync_to_async and async_to_sync cross the sync/async boundary; async-capable middleware avoids extra thread hops.
  • Channels adds WebSockets on top of ASGI; plain database-heavy pages are often best left synchronous.

Next lesson: Connecting Django with a React Frontend.