Infrastructure as Code

Lambda와 API Gateway

meellon 2026. 7. 16. 09:10

학습 목표

handler·runtime·event/response 형식으로 Lambda 함수를 작성할 수 있다.

execution role·resource policy로 Lambda·API Gateway 권한을 최소로 연결할 수 있다.

REST APIHTTP API 차이를 보고 신규 API에 적합한 타입을 고를 수 있다.

Lambda proxy integration으로 API Gateway와 함수를 IaC(CDK) 로 배포할 수 있다.

앞 편 Serverless 아키텍처 선택 기준을 구체 구현으로 이어갈 수 있다.

문제 상황

  • 10편에서 sync API는 Lambda가 맞다고 했는데 — handlerevent 구조를 몰라 500만 반환
  • API Gateway REST로 만들었더니 비용·설정이 과함 — HTTP API가 있었다는 걸 늦게 발견
  • Lambda 권한 없음 — AccessDenied on dynamodb:GetItem — role에 policy 누락
  • API Gateway가 Lambda를 호출 못함lambda:InvokeFunction resource policy 미설정
  • 7편 CDK lambda.Function은 썼지만 — API 연결·route콘솔에서만
  • CORS preflight 403 — API·Lambda 둘 다 헤더 설정 필요
  • cold start 10편에서 봤지만 — memory·timeout을 코드에 어떻게 넣는지 모름

10편 Serverless 아키텍처에서 FaaS·이벤트·cold start를 봤다. 이번 편은 가장 흔한 조합HTTP API + Lambda — 의 handler·IAM·통합이다. SAM local invoke는 12편, SQS·EventBridge는 13편.

1. Lambda 핵심 — handler · runtime

Lambda는 이벤트를 받아 handler가 처리하고 결과를 반환한다.

요소 설명
Runtime Node 20, Python 3.12 등 — 실행 환경
Handler file.export — 예 index.handler
Event 트리거별 JSON — API는 HTTP 요청 매핑
Context requestId, getRemainingTimeInMillis()
Response 트리거별 스키마 — API는 statusCode·body
// code/handler.example.ts (발췌)
export const handler = async (event: APIGatewayProxyEventV2) => {
  if (event.requestContext.http.method === "GET" && event.rawPath === "/health") {
    return { statusCode: 200, body: JSON.stringify({ ok: true }) };
  }
  return { statusCode: 404, body: JSON.stringify({ error: "not found" }) };
};
  • Stateless — 요청 간 메모리 공유 금지 (warm 재사용은 best-effort)
  • /tmp쓰기 가능 — 512MB~10GB (메모리에 비례)
  • Timeout 기본 3초 — API는 API GW 29초 한도 안에서 설정
  • Package — zip 또는 container image (9편 asset)

2. API Gateway 이벤트 · 응답

Lambda proxy integration — API Gateway가 HTTP를 event로 넘기고, handler return을 HTTP로 변환.

필드 (HTTP API v2) 용도
requestContext.http.method GET, POST, …
rawPath /items
queryStringParameters ?page=1
headers authorization, content-type
body 문자열 — JSON은 parse
isBase64Encoded 바이너리 업로드
응답 필드 용도
statusCode 200, 201, 4xx, 5xx
headers content-type, cache-control
body 문자열 (JSON은 JSON.stringify)
  • 에러 — uncaught exception → API Gateway 502
  • Validation — API GW request validator (REST) 또는 handler에서 직접
  • LoggingrequestContext.requestId구조화 로그에 포함
  • Stage$default (HTTP API) 또는 prod (REST)

3. IAM — execution role · invoke permission

Lambda는 자신의 role으로 AWS API를 호출하고, API Gateway는 Lambda를 invoke권한이 필요하다.

주체 권한 대상
Lambda execution role dynamodb:GetItem, s3:PutObject 함수가 접근하는 리소스
API Gateway → Lambda lambda:InvokeFunction 함수 resource policy 또는 CDK integration이 자동
Caller → API IAM auth, JWT, API key API Gateway authorizer
// 7편 패턴 — grant로 최소 권한
bucket.grantRead(fn);
table.grantReadWriteData(fn);
  • Role — 함수당 1 execution role — policy 누적 주의
  • VPC Lambda — role에 ec2:CreateNetworkInterface추가 (7편)
  • Secrets — env에 평문 금지 — Secrets Manager + grant
  • Least privilege — 와일드카드 * 지양 — 리소스 ARN 명시

4. REST API vs HTTP API

신규 HTTP 백엔드는 대부분 HTTP API (v2) 가 단순·저렴하다.

  REST API (v1) HTTP API (v2)
비용 상대적 높음 낮음
지연 보통 더 낮음 (경량)
모델 resource·method 트리 route 중심
인증 IAM, Cognito, custom authorizer JWT·IAM·Lambda authorizer
기능 API key, usage plan, WAF 연동 풍부 핵심 HTTP 위주
CDK aws-apigateway aws-apigatewayv2
# code/api-type-comparison.yaml (발췌)
http:
  when:
    - "new public or internal HTTP API"
    - "JWT authorizer · lower latency · lower cost"
rest:
  when:
    - "API keys · usage plans · request validation"
    - "existing REST resource tree migration"
  • WebSocket — 별도 WebSocket API (본 편 범위 밖)
  • Private API — VPC endpoint + resource policy (10편 규제 시나리오)
  • Migration — REST → HTTP 1:1 아님 — route·authorizer 재설계

5. CDK — HTTP API + Lambda 스택

7·9편 CDK 패턴으로 한 스택에 API·함수를 선언한다.

// code/api-stack.example.ts (발췌)
const fn = new lambda.Function(this, "HttpApiHandler", {
  runtime: lambda.Runtime.NODEJS_20_X,
  handler: "handler.handler",
  code: lambda.Code.fromAsset("lambda"),
  timeout: cdk.Duration.seconds(10),
  memorySize: 256,
});

const httpApi = new apigwv2.HttpApi(this, "PublicApi", {
  corsPreflight: { allowOrigins: ["https://app.example.com"] },
});

httpApi.addRoutes({
  path: "/health",
  methods: [apigwv2.HttpMethod.GET],
  integration: new integrations.HttpLambdaIntegration("HealthInt", fn),
});
cdk synth && cdk deploy ApiStack   # bootstrap 필요 시 9편 참고
curl "$(aws cloudformation describe-stacks --stack-name ApiStack \
  --query 'Stacks[0].Outputs[?OutputKey==`ApiUrl`].OutputValue' --output text)/health"
  • HttpLambdaIntegration — invoke permission + proxy 연결 자동
  • CORS — API GW에서 preflight — handler는 실제 응답 헤더
  • Alias·stage — blue/green은 Lambda alias + weighted (19편 거버넌스)
  • 테스트Template.fromStack으로 route·IAM assertion (9편)

6. 운영 포인트

항목 권장
Memory 프로파일 후 설정 — CPU·cold start에 영향
Timeout downstream < API GW 29초
Concurrency reserved·account limit 사전 설계 (10편)
Logging JSON · requestId · PII 마스킹
Tracing X-Ray 선택 — latency 병목
Errors 4xx는 handler · 5xx·502는 알람

7. 실무 체크리스트

# 질문
1 handler가 event v2 형식에 맞는가 (HTTP API)
2 execution role이 필요 API만 허용하는가
3 API Gateway invoke 권한이 있는가
4 REST vs HTTP 선택 이유를 문서화했는가
5 CORS·4xx/5xx 응답 형식이 클라이언트와 합의됐는가
6 timeout·memory·concurrency가 SLO에 맞는가

정리

  • Handler — event in · response out · stateless
  • API Gateway proxy — HTTP ↔ Lambda 매핑 표준
  • IAM — execution role + invoke permission
  • HTTP API — 신규 HTTP에 기본 선택 · REST는 레거시·고급 기능
  • CDKHttpApi + HttpLambdaIntegration으로 재현 가능 배포
  • 12편 — SAM template·sam local invoke

다음에 다룰 것

  • SAM과 Serverless Framework
  • template.yaml, sam build/deploy, local invoke

해당 내용은 AWS Lambda Developer Guide, Amazon API Gateway Developer Guide 를 기반으로 합니다.

'Infrastructure as Code' 카테고리의 다른 글

Serverless 아키텍처  (0) 2026.07.12
CDK 테스트와 배포  (0) 2026.07.10
CDK vs Terraform  (0) 2026.07.10
CDK로 인프라 정의  (0) 2026.07.09
AWS CDK 개요  (0) 2026.07.07