# Lifespan Events

*noun*

say it: **“LYFE-span ih-VENTS”** **/ˈlaɪfˌspæn ɪˈvɛnts/**

FastAPI's startup and shutdown code, written in one lifespan function: the part before yield runs once when the app starts, the part after when it stops.

## What is **Lifespan Events**?

A **lifespan** function runs setup code before the app starts serving (open connections, load models) and cleanup code when it shuts down.

```python
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = await connect()
    yield
    await app.state.db.close()

app = FastAPI(lifespan=lifespan)
```

## In a sentence

- “The **lifespan events** close the database connection when the app stops.”
- “Migrations run in the app's **lifespan events**, before the first request arrives.”

Level: Freelancer · [More FastAPI terms at this level](https://www.ask-codey.com/glossary?category=fastapi&level=4)

Updated: November 19, 2026

Source: https://www.ask-codey.com/glossary/lifespan-events
