FastAPI Lifespan Events
FastAPI 앱에는 시작과 종료 시점에 딱 한 번씩 실행되는 lifecycle hook이 있다. HTTP 요청이 들어오기 전에 DB 연결이나 캐시 로딩 같은 준비 작업을 해두기 위한 장치다.
@app.on_event("startup") — 구식 방법 (deprecated)
@app.on_event("startup")
async def startup():
await db.connect()
@app.on_event("shutdown")
async def shutdown():
await db.disconnect()
데코레이터가 "이 함수를 startup 이벤트 발생 시 실행해라"고 등록한다. app.on_event("startup")(startup)와 동일한 의미.
FastAPI 0.93부터 deprecated.
lifespan — 현재 권장 방법
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
await db.connect() # startup: yield 이전
yield
await db.disconnect() # shutdown: yield 이후
app = FastAPI(lifespan=lifespan)
yield 하나로 startup/shutdown을 한 블록에 표현한다. 자원 관리가 명확하고, Python의 context-manager 패턴과도 일치해서 더 직관적이다.
언제 쓰나
- DB connection pool 초기화
- ML 모델 로딩 (매 요청마다 로드하면 너무 느리니까)
- 외부 서비스 연결 및 종료 시 정리
- 설정 파일/캐시 미리 로딩