0
0
FastAPIframework~3 mins

Why Lifespan context manager in FastAPI? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple context manager can save your app from hidden crashes and resource leaks!

The Scenario

Imagine you have a web app that needs to connect to a database and start background tasks every time it runs. You try to open connections and start tasks manually in many places in your code.

The Problem

Doing this manually means you might forget to close connections or stop tasks properly. This can cause your app to slow down, crash, or leak resources without clear errors.

The Solution

The lifespan context manager in FastAPI lets you define startup and shutdown actions in one place. It automatically runs your setup code when the app starts and cleanup code when it stops, keeping things neat and safe.

Before vs After
Before
async def startup():
    await connect_db()

async def shutdown():
    await disconnect_db()

app.add_event_handler('startup', startup)
app.add_event_handler('shutdown', shutdown)
After
from fastapi import FastAPI

app = FastAPI()

@app.lifespan
async def lifespan(app):
    await connect_db()
    yield
    await disconnect_db()
What It Enables

This lets your app manage resources cleanly and reliably, so it runs smoothly without leaks or crashes.

Real Life Example

Think of a coffee machine that automatically starts heating water when turned on and cleans itself when turned off. The lifespan context manager does the same for your app's resources.

Key Takeaways

Manual resource management is error-prone and messy.

Lifespan context manager centralizes startup and shutdown logic.

It ensures clean, reliable app behavior and resource use.