Software Engineer (SDE)fastapiintermediate3 interactive MCQs in app
DB Session Dependency Pattern
yield dependency try/except/finally session closepreventing DB connection pool exhaustionper-request session isolation
Core Concept
Database sessions MUST use a **`yield` dependency**: `session = SessionLocal(); try: yield session; finally: session.close()` (rollback on exception cleanly before close!). Notice FastAPI’s exit behavior: cleanup after `yield` runs **AFTER** the response is generated/returned cleanly (unless handling errors inside `try/except`), freeing pooled connections reliably without leaking pool slots!
Worked Example
`db = SessionLocal(); try: yield db; except Exception: db.rollback(); raise; finally: db.close()` guarantees connections return to the pool even on unhandled 500s!
Common Pitfall
opening a global shared session at module import time (breaks concurrency + leaks uncommitted state across requests) or omitting `rollback()` on exception.
Recommended Readings & Practice
Practice DB Session Dependency Pattern with 3 graded MCQs & written feedback.
Take SOARDO’s free 12-question diagnostic to see how strong you are across your target role and unlock adaptive daily missions.