๐Ÿ“ Fastapi

Lifespan Events in FastAPI

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
508
๐ŸŒณ
Level
Advanced

Lifespan โ€” manage application startup and shutdown (DB initialization, ML models, connection pools).

Modern Approach (FastAPI 0.95+)

from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: runs when the application starts
    print("Starting application...")
    await init_db()
    yield
    # Shutdown: runs when the application stops
    print("Stopping application...")
    await close_db()

app = FastAPI(lifespan=lifespan)

Usage Examples

Database Initialization

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Create tables on startup
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield
    # Close the connection pool
    await engine.dispose()

app = FastAPI(lifespan=lifespan)

Loading an ML Model

ml_model = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Load the model once on startup
    ml_model["classifier"] = load_model("model.pkl")
    yield
    # Clean up
    ml_model.clear()

app = FastAPI(lifespan=lifespan)

@app.post("/predict/")
def predict(data: PredictRequest):
    result = ml_model["classifier"].predict(data.features)
    return {"result": result}

Redis and HTTP Client

import httpx
import redis.asyncio as redis

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.redis = await redis.from_url("redis://localhost")
    app.state.http_client = httpx.AsyncClient()
    yield
    await app.state.redis.close()
    await app.state.http_client.aclose()

Accessing State in Endpoints

@app.get("/cache/{key}")
async def get_cache(key: str, request: Request):
    value = await request.app.state.redis.get(key)
    return {"value": value}

Deprecated Approach (startup/shutdown events)

# Old approach โ€” works, but not recommended
@app.on_event("startup")
async def startup():
    await init_db()

@app.on_event("shutdown")
async def shutdown():
    await close_db()

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Middleware and CORS in FastAPI

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 332
๐Ÿ“

HTTPException in FastAPI

Covered topics: Basic Usage, Status Codes, Error Details, Custom Headers.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 298
๐Ÿ“

Dependency Injection in FastAPI

Depends โ€” FastAPI's dependency injection system for reusing code across endpoints.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 306
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

FastAPI: From First Route to an AI-Powered Site Open course curriculum