← Back to articles

FastAPI · Resource Management

FastAPI Yield Dependencies: Keep Resource Cleanup Close to Setup

Use yield and finally to release request resources predictably while keeping transaction decisions explicit.

A request capsule borrows a golden connection key from a database dock and returns it along a curved track.
Pair resource acquisition with a clear cleanup path.

A request may borrow a database session or another short-lived resource. FastAPI dependencies with yield keep acquisition and cleanup together, reducing the chance that an error skips resource release.

Define the lifecycle
Create the resource before yield, yield it once, and release it in finally. The yielded value becomes the argument injected into the endpoint. For a synchronous session factory, the structure is:

def get_session():
session = make_session()
try:
yield session
finally:
session.close()

Here, make_session is your application’s configured factory. Match synchronous or asynchronous cleanup to the client library you actually use.

Let failures remain visible
Exceptions from the endpoint can reach the dependency. If you catch one to add context, re-raise it or deliberately translate it into the intended error. Silently swallowing an exception makes diagnosis harder.

Separate cleanup from business success
Closing a session is resource management. Decide explicitly where transactions commit or roll back; do not treat reaching cleanup as proof that a business operation succeeded.

Test both paths
Verify release after a successful request and after an endpoint exception. When streaming responses or background work use resources, review dependency lifetime rules for your installed FastAPI version.