NestJS 서버리스

Lambda는 Nest 앱을 매 요청마다 새로 만드는 곳이 아니다

서버리스 NestJS의 핵심은 API Gateway 이벤트를 Nest request처럼 변환하고, cold start에서 만든 adapter와 application context를 warm invocation에 재사용하는 경계를 분명히 잡는 것이다.

실행 경계 지도

event to request
API Gateway에서 Lambda와 NestJS handler로 이어지는 서버리스 실행 흐름 API Gateway 이벤트가 Lambda handler에 들어오고 cold start에서는 Nest application context와 adapter를 만들며, warm invocation에서는 cache된 handler를 거쳐 guard, pipe, controller, service, database로 진행한다. API Gateway HTTP event / stage Lambda handler context / requestId Cold start boundary bundle load + NestFactory adapter cache 생성 Warm cache cached server Response status / body Adapter event 변환 Request scope guard / pipe interceptor Controller route handler DTO validation Provider service / repo pool 재사용 DB / Queue timeout 예산 request 상태는 invocation 밖으로 새면 안 된다 app bootstrap과 connection pool은 warm 재사용 후보
event API Gateway event

stage, path, headers, body가 Lambda handler 입력으로 들어온다.

handler Lambda handler + adapter

event를 Nest가 이해하는 request/response 형태로 바꾼다.

cold NestFactory bootstrap

cold start에서 앱과 adapter를 만들고 warm invocation에 재사용한다.

request Guard, pipe, controller, provider

요청별 상태는 이 경계 안에서 끝내고, pool 같은 자원만 재사용한다.

Lambda 수명 주기

cold vs warm
01

bundle load

런타임이 코드를 로드하고 환경 변수와 DI 토큰 정의를 읽는다.

init
02

Nest bootstrap

app context, route metadata, adapter를 만들고 cache 변수에 둔다.

NestFactory
03

event mapping

Gateway event를 request 객체로 바꾸고 응답 mapping 규칙을 적용한다.

serverlessExpress
04

request 처리

guard, pipe, interceptor, controller, provider가 invocation 안에서 끝난다.

handler(event)

상태 보존 경계

reuse map
cold start 처음 만들거나 컨테이너 교체 시 다시 만든다.
Nest app bootstrap 결과를 cache한다.
route metadata controller, pipe 설정을 재사용한다.
warm invocation 같은 컨테이너면 메모리와 pool이 남을 수 있다.
DB pool idle timeout과 connection storm을 같이 본다.
compiled handler adapter/server instance를 재사용한다.
request only invocation이 끝나면 버려야 하는 상태다.
user context 전역 변수에 저장하면 다음 호출로 샌다.
idempotency key retry 중복은 외부 저장소 기준으로 막는다.
cold start init duration 증가 bundle 크기, provider 초기화, DB 연결 생성이 cold path에 섞였는지 본다.
timeout Lambda 예산 초과 Gateway timeout, Lambda timeout, DB query timeout을 같은 값으로 보지 않는다.
payload event mapping 오류 binary body, stage path, multi-value header가 Nest route까지 보존되는지 확인한다.
retry 중복 실행 비동기 trigger나 client retry는 idempotency key와 로그 상관관계로 분리한다.
검증 질문

서버리스 NestJS는 “Nest가 뜬다”보다 경계와 수명 주기가 맞는지 확인해야 한다.

  • API Gateway event가 Nest request와 response code로 손실 없이 매핑되는가?
  • cold start에서만 필요한 bootstrap이 warm 호출마다 반복되지 않는가?
  • request별 user/session 상태가 singleton provider나 module 전역에 남지 않는가?