Start here. This is the direct spoken answer to practice first.
Overview
A yield dependency is a resource-owner boundary, so cleanup timing must match the response path.
A dependency with yield acquires a resource before the yield, provides the yielded value to downstream dependencies or the handler, and runs the code after yield as cleanup. A try/finally or context manager makes cleanup run when processing succeeds or fails. In current FastAPI, request scope is the default and cleanup runs after the response is sent; scope="function" cleans up after the handler finishes but before the response is sent. The chosen scope must keep the resource alive for every consumer that still needs it.