Under The Hood
backend fastapi FastAPI 0.100+ (Lifespan API)

Lifespan Context Manager (@asynccontextmanager) Startup and Shutdown Events

Last updated
Prerequisites:
Python `@contextlib.asynccontextmanager`
Database connection pool initialization
  • fastapi
  • lifespan
  • startup
  • shutdown
  • asynccontextmanager
  • starlette

Read at your depth

The practical view

The `lifespan` context manager handles application startup and shutdown in FastAPI, replacing deprecated `@app.on_event('startup')` and `@app.on_event('shutdown')`. Define an async context manager: `@asynccontextmanager async def lifespan(app: FastAPI): # startup logic; yield; # shutdown logic`. Pass it to your app: `app = FastAPI(lifespan=lifespan)`.

The same idea in other frameworks

fastapi equivalent
`@asynccontextmanager async def lifespan(app: FastAPI): ... yield ...`.

Legacy vs modern

Deprecated @app.on_event vs Modern Lifespan Context Manager

Deprecated `on_event` split startup and shutdown across separate decorators; `lifespan` manages lifecycle in a single context manager.

before → after
Deprecated on_event Decorators
@app.on_event('startup') ... @app.on_event('shutdown') ... // ❌ Deprecated in FastAPI
FastAPI Lifespan Context Manager
@asynccontextmanager async def lifespan(app: FastAPI): yield // ✅ NEW: Unified state & teardown

Interview gotchas

Context

Interviewers test your knowledge of ASGI protocol evolution and state management.

The mechanical answer

`@app.on_event` split initialization and teardown into disconnected functions, forcing shared resources (like database pools or ML models) to be stored in error-prone global variables. `lifespan` uses a standard Python async context manager (`@asynccontextmanager`), keeping setup and teardown within the same lexical scope and guaranteeing that exceptions in startup cleanly trigger teardown logic in `finally` blocks.

Trap

Using `@app.on_event` in modern FastAPI will emit deprecation warnings.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.