Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 50 ยท Structuring larger apps

Lifespan events and app state

Learn the FastAPI lifespan context manager: run code at startup and shutdown, keep shared resources on app.state and run the lifespan in tests.

Some things should happen exactly once for the whole application, not once per request: opening a connection pool, loading a machine-learning model, warming a cache, or flushing buffers before the process exits. FastAPI calls these moments the lifespan of the app: the time between "the server has started" and "the server is stopping".

In this lesson you will write a lifespan function with asynccontextmanager, store shared resources on app.state, read them from endpoints through request.app.state and a dependency, and learn the one detail that surprises everybody in tests: the lifespan only runs if you ask for it.

The lifespan context manager

A lifespan is an async context manager that you pass to FastAPI(lifespan=...). Everything before yield is startup; everything after it is shutdown. The value you yield is optional.

Python
from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("starting")        # runs once, before the first request
    yield
    print("stopping")        # runs once, after the last request

app = FastAPI(lifespan=lifespan)

One app, one lifespan

Startup Code before yield runs once.
Serving Requests are handled while it is paused at yield.
Shutdown Code after yield runs once.
1 / 2

The old @app.on_event("startup") and @app.on_event("shutdown") decorators still exist but are deprecated. The lifespan form is better because setup and cleanup sit in one function, so a resource opened at startup is visibly closed at shutdown, and a try/finally can protect the cleanup.

If you pass a lifespan, the old on_event handlers are ignored. Pick one style per app, and pick lifespan.

Storing shared state

Where do you keep what you created at startup? FastAPI (through Starlette) gives every app an app.state object, a simple namespace to which you can attach attributes. Inside an endpoint, the same object is reachable as request.app.state.

sequenceDiagram
    participant S as Server
    participant L as lifespan
    participant E as Endpoint
    S->>L: start (before yield)
    L->>L: app.state.client = Client()
    S->>E: request
    E->>E: request.app.state.client
    S->>L: stop (after yield)
    L->>L: client.close()

The lifespan creates the resource once; every request reads it from app.state.

Module-level globals also work, but app.state has two advantages: it travels with the app instance (so tests that build their own app do not share hidden globals), and it makes the dependency on startup explicit.

Running the lifespan in the in-process client

The first thing to know when you test: httpx.ASGITransport does not send lifespan events. If you call the app directly the way earlier lessons did, startup never runs and app.state stays empty. Starlette's TestClient handles this when you use it as a context manager, but this site's runner uses httpx, so we enter the lifespan ourselves with app.router.lifespan_context(app).

The example uses a tiny stand-in for a database client, so you can watch the order of events.

Python Startup, requests and shutdown in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first call fails with an AttributeError because nothing created app.state.client. Inside the async with block the lifespan has started, so both requests succeed and share one client object (the query counter reaches 2). When the block ends, the code after yield runs and the client is closed.

A dependency for shared resources

Writing request.app.state.client in every endpoint is noisy and untyped. A small dependency fixes both. Dependencies were introduced in Dependencies; here the dependency's only job is to fetch the resource from the state.

Python
from typing import Annotated
from fastapi import Depends, Request

async def get_client(request: Request) -> FakeClient:
    return request.app.state.client

ClientDep = Annotated[FakeClient, Depends(get_client)]

@app.get("/items/{key}")
async def read_item(key: str, client: ClientDep):
    return await client.fetch(key)

Now the endpoint declares what it needs, editors know the type, and a test can replace the client with dependency_overrides without touching the lifespan at all.

Python State behind a dependency, and failing startup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note the last step of the output. When an override is installed, FastAPI never calls get_counter, so the lifespan is not needed: the fake counter starts at 100 and the first hit returns 101. And a lifespan that raises before yield aborts startup: a real server would refuse to start, which is exactly what you want when the database is down.

Design guidelines

  • Use try/finally around yield. The finally block runs on a normal shutdown and when something goes wrong while the app is running.
  • Create once, share everywhere. Clients such as httpx.AsyncClient and database engines are designed to be reused. Creating one per request wastes connections.
  • Keep startup fast. A health check from your host may time out if startup takes minutes. Load only what you need, or load in the background.
  • Do not store per-request data in app.state. It is shared by all requests at the same time. Use dependencies or request.state for per-request values.
  • Each worker runs its own lifespan. With four server worker processes you get four pools and four model copies. Size them accordingly.

Lifespan code is also the right home for work that Settings and configuration feeds: read the settings once, build the clients from them, and keep both on app.state.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which part of a lifespan function runs at shutdown?

    Everything before yield is startup. The code after yield runs when the app stops, which is where you close what you opened.
  2. 2. Why did the first request in the example fail with an AttributeError?

    The ASGI transport sends only HTTP requests. Enter app.router.lifespan_context(app) yourself (or use Starlette's TestClient as a context manager) to run startup and shutdown.
  3. 3. Where is the right place to keep per-request data such as the current user?

    app.state is shared by every request at the same time. Per-request values belong to dependencies or request.state.
  4. 4. What happens to @app.on_event handlers when you pass lifespan= to FastAPI()?

    When a lifespan is given, the deprecated event handlers are not used. Move their code into the lifespan function.

Summary

  • A lifespan is an async context manager passed as FastAPI(lifespan=...); code before yield is startup, code after it is shutdown.
  • Put shared, expensive resources (clients, pools, models) on app.state and read them with request.app.state.
  • Wrap access in a small dependency so endpoints get a typed object that tests can override.
  • httpx.ASGITransport does not run the lifespan: wrap your test calls in app.router.lifespan_context(app).
  • Use try/finally, keep startup quick, and remember that each worker process runs its own lifespan.

Next, learn how FastAPI runs your code concurrently in async def vs def endpoints.