﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37302	Are database connections still async_unsafe?	Gyeongjae Choi		"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:

- [#11209 Added ASGI handler and coroutine-safety](https://github.com/django/django/pull/11209)

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:

- [#367 Allow nesting sync_to_async via asyncio.wait_for](https://github.com/django/asgiref/pull/367)

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?


"	Cleanup/optimization	new	Database layer (models, ORM)	6.1	Normal		async, database	Gyeongjae Choi	Unreviewed	0	0	0	0	0	0
