Lifespan quản lý resource cấp app như connection pool, cache client, ML model hoặc scheduler. Code trước yield chạy khi app startup, code sau yield chạy khi shutdown, giúp mở và đóng resource đúng vòng đời.
Ví dụ:
python
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.redis = await Redis.from_url(REDIS_URL)
yield
await app.state.redis.aclose()
app = FastAPI(lifespan=lifespan)Không nên tạo resource nặng ở global import nếu nó cần cleanup hoặc phụ thuộc cấu hình runtime.