Bird
Raised Fist0
FastAPIframework~10 mins

Connection lifecycle management in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Connection lifecycle management
Start Request
↓
Open Connection
↓
Process Request
↓
Close Connection
↓
End Request
This flow shows how FastAPI opens a connection at the start of a request, processes it, then closes the connection at the end.
Execution Sample
FastAPI
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session

app = FastAPI()

def get_db():
    db = Session()
    try:
        yield db
    finally:
        db.close()
This code manages a database connection lifecycle by opening a session before a request and closing it after.
Execution Table
StepActionConnection StateYielded ValueNotes
1Request receivedNo connectionNoneStart handling request
2Call get_db()Open connectiondb session objectConnection opened and yielded
3Process endpoint using dbConnection opendb session objectUse connection for queries
4Request processing doneConnection opendb session objectReady to close connection
5Exit get_db() generatorConnection closedNoneConnection closed in finally block
6Response sentNo connectionNoneRequest fully handled
💡 Request ends after connection is closed and response is sent
Variable Tracker
VariableStartAfter Step 2After Step 5Final
dbNoneSession object (open)None (closed)None (closed)
Key Moments - 2 Insights
Why does the connection stay open during request processing?
Because the connection is yielded by the generator at Step 2 and only closed after the request finishes at Step 5, allowing the endpoint to use it.
What ensures the connection is closed even if an error occurs?
The finally block in the generator function always runs after yielding, closing the connection regardless of errors, as shown in Step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the connection opened?
AStep 1
BStep 4
CStep 2
DStep 5
💡 Hint
Check the 'Connection State' column in the execution table at Step 2
At which step does the connection close?
AStep 5
BStep 4
CStep 3
DStep 6
💡 Hint
Look for 'Connection closed' in the 'Connection State' column
If the finally block was removed, what would happen?
AConnection would never open
BConnection might stay open after request ends
CConnection would close earlier
DNo change in connection lifecycle
💡 Hint
Refer to Step 5 where connection is closed in finally block
Concept Snapshot
FastAPI connection lifecycle:
- Open connection before request (yield in dependency)
- Use connection during request
- Close connection after request (finally block)
- Ensures resources free even on errors
- Use generator dependencies for clean lifecycle
Full Transcript
In FastAPI, connection lifecycle management means opening a connection at the start of a request and closing it at the end. This is often done using a generator function dependency that yields a connection object. When the request starts, FastAPI calls the generator, opening the connection and yielding it to the endpoint. The endpoint uses this connection to process the request. After the request finishes, FastAPI continues the generator, which runs the finally block to close the connection. This ensures connections do not stay open and resources are freed properly, even if errors occur during processing.

Practice

(1/5)
1. What is the main purpose of using yield in FastAPI dependencies for connection lifecycle management?
easy
A. To setup a resource before the request and clean it up after the request
B. To define a synchronous function only
C. To permanently keep a connection open for all requests
D. To return multiple values from a function

Solution

  1. Step 1: Understand yield in dependencies

    In FastAPI, yield is used in dependencies to create a setup before the request and a cleanup after the request finishes.
  2. Step 2: Identify the lifecycle role

    This pattern ensures resources like database connections open before and close after each request, preventing leaks.
  3. Final Answer:

    To setup a resource before the request and clean it up after the request -> Option A
  4. Quick Check:

    Yield in dependencies = setup and cleanup per request [OK]
Hint: Yield in dependencies means setup before and cleanup after request [OK]
Common Mistakes:
  • Thinking yield returns multiple values at once
  • Assuming yield keeps connection open forever
  • Confusing yield with async context managers
2. Which of the following is the correct way to define a FastAPI dependency that opens a connection before a request and closes it after using yield?
easy
A. def get_conn(): conn = open_conn() yield conn return conn.close()
B. def get_conn(): conn = open_conn() return conn conn.close()
C. async def get_conn(): conn = open_conn() yield conn conn.close()
D. def get_conn(): conn = open_conn() yield conn conn.close()

Solution

  1. Step 1: Check the use of yield for setup and cleanup

    def get_conn(): conn = open_conn() yield conn conn.close() correctly uses yield to provide the connection and then closes it after the request.
  2. Step 2: Identify syntax and flow correctness

    def get_conn(): conn = open_conn() return conn conn.close() returns before closing, so cleanup never runs. async def get_conn(): conn = open_conn() yield conn conn.close() mixes async with a sync open_conn (may cause issues). def get_conn(): conn = open_conn() yield conn return conn.close() returns early after yield, skipping cleanup.
  3. Final Answer:

    def get_conn(): conn = open_conn() yield conn conn.close() -> Option D
  4. Quick Check:

    Yield then cleanup = correct dependency pattern [OK]
Hint: Yield must be followed by cleanup code, not return [OK]
Common Mistakes:
  • Placing return before cleanup code
  • Using async without async resource
  • Returning after yield instead of cleanup
3. Given this FastAPI dependency:
async def get_db():
    db = await connect_db()
    try:
        yield db
    finally:
        await db.disconnect()
What happens when a request finishes using this dependency?
medium
A. An error occurs because yield cannot be used with async
B. The database connection remains open for reuse
C. The database connection is closed asynchronously after the request
D. The connection is closed before the request starts

Solution

  1. Step 1: Analyze async dependency with yield and finally

    The yield pauses the function to provide db during the request, then finally runs cleanup after the request.
  2. Step 2: Understand async cleanup

    The await db.disconnect() runs after the request finishes, closing the connection asynchronously.
  3. Final Answer:

    The database connection is closed asynchronously after the request -> Option C
  4. Quick Check:

    Async yield with finally = async cleanup after request [OK]
Hint: Async yield with finally cleans up after request ends [OK]
Common Mistakes:
  • Thinking yield can't be async
  • Assuming connection stays open
  • Confusing order of cleanup
4. Identify the error in this FastAPI startup event handler:
@app.on_event("startup")
@asynccontextmanager
async def startup():
    await connect_to_service()
    yield
    await disconnect_from_service()
medium
A. Missing async keyword before function definition
B. Cannot combine @app.on_event with @asynccontextmanager on the same function
C. Yield cannot be used in async functions
D. No error, this is correct usage

Solution

  1. Step 1: Understand decorator usage for startup events

    The @app.on_event("startup") expects a normal async function, not an async context manager.
  2. Step 2: Recognize conflict of decorators

    Using @asynccontextmanager with @app.on_event on the same function is invalid because FastAPI expects a coroutine, not a context manager.
  3. Final Answer:

    Cannot combine @app.on_event with @asynccontextmanager on the same function -> Option B
  4. Quick Check:

    @app.on_event and @asynccontextmanager cannot be combined [OK]
Hint: Don't mix @app.on_event with @asynccontextmanager on one function [OK]
Common Mistakes:
  • Assuming yield is invalid in async functions
  • Forgetting async keyword
  • Thinking this pattern is valid
5. You want to manage a database connection pool that opens once when the FastAPI app starts and closes when it shuts down. Which is the best way to implement this lifecycle management?
hard
A. Use @app.on_event("startup") to open and @app.on_event("shutdown") to close the pool directly without context managers
B. Use a dependency with yield to open and close the pool per request
C. Open the pool globally outside FastAPI and never close it
D. Use @asynccontextmanager to create a context manager function and call it in @app.on_event("startup") and @app.on_event("shutdown")

Solution

  1. Step 1: Understand app-wide resource lifecycle

    A connection pool should open once at app startup and close at shutdown, not per request.
  2. Step 2: Choose correct FastAPI pattern

    Using @app.on_event("startup") and @app.on_event("shutdown") to open and close the pool directly is the simplest and recommended way.
  3. Step 3: Why not others?

    Use @asynccontextmanager to create a context manager function and call it in @app.on_event("startup") and @app.on_event("shutdown") misuses @asynccontextmanager with events. Use a dependency with yield to open and close the pool per request opens/closes per request, which is inefficient. Open the pool globally outside FastAPI and never close it never closes, risking resource leaks.
  4. Final Answer:

    Use @app.on_event("startup") to open and @app.on_event("shutdown") to close the pool directly without context managers -> Option A
  5. Quick Check:

    App startup/shutdown events manage global resources best [OK]
Hint: Use startup and shutdown events for global resource management [OK]
Common Mistakes:
  • Opening/closing pool per request wastes resources
  • Not closing pool causes leaks
  • Misusing asynccontextmanager for app events
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard