Trending

World technology news

→
Django 3.1: drawing the ORM boundary in async views
Software Engineering · 2020
Software Engineering2020

Django 3.1: drawing the ORM boundary in async views

Build a Django 3.1 ASGI status view that waits for two sources, keeps ORM work behind a synchronous adapter, and tolerates an individual timeout.

Archive retrospective · Topic year 2020

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. One page, three places to wait
  2. Different request paths under ASGI and WSGI
  3. Complete ORM work on the synchronous side
  4. Preserve useful results when one source times out
  5. Test the response separately from timing
  6. Give waiting an explicit budget

One page, three places to wait

A support status page reads published public desks from a local database and asks two independent sources about phone and ticket availability. One provider may take much longer than the other. Without defined behavior the entire page can appear unavailable even when it has useful data. Django 3.1, released August 4, 2020, added asynchronous views and middleware support. That made independent I/O waits easier to overlap. The synchronous ORM in that release required a separate boundary. This retrospective uses a synthetic service, with one quick fixture and one that exceeds a chosen timeout. Local desk information is required in this design. Channel state has a separate meaning and can explicitly be unknown while local data remains available.

Different request paths under ASGI and WSGI

A Django 3.1 function view declared with async def is eligible to run asynchronously. Under WSGI, Django can run the view in a one-off event loop for the request. It can still overlap concurrent external calls there, but the overall stack does not gain the benefits of an async request path. ASGI provides that potential when the request stack is compatible. A synchronous middleware component may cause the framework to adapt execution between modes. Keep required authentication and authorization in the request path. Document their placement and inspect which operations wait. Connection pools, server settings, and worker capacity all affect results. One quick successful GET cannot show that many concurrent requests can still be handled efficiently.

Database access flowConceptual sketch · summary of the article's technical flow

Complete ORM work on the synchronous side

The Django 3.1 ORM did not provide async query methods for this example. Build and evaluate the query in an ordinary function, then call it through sync_to_async with thread_sensitive=True. The adapter returns an evaluated list of dictionaries. Returning a lazy queryset or an object with unloaded relationships can move database work back into the async view when a serializer accesses it. The example returns the first ten published desks in a stable order and excludes internal staff identifiers and notes. If the public policy becomes viewer-specific, test it directly in the data lookup. For atomic writes complete the whole database transaction within one synchronous function. Several awaited calls do not by themselves establish one connection and transaction boundary.

from asgiref.sync import sync_to_async
from .models import SupportDesk

def public_desks():
    return list(
        SupportDesk.objects.filter(is_published=True)
        .order_by("slug").values("slug", "display_name")[:10]
    )

load_public_desks = sync_to_async(public_desks, thread_sensitive=True)

Preserve useful results when one source times out

The sample coroutine is a fixture and makes no external calls. Two operations start through asyncio.gather, and wait_for gives each operation its own time allowance. The phone is expected to return available while the ticket provider returns unknown with reason timeout. The consumer receives a source name with each result. Other provider faults need a defined policy; the sample converts only timeouts to a partial response. Failure of the required local list also needs its own visible outcome. A production async HTTP client would need bounded concurrency and connection reuse. A timeout limits the wait, but does not cap the number of connections opened by simultaneous visitors. When freshness matters, surface the source and time of the last successful result.

import asyncio
from django.http import JsonResponse

async def fixture_status(name):
    delays = {"phone": 0.01, "ticket": 0.1}
    await asyncio.sleep(delays[name])
    return "available"

async def result_for(name, timeout=0.05):
    try:
        state = await asyncio.wait_for(fixture_status(name), timeout)
        return {"name": name, "state": state}
    except asyncio.TimeoutError:
        return {"name": name, "state": "unknown", "reason": "timeout"}

async def status_view(request):
    desks = await load_public_desks()
    channels = await asyncio.gather(result_for("phone"), result_for("ticket"))
    return JsonResponse({"desks": desks, "channels": channels})

Test the response separately from timing

Use Django 3.1 AsyncClient to check the JSON response. Exercise two healthy sources, one timeout, and two timeouts with separate fixtures. Every channel should still have a clear state. For contract tests, have a fake provider raise asyncio.TimeoutError directly instead of relying on narrow real-time limits. Also run a few concurrent requests through the real ASGI entry point with a representative quick request alongside them. Blocking synchronous work and heavy CPU work can delay the quick request even when two calls are correctly written as coroutines. Check that the desk query runs once and response serialization adds no queries. That can catch a future field that unexpectedly performs lazy database access. Correct JSON can stay the same across deployments with different latency.

Give waiting an explicit budget

Define successful, partial, and local failure outcomes independently. A slow provider has a bounded wait and its channel remains identified in the response. A vendor's hourly request limit is another concern: concurrent waits do not reduce request volume. Choose refresh and reuse rules with measured demand. Record pool pressure and local query delay separately because they point to different fixes. Recheck synchronous adaptation when adding new middleware. The useful lesson from this feature is to make waiting part of the contract. State which operation may fail, which result may be partial, and what information the user receives. New providers can then be integrated without changing the meaning of healthy, delayed, or unavailable status.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

What is the most important unanswered question about this topic?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.