Skip to main content

Async with Django

Working with Django in ASGI mode can benefit applications with long requests where the synchronous mode may be a bit wasteful, as you would likely need a ton of workers—especially if those workers are processes (e.g., Gunicorn). Your app may also run some fancy new LLM framework which is often async only.


That said, async mode isn't a silver bullet for scaling. In Django 5.1, you still need threads to offload blocking database operations, which remain synchronous by design.

Django provides async query wrappers like aget, acount, and aall, but these are just syntactic sugar for offloading the operation to a worker thread via asgiref.sync_to_async.

You can use the asgiref package's sync_to_async utility to move blocking executions to the worker. By default, that is a ThreadPoolExecutor with one worker. This thread is shared by all sync_to_async calls during the request context, effectively meaning that each request spawns one worker thread for all sync work.

So, to summarize:

  • The async main thread handles HTTP calls or non-blocking tasks (e.g., LLM requests, httpx calls...).
  • But the moment your view touches the database (or any blocking operation), Django spawns a thread.
  • That thread lives for the entire request, holding a DB connection open until the request is complete.

This thread-per-request operation is mostly fine—this has been the default modus operandi for web apps for years, at least before event loops, green threads, and coroutines took over. Of course, it's a bit wasteful, but it's not like we don't do wasteful things as programmers.

So, you can choose between creating a lot of workers or spawning a thread-per-request. Latter is arguably better since with thread you don't have to think about forking and shared memory, and a thread is likely much lighter than, say, a full-blown Gunicorn worker.

Another thing to consider with long requests are of course the DB connections. As said, the DB connection starts when you perform your first operation and stays open for the full request. This is problematic for high-load systems due to the expense of connections to DBs like Postgres.

Django 5.1 introduced the Psycopg 3 connection pooling option, which can help here. During your long request, you likely don't need to keep the connection open at all times, but you can return it to the pool. That's a bit annoying, of course, since you need to manually find where you wait for I/O (like a complex LLM call) outside DB operations for a prolonged time and manually close the connection. It is performant, though, since the actual DB connection doesn't get closed; only the requests handle to it.

It would be fantastic in this era of LLM streaming or long polling if Django supported async DB connections. It would eliminate the need to spawn a thread for each request. Combined with that, it would be fantastic if we were able to configure Django to return an idling DB connection to the Psycopg pool automatically (though I'm not sure how feasible that is).

Comments

Popular posts from this blog

I'm not a passionate developer

A family friend of mine is an airlane pilot. A dream job for most, right? As a child, I certainly thought so. Now that I can have grown-up talks with him, I have discovered a more accurate description of his profession. He says that the truth about the job is that it is boring. To me, that is not that surprising. Airplanes are cool and all, but when you are in the middle of the Atlantic sitting next to the colleague you have been talking to past five years, how stimulating can that be? When he says the job is boring, it is not a bad kind of boring. It is a very specific boring. The "boring" you would want as a passenger. Uneventful.  Yet, he loves his job. According to him, an experienced pilot is most pleased when each and every tiny thing in the flight plan - goes according to plan. Passengers in the cabin of an expert pilot sit in the comfort of not even noticing who is flying. As someone employed in a field where being boring is not exactly in high demand, this sounds pro...

Canyon Precede:ON 7

I bought or technically leased a Canyon Precede:ON 7 (2022) electric bike last fall. This post is about my experiences with it after riding for about 2000 km this winter. The season was a bit colder than usual, and we had more snow than in years, so I properly put the bike through its paces. I've been cycling for almost 20 years. I've never owned a car nor used public transport regularly. I pedal all distances below 30km in all seasons. Besides commuting, I've mountain biked and raced BMX, and I still actively ride my road bike during the spring and summer months. I've owned a handful of bikes and kept them until their frames failed. Buying new bikes or gear has not been a major part of my hobby, and frankly, I'm quite sceptical about the benefits of updating bikes or gear frequently. I've never owned an E-bike before, but I've rented one a couple of times. The bike arrived in a hilariously large box. I suppose there's no need to worry about damage durin...

Emit structured Postgres data change events with wal2json

A common thing I see in an enterprise system is that when an end-user does some action, say add a user, the underlying web of subsystems adds the user to multiple databases in separate transactions. Each of these transactions may happen in varying order and, even worse, can fail, leaving the system in an inconsistent state. A better way could be to write the user data to some main database and then other subsystems like search indexes, pull/push the data to other interested parties, thus eliminating the need for multiple end-user originating boundary transactions. That's the theory part; how about a technical solution. The idea of this post came from the koodia pinnan alla podcast about event-driven systems and CDC . One of the discussion topics in the show is emitting events from Postgres transaction logs.  I built an utterly simple change emitter and reader using Postgres with the wal2json transaction decoding plugin and a custom go event parser. I'll stick to the boring ...