FastAPI resolves Depends() trees recursively and caches each dependency’s result per request by default (use_cache=True), so two dependencies asking for get_db share the same session. Code after yield runs after the response is sent (or on exception). In tests, app.dependency_overrides swaps dependencies without monkeypatching.
Follow-up Interview Question · What happens if an HTTPException is raised inside the cleanup code after yield?