Performance: Lifespan context manager
This affects the startup and shutdown phases of a FastAPI app, impacting initial load time and resource cleanup.
Jump into concepts and practice - no test required
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): # Async startup tasks await some_async_setup() yield # Async cleanup tasks await some_async_cleanup() app = FastAPI(lifespan=lifespan)
from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def startup_event(): # Blocking long task import time time.sleep(5) # blocks event loop @app.on_event("shutdown") async def shutdown_event(): # Cleanup without async pass
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking startup with sync sleep | N/A | N/A | Blocks LCP for seconds | [X] Bad |
| Async lifespan context manager | N/A | N/A | Non-blocking startup, fast LCP | [OK] Good |
lifespan context manager in a FastAPI application?yield inside the async function allows running code before and after the yield for startup and shutdown.async def lifespan(app):
print('Starting app')
yield
print('Stopping app')yield runs at startup, and code after yield runs at shutdown.async def lifespan(app):
print('Starting')
return
print('Stopping')yield to separate startup and shutdown code.return exits the function immediately, so shutdown code after it never runs.