본문 바로가기
Backend2026년 4월 24일10분 읽기

Deno 3.0 Lambda — 콜드 스타트 50ms 이내 패턴

YS
김영삼
조회 1
Deno 3.0 Lambda — 콜드 스타트 50ms 이내 패턴

핵심 요약

Lambda 콜드 스타트의 적은 Node.js 패키지 부팅. Deno 3.0은 단일 바이너리 + JIT으로 50ms 안에 시작 가능. 또한 TypeScript 네이티브, 보안 권한 모델 기본 탑재.

  • Deno 3.0 (2025-09) + Lambda provided.al2023
  • 콜드 스타트 평균 50ms (Node 18 대비 250ms)
  • TypeScript 컴파일 불필요
  • 외부 패키지 import URL 직접

1. 기본 핸들러

// handler.ts
export async function handler(event: any, context: any) {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Hello from Deno", event }),
    headers: { "Content-Type": "application/json" },
  }
}

2. Custom Runtime — bootstrap

#!/bin/sh
# bootstrap (Lambda Runtime)
set -e

# Lambda 환경에서 deno 실행
./deno run --allow-net --allow-env --allow-read=/var/task /var/task/handler.ts

3. Lambda Runtime API 통합

// runtime.ts — Lambda Runtime API 직접 호출
const RUNTIME_URL = `http://${Deno.env.get("AWS_LAMBDA_RUNTIME_API")}/2018-06-01/runtime`

async function next() {
  const r = await fetch(`${RUNTIME_URL}/invocation/next`)
  const event = await r.json()
  const requestId = r.headers.get("Lambda-Runtime-Aws-Request-Id")!
  return { event, requestId }
}

async function respond(requestId: string, response: any) {
  await fetch(`${RUNTIME_URL}/invocation/${requestId}/response`, {
    method: "POST",
    body: JSON.stringify(response),
  })
}

import { handler } from "./handler.ts"

while (true) {
  const { event, requestId } = await next()
  try {
    const result = await handler(event, { requestId })
    await respond(requestId, result)
  } catch (e) {
    await fetch(`${RUNTIME_URL}/invocation/${requestId}/error`, {
      method: "POST",
      body: JSON.stringify({ errorMessage: e.message })
    })
  }
}

4. 배포 — Container 또는 Layer

Container 방식

FROM public.ecr.aws/lambda/provided:al2023
COPY deno /usr/local/bin/deno
COPY bootstrap ${LAMBDA_RUNTIME_DIR}
COPY handler.ts runtime.ts ${LAMBDA_TASK_ROOT}/
CMD ["handler.handler"]

Compile 방식 — 단일 바이너리

deno compile --target x86_64-unknown-linux-gnu \
  --allow-net --allow-env --allow-read \
  --output bootstrap runtime.ts

# bootstrap 단일 파일 → Lambda Layer 또는 직접 배포
zip lambda.zip bootstrap
aws lambda update-function-code --function-name my-fn --zip-file fileb://lambda.zip

5. 콜드 스타트 비교

런타임p50p99패키지 크기
Node.js 20 (zip)180ms800ms50MB
Python 3.13140ms600ms30MB
Deno 3 (compile)50ms180ms80MB (단일 바이너리)
Rust + Lambda20ms80ms10MB

6. 의존성 — URL Import

import { z } from "https://deno.land/x/zod@v3.22.0/mod.ts"
import { Hono } from "https://deno.land/x/hono@v4.0.0/mod.ts"

const schema = z.object({
  email: z.string().email(),
})

Lock 파일 (deno.lock) 자동 관리. 배포 시 모든 의존성 컴파일에 포함.

7. Hono on Deno Lambda

import { Hono } from "https://deno.land/x/hono@v4.0.0/mod.ts"
import { handle } from "https://deno.land/x/hono@v4.0.0/adapter/aws-lambda/handler.ts"

const app = new Hono()
app.get("/", (c) => c.text("Hello"))
app.get("/users/:id", (c) => c.json({ id: c.req.param("id") }))

export const handler = handle(app)

8. 환경변수·Secrets

// 일반 env
const dbUrl = Deno.env.get("DATABASE_URL")!

// Secrets Manager
import { SecretsManager } from "npm:@aws-sdk/client-secrets-manager"
const sm = new SecretsManager()
const secret = await sm.getSecretValue({ SecretId: "my-secret" })

9. CloudWatch 로깅

// console.log → CloudWatch 자동
console.log(JSON.stringify({ level: "info", msg: "request", requestId, path }))
// JSON 구조화 로그가 가장 분석 쉬움

10. CI/CD — GitHub Actions

name: Deploy Lambda
on: { push: { branches: [main] } }

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: denoland/setup-deno@v1
      - run: deno test
      - run: |
          deno compile --target x86_64-unknown-linux-gnu \
            --allow-net --allow-env --allow-read \
            --output bootstrap runtime.ts
          zip lambda.zip bootstrap
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_ROLE }}
          aws-region: ap-northeast-2
      - run: aws lambda update-function-code --function-name my-fn --zip-file fileb://lambda.zip

11. 한계·주의

  • Deno deploy.com은 Lambda보다 더 단순한 대안 (Edge에서 동작, 콜드 스타트 0)
  • 일부 native node modules (canvas·sharp) 호환 불가
  • Lambda 빌드 시 ARM(graviton) target도 컴파일 가능 — 비용 20% 절감

12. Deno Deploy vs Lambda

항목Lambda + DenoDeno Deploy
콜드 스타트50ms0 (이미 워밍)
비용요청 단가 + 시간요청 단가 (단순)
지역1개 region30+ edge locations
AWS 통합강함 (IAM·VPC)제한적

자주 묻는 질문

Node.js 대신 Deno를 쓰는 이유?콜드 스타트 + TypeScript 네이티브 + 보안 권한 모델. 새 프로젝트는 Deno가 매력.

npm 패키지 사용?npm: prefix로 import (npm:@aws-sdk/client-s3). 호환성 95%+.

운영 안정성?3.0이라 안정. Deno Deploy로 1억+ 요청 처리하는 회사 다수.

댓글 0

아직 댓글이 없습니다.
Ctrl+Enter로 등록