← Back to FastAPI, page 2

fastapi-0030 · Medium mid

What is the lifespan function in FastAPI, and how do you use it for startup and shutdown work?

lifespan is an async context manager passed to FastAPI(lifespan=...). Code before its yield runs once at startup, before the app accepts requests, and code after yield runs at shutdown. Use it to create and close shared resources such as database engines, HTTP clients, caches or ML models, and store them on app.state or yield a state dict. It replaces the deprecated @app.on_event("startup") and ("shutdown") handlers.

Full answer

Some resources should be created once per process, not per request: a database engine with its connection pool, an httpx.AsyncClient, a Redis client, a loaded ML model. They also need clean shutdown.

python
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.http = httpx.AsyncClient(timeout=5)
    model = load_model()
    yield {"model": model}          # app runs while suspended here
    await app.state.http.aclose()

app = FastAPI(lifespan=lifespan)

How it runs:

  • The ASGI server sends a lifespan "startup" event when a worker starts. FastAPI runs the code up to yield. If it raises, startup fails and the worker does not serve traffic, which is good: better to fail loudly than to serve errors.
  • During yield, the app serves requests.
  • On shutdown (SIGTERM during a deploy, Ctrl+C), the code after yield runs. Wrap in try/finally if cleanup must run even when something fails.

Sharing resources with endpoints:

  • app.state.x (read through request.app.state.x).
  • Yield a dict: its keys become available as request.state.x in each request (Starlette copies the lifespan state into each request's state).
  • Wrap access in a dependency (def get_http(request: Request)) so tests can override it.

Notes:

  • @app.on_event("startup") is deprecated in FastAPI. Starlette 1.0 removed its own on_startup/on_shutdown arguments, so use lifespan in new code.
  • Each worker process runs its own lifespan. Four workers load the model four times and open four pools.
  • Mounted sub-applications do not get their own lifespan events, only the main app does.
  • In tests, with TestClient(app) as client: triggers lifespan; a client without with does not.
  • Keep startup fast; orchestrators kill slow-starting containers. Use readiness probes that check the resources are ready.
python
from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI, Request
from fastapi.testclient import TestClient

log = []


class FakeModel:
    def predict(self, marks: list[int]) -> str:
        return "on track" if sum(marks) / len(marks) >= 60 else "needs support"


class FakePool:
    def __init__(self):
        log.append("pool opened")

    async def close(self):
        log.append("pool closed")


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.pool = FakePool()
    log.append("model loaded")
    try:
        yield {"model": FakeModel()}
    finally:
        await app.state.pool.close()


app = FastAPI(lifespan=lifespan)


def get_model(request: Request) -> FakeModel:
    return request.state.model


@app.post("/predict")
def predict(marks: list[int], model: FakeModel = Depends(get_model)):
    return {"result": model.predict(marks)}


with TestClient(app) as c:
    log.append("serving")
    print(c.post("/predict", json=[72, 65, 58]).json())
    print(c.post("/predict", json=[40, 35, 52]).json())
print(log)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'result': 'on track'} {'result': 'needs support'} ['pool opened', 'model loaded', 'serving', 'pool closed']

Key points

  • Async context manager: before yield = startup, after = shutdown
  • Use for engines, HTTP clients, models: once per process
  • Share via app.state or a yielded state dict
  • Replaces deprecated on_event handlers
  • Runs per worker; TestClient needs 'with' to trigger it

Common mistakes

  • Using the deprecated @app.on_event decorators in new code
  • Creating an HTTP client or engine inside each request
  • Forgetting that every worker runs lifespan separately
  • Testing without 'with TestClient(app)' so startup never runs
  • Doing slow work at startup without readiness checks

Follow-ups

  • How would you load a 2 GB ML model without slowing every deploy?
  • How do you share a resource from lifespan with endpoints in a testable way?
  • What happens to in-flight requests during shutdown?

Tips

  • Describe exactly when each half runs
  • Show how endpoints get the resource
  • Mention the per-worker point and the TestClient detail