#37302 new Cleanup/optimization

Are database connections still async_unsafe?

Reported by: Gyeongjae Choi Owned by:
Component: Database layer (models, ORM) Version: 6.1
Severity: Normal Keywords: async, database
Cc: Gyeongjae Choi Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi, I recently enjoyed listening to [Carlton Gibson's Django's Async Story podcast](https://talkpython.fm/episodes/show/556/updates-on-djangos-async-story), and exploring the Django's async feature.

One thing I noticed is that accessing database (using ORM's etc) is still marked as @async_unsafe, which raises SynchronousOnlyOperation error when you are in the event loop. It is also mentioned in the [documentation](https://docs.djangoproject.com/en/6.1/topics/async/#envvar-DJANGO_ALLOW_ASYNC_UNSAFE).

However, I was wondering if there are actually still async-unsafe.

When I tracked down the Git history, the @async_unsafe was first added in this PR in 2019:

If I am understanding correctly, at that time, the database connection was a threading.local(), which blocked database operations be performed when there is a running event loop since the database connection should not be shared between different tasks.

And in 2023, I found a PR in asgiref, changing the asgiref.local.Local() to context vars when there is a running event loop:

with that change, the database connection is not shared between different tasks since they would have different context vars per task.

So my question is, should database operations still be marked with async-unsafe? Are there other risks that could happen?

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top