Stop Memory Leaks | FastAPI Yield for Database Sessions

Analytics Vidhya · Beginner ·🔧 Backend Engineering ·1mo ago

Key Takeaways

Explains using FastAPI yield for database sessions to prevent memory leaks

Full Transcript

Hey, welcome back. In the last video you saw three dependencies, authorization, a database session, and an LLM client. The database session one used yield instead of return. We said we did explain that properly. That's exactly what this video is about. By the end, you will understand why yield exist in dependencies, when to use it, and how FastAPI handles cleanup automatically even when things go wrong. Look at the flow diagram on the screen. Request comes in, dependency runs, return value is passed, endpoint runs, request ends, and then cleanup with a big red cross. That's the problem. A return-based dependency is done the moment it returns. Once it hands the value to the endpoint, it has no way to run any code after the endpoint finishes. But some resources need exactly that. Database session Database sessions must be closed. HTTP client should be disconnected. File handles needs to be released. If you don't clean up these, you end up with leaked connection and resource exhaustion in production. That's the gap yield fills. Yield splits our dependency into two phases. Look at the code. Everything before the yield is setup. It runs first before your endpoint. The value after yield is what gets injected in your endpoint. And everything after the yield is cleanup. It runs after your endpoint finishes. In this example, setup runs, resource is injected, and the endpoint does its work, and then cleanup runs automatically. The callout at the bottom says it perfectly. Think of it like a try and final block wrapped around your endpoint. That's exactly what FastAPI does internally when it sees a yield dependency. So, here's the most common yield dependency you will write. Get DB. It opens a session local connection, then yield the DB session into the endpoint inside a try block. The finally block closes the connection after the endpoint finishes. The inline comment says it, always closes even on error. Look at the endpoint below. The DB parameter just declares depends get DB. The endpoint query start session by ID and returns the result. It never opens or closes anything. Fast API wire everything together, open before, inject during, close after. Now, the same pattern works for any external client. Two examples on screen. First, Qdrant vector store client. Qdrant client connects on setup, yields the client to the endpoint, and calls client close in the finally block after the request finishes. Second, an HTTPX async client. Same structure, but notice the difference. It uses async def and await client aclose. This matters because HTTPX async client is async and its close method is coroutine. You must await. And to do that, you need an async dependency function. If you use a regular def function here and call aclose without await, it won't actually close. Same pattern, but always match async client with async dependency functions. So, this slide shows exactly why finally is the right choice over writing cleanup code after yield. Look at the endpoint. It queries a document by ID. If it's not found, it raises a 404 HTTP exception. Without finally, that exception would bubble up before any cleanup code runs and the session would leak. With finally, it doesn't matter. The comment in the code says it. Directly run even if endpoint raises HTTP exception. The 404 gets raised, FastAPI formats the error response, and before sending it back to DB close, and before sending it back, DB.close executes. No leak session. No matter what happens inside your endpoint, the cleanup always runs. So, a quick recap. Yield dependency split into two phases. Setup before yield, cleanup after. Always use finally for cleanup block so it runs even when your endpoint raises an exception. The three most common use case in AR backends are database sessions, vector store clients, and HTTP clients. All three follow the same pattern. Define once, inject anywhere, and your endpoints never have to worry about closing anything. In the next video, we zoom out. As Karan's API grows, a single main.py file isn't enough. We will look at the API router, how to split a growing application into clean, organized modules. See you there.

Original Description

Description: This video clarifies the use of the `yield` keyword within `fastapi dependency injection`, contrasting it with `return` for robust `python web development`. We illustrate how `yield` manages setup and cleanup, ensuring resources are properly handled even during errors. This `tutorial` is essential for anyone looking to deepen their `python` `coding` and `programming` skills. Hashtags: #FastAPI #YieldDependency #DatabaseSession #Python #CleanCode
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related Reads

Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →