☁️ 클라우드

서버리스

Serverless

서버리스는 서버 인프라 관리 없이 코드만 작성하면 되는 클라우드 컴퓨팅 모델입니다. AWS Lambda, Vercel, Cloudflare Workers 등에서 FaaS(Function as a Service) 형태로 제공되며, 사용한 만큼만 과금됩니다.

📖 상세 설명

서버리스(Serverless)는 "서버가 없다"는 의미가 아니라 "서버를 관리할 필요가 없다"는 의미입니다. 클라우드 제공업체가 서버 프로비저닝, 스케일링, 패치 등을 자동으로 처리하며, 개발자는 비즈니스 로직에만 집중할 수 있습니다.

주요 서버리스 플랫폼

AWS Lambda

서버리스 원조, 가장 많은 트리거 지원

Vercel Functions

Next.js 통합, Edge Runtime

Cloudflare Workers

V8 Isolate, 초저지연 Edge

Supabase Edge

Deno 기반, PostgreSQL 통합

서버리스 vs 전통 서버

💻 코드 예제

AWS Lambda (Node.js)

// handler.js
export const handler = async (event, context) => {
  const { name } = JSON.parse(event.body);

  // 비즈니스 로직
  const greeting = `Hello, ${name}!`;

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

// serverless.yml (Serverless Framework)
service: my-service
provider:
  name: aws
  runtime: nodejs20.x
  region: ap-northeast-2
functions:
  hello:
    handler: handler.handler
    events:
      - http:
          path: /hello
          method: post

Vercel Edge Function

// app/api/hello/route.ts (Next.js App Router)
import { NextRequest } from 'next/server';

export const runtime = 'edge'; // Edge Runtime 사용

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get('name') || 'World';

  return new Response(
    JSON.stringify({ message: `Hello, ${name}!` }),
    {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    }
  );
}

Cloudflare Workers

// src/index.ts
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === '/api/hello') {
      const name = url.searchParams.get('name') || 'World';

      return new Response(
        JSON.stringify({ message: `Hello, ${name}!` }),
        {
          headers: { 'Content-Type': 'application/json' },
        }
      );
    }

    return new Response('Not Found', { status: 404 });
  },
};

Cold Start 최적화

// Lambda Provisioned Concurrency (항상 warm 상태 유지)
// serverless.yml
functions:
  api:
    handler: handler.main
    provisionedConcurrency: 5  # 5개 인스턴스 warm 유지

// 또는 코드 레벨 최적화
// 모듈 초기화를 핸들러 밖에서 (재사용됨)
import { DynamoDB } from '@aws-sdk/client-dynamodb';

const dynamodb = new DynamoDB({});  // Cold Start 시 1회만 실행

export const handler = async (event) => {
  // 핸들러는 매 요청마다 실행
  const result = await dynamodb.getItem({ /* ... */ });
  return { statusCode: 200, body: JSON.stringify(result) };
};

💬 현업 대화 예시

👨‍💼 PM

"이번 프로모션에 트래픽이 10배 늘어날 것 같은데 서버 증설해야 하나요?"

👩‍💻 백엔드 개발자

"서버리스라서 자동 스케일링됩니다. Lambda가 동시 실행 수를 자동으로 늘려서 트래픽 폭증도 문제없어요. 비용은 실제 사용량만큼만 나오고요."

👨‍💻 주니어 개발자

"API 응답이 가끔 느려요. 첫 요청만 2초 정도 걸리고 그 다음부터는 빨라요."

👩‍💻 시니어 개발자

"Cold Start 현상이에요. Lambda가 한동안 안 쓰이면 컨테이너가 내려가는데, 다시 요청 오면 초기화하느라 느려져요. Provisioned Concurrency 설정하거나 Edge 런타임 쓰면 개선돼요."

⚠️ 주의사항

Cold Start: 함수가 일정 시간 호출되지 않으면 컨테이너가 종료되어 다음 호출 시 초기화 지연이 발생합니다. 레이턴시에 민감한 API는 Provisioned Concurrency나 Edge Runtime을 고려하세요.

실행 시간 제한: Lambda는 15분, Vercel Edge는 30초 등 플랫폼별 제한이 있습니다. 장시간 작업은 Step Functions나 큐 기반 처리로 분리하세요.

팁: Cloudflare Workers는 V8 Isolate 기반으로 Cold Start가 거의 없고, 전 세계 Edge에서 실행되어 지연이 매우 낮습니다. 단순 API나 프록시에 적합합니다.

🔗 관련 용어

📚 더 배우기