Design DB transaction middleware and identify the background-task pitfall

Tests request-scoped DB lifecycle awareness. Strong answer: middleware closes the session on response, yet BackgroundTasks run afterward, so sharing that session causes crashes or leaks. Red flag: saying background tasks can reuse the request transaction.
Tests the lifecycle mismatch between request-scoped DB transactions and FastAPI BackgroundTasks. Strong answer: middleware commits or rolls back and closes the session when the response returns, but BackgroundTasks execute after the response is sent. Reusing that session causes closed-connection or detached-instance errors. The fix is to give background tasks their own fresh session or use an external worker. Red flag: suggesting background tasks can simply capture and reuse the request-scoped session.
Read the original → fastapi.tiangolo.com
- #fastapi
- #middleware
- #databases
- #background-tasks
- #transactions
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.