Performance: Lifespan context manager
MEDIUM IMPACT
This affects the startup and shutdown phases of a FastAPI app, impacting initial load time and resource cleanup.
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 |