Implement an async database session dependency using yield for setup and teardown
This tests async resource lifecycle management in FastAPI. A strong answer uses async def, yields a session inside try, closes in finally, and injects with Depends. A red flag is omitting finally or using sync def for async I/O, which leaks connections.
WHAT THIS TESTS: The interviewer is probing whether you understand that FastAPI dependencies can be async generators and that the framework guarantees the code after the yield runs as teardown. They want to see if you know how to protect that teardown with exception handling and how to correctly wire the dependency into an async path operation. This separates engineers who have merely used Depends from those who understand resource lifecycle management in an async context.
A GOOD ANSWER COVERS: First, declare the dependency as an async def function. Second, open the database session before the yield. Third, yield the session object so FastAPI injects it into the path operation. Fourth, wrap the yield in a try block and place the session close logic in a finally block so cleanup always runs even if the path operation raises an exception. Fifth, inject the dependency into an async def path operation using Depends. Optionally mention that FastAPI runs the code before yield, then sends the response, then runs the code after yield.
COMMON WRONG ANSWERS: A major red flag is using a regular def instead of async def when the database driver is async because FastAPI will run the dependency in a separate thread pool and you lose the performance benefits and risk thread safety issues. Another red flag is writing the cleanup code after the yield without a try finally block because an unhandled exception in the path operation would skip the teardown and leak connections. Some candidates also forget that the dependency itself must yield exactly once and behave like an async context manager.
LIKELY FOLLOW-UPS: The interviewer may ask what happens if you raise an HTTPException inside the dependency before the yield, or how to handle exceptions after the yield. They might also ask about sub-dependencies with yield, whether multiple yield dependencies run in parallel or sequence, or how background tasks interact with teardown since background tasks run after the response but share the same scope. Another follow-up is converting the generator into a real context manager using contextlib.asynccontextmanager.
ONE CONCRETE EXAMPLE: Imagine an async SQLAlchemy session. You write async def get_db_session followed by a colon and newline. Inside, you create session equals AsyncSession with engine. Then you write try, yield session, and finally await session close. In your path operation, you write async def read item with db equals Depends get db session. FastAPI will call get db session, run up to the yield, execute read item, send the response, and then resume get db session to run the finally block and close the connection.
Read the original → fastapi.tiangolo.com
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.