When does Django actually observe cancellation in an async view after a client disconnects?
0 reputation · 07 Mar 2021, 07:01 UTC
I am designing an async view running under ASGI (Django 4.2+ assumed) that performs several awaits plus one expensive synchronous computation. My understanding is that when the client disconnects, the ASGI server cancels the request task and asyncio.CancelledError propagates — but only at the next await point. Blocking sync work inside the coroutine would delay that cancellation while still holding resources like database connections and locks.
The uncertainty is about where the boundary really sits. I want cleanup code (releasing a lock, closing a file, ending a transaction) to run reliably on disconnect, without accidentally swallowing the cancellation by catching broad exceptions. I also want to know whether wrapping sections in asyncio.wait_for changes how disconnect-driven cancellation is delivered, and whether a blocking call should be moved to a thread or a task queue instead.
At which exact points in an async view does Django/ASGI deliver cancellation, and is there any notification while a synchronous call is still executing?
Does asyncio.wait_for interact with server-initiated cancellation in a way that changes cleanup semantics?
Is sync_to_async with thread-sensitive mode a safe way to make blocking work cancellable, or does the thread keep running after the request task is cancelled?