OPEN HYPER STEP
← 목록으로 (stack-analysis)
STACK-ANALYSIS · 116 / 120
stack-analysis
CHAPTER 116 / 120
읽기 약 2
FUNCTION

서버리스: Vercel Edge + AWS Lambda


핵심 개념

cold start·edge runtime·콜드 스타트·비용 모델 — 서버 없이 확장.

본문

서버리스 종류

📋 코드 (18줄)
Vercel Functions
- Node.js + Edge runtime
- Next.js 자동 통합
- 자동 글로벌 분산

AWS Lambda
- 다양한 런타임
- 자체 인프라 통합
- VPC 연결

Cloud Functions (GCP)
- Google 인프라
- BigQuery 연계 강함

Cloudflare Workers
- 가장 빠른 cold start
- WebAssembly 지원
- 가장 저렴

Vercel Edge Functions

TYPESCRIPT📋 코드 (20줄)
// app/api/hello/route.ts
export const runtime = 'edge';

export async function GET(request: Request) {
  // Edge runtime — 글로벌 분산
  // 콜드 스타트 거의 없음
  // 단, Node.js API 일부 미지원

  return Response.json({
    region: process.env.VERCEL_REGION,
    timestamp: Date.now(),
  });
}


// 제약:
// - fs, child_process 없음
// - 실행 시간 30s
// - 메모리 128MB
// - native modules X (예: bcrypt → Web Crypto 사용)

AWS Lambda

TYPESCRIPT📋 코드 (35줄)
// 핸들러
export const handler = async (event: any) => {
  const { httpMethod, path, body } = event;

  // 비즈니스 로직
  const result = await processRequest(body);

  return {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(result),
  };
};


// SAM template
Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./
      Handler: dist/handler.handler
      Runtime: nodejs20.x
      MemorySize: 1024
      Timeout: 30
      ReservedConcurrentExecutions: 100
      Environment:
        Variables:
          DATABASE_URL: !Ref DbSecret
      Events:
        Api:
          Type: HttpApi
          Properties:
            Path: /{proxy+}
            Method: ANY

Cold Start 최소화

📋 코드 (21줄)
[Edge runtime] (Vercel·Cloudflare Workers)
- 0ms cold start
- 항상 워밍업 상태

[Node.js Lambda]
- 100~500ms cold start
- 최적화 방법:
  1. Provisioned Concurrency
  2. 의존성 최소화
  3. Layer 활용
  4. 워밍업 ping (cron)


[Java/.NET Lambda]
- 1~3초 cold start
- 권장: 다른 런타임 사용 또는 SnapStart


[Python Lambda]
- 200~800ms
- numpy 등 무거운 라이브러리 시 큼

의존성 최소화

JAVASCRIPT📋 코드 (15줄)
// next.config.js (Vercel)
module.exports = {
  experimental: {
    serverComponentsExternalPackages: ['heavy-lib'],  // bundle 분리
  },
};


// AWS Lambda — esbuild
// 50MB → 5MB 번들로 cold start 1/2


// 또는 Layer 활용
// 공유 의존성을 별도 layer로 분리
// 함수마다 같은 layer 재사용

비용 모델

📋 코드 (21줄)
[Vercel] Hobby
- 1M Edge Function invocations 무료
- 100GB bandwidth 무료
- 6,000 build minutes 무료

[Vercel] Pro $20/mo
- 1M invocations
- $0.65 / additional 1M
- 1TB bandwidth


[AWS Lambda]
- 1M invocations 무료 (영구)
- 400,000 GB-second compute 무료
- 그 후: $0.20 / 1M invocations + $0.0000166667 / GB-s


[Cloudflare Workers]
- 100K req/일 무료
- $5/mo: 10M req
- 가장 저렴 — 비교 시 1/5 가격

DB 연결 — 서버리스 함정

TYPESCRIPT📋 코드 (29줄)
// ❌ 매 요청마다 새 연결
export const handler = async () => {
  const prisma = new PrismaClient();
  const users = await prisma.user.findMany();
  await prisma.$disconnect();
  return users;
};


// ✅ 연결 재사용 (Lambda 컨테이너 재사용)
const prisma = new PrismaClient();

export const handler = async () => {
  return prisma.user.findMany();
};


// ⚠️ 동시 실행 100개 = 100개 DB 연결
// → DB connection limit 초과 위험


// ✅ 해결: Connection Pooler
// - PgBouncer
// - Supabase Pooler
// - Vercel Postgres (자동)
// - Prisma Accelerate

DATABASE_URL="postgresql://...?pgbouncer=true&connection_limit=1"
DIRECT_URL="postgresql://..." # for migrations

서버리스 vs 컨테이너 결정

📋 코드 (17줄)
[서버리스 적합]
- 트래픽 변동 큼
- API 가벼움 (< 30s)
- 스타트업·MVP
- 부분 사용 (cron·webhook)

[컨테이너 적합]
- 트래픽 일정·예측 가능
- 긴 작업 (> 5분)
- WebSocket·실시간
- 메모리·CPU 집약


→ 보통 혼합:
- Web/API → 서버리스
- 백그라운드 worker → 컨테이너
- 큰 작업 → 별도 서버

다음 챕터

CH.117 "데이터 파이프라인: ETL + 스트리밍".


AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude

무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6

내 코드의 서버리스 부분을 분석해서
실전 분석 + 개선 우선순위를 알려줘.
ChatGPT

무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro

서버리스 관련 베스트 프랙티스 5가지를
비교 분석해서 패턴 추출를 알려줘.
Gemini

무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro

내 프로젝트 전체에서 서버리스
최적화 가능 위치를 보고해줘.
Grok

무료: Grok 4.1 / SuperGrok $30/mo

2026년 한국 시장의 서버리스
트렌드를 솔직히 알려줘.

⭐ 이것만 기억하세요
서버리스: Vercel Edge + AWS Lambda 이 3가지만 확실히 잡으세요
1.Edge runtime (Vercel·Cloudflare) = 0ms cold start
2.Lambda는 동시 실행 = DB 연결 → Pooler 필수
3.서버리스 적합: 가벼운 API, 컨테이너 적합: WebSocket·긴 작업


공유하기
진행도 116 / 120