The current middleware subclasses BaseHTTPMiddleware which per Kludex/starlette#919 and fastapi/fastapi#2086 will cause all background tasks to run before the response is sent. Better would be to not subclass BaseHTTPMiddleware.
Instead the class would look like:
class DBSessionMiddleware:
def __init__(self, app....)
....
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
with db():
await self.app(scope, receive, send)