Use Cases

AWS Lambda 최적화: Claude Code 활용 가이드

Claude Code로 AWS Lambda 함수를 빠르게 작성하는 방법을 API Gateway, DynamoDB 연동부터 CDK IaC, 로컬 테스트까지 한 번에 정리했습니다.

Claude Code로 AWS Lambda 개발 가속화하기

AWS Lambda는 이벤트 기반 서버리스 컴퓨팅 서비스입니다. API Gateway, S3, DynamoDB 같은 AWS 서비스와 긴밀하게 연동돼 확장 가능한 백엔드를 구축할 수 있죠. Claude Code를 활용하면 Lambda 특유의 구현 패턴이나 IaC 작성까지 효율적으로 처리할 수 있습니다.

Lambda 함수의 기본 설계

> TypeScript로 Lambda 함수를 생성해줘.
> API Gateway에서 오는 요청을 처리하는 구조로.
// src/handlers/api.ts
import {
  APIGatewayProxyEvent,
  APIGatewayProxyResult,
  Context,
} from 'aws-lambda';

export const handler = async (
  event: APIGatewayProxyEvent,
  context: Context
): Promise<APIGatewayProxyResult> => {
  const { httpMethod, path, body, queryStringParameters } = event;

  try {
    switch (`${httpMethod} ${path}`) {
      case 'GET /users':
        return await getUsers(queryStringParameters);
      case 'POST /users':
        return await createUser(JSON.parse(body || '{}'));
      case 'GET /users/{id}':
        const id = event.pathParameters?.id;
        return await getUser(id!);
      default:
        return response(404, { error: 'Not Found' });
    }
  } catch (error) {
    console.error('Lambda error:', error);
    return response(500, { error: 'Internal Server Error' });
  }
};

function response(statusCode: number, body: object): APIGatewayProxyResult {
  return {
    statusCode,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    },
    body: JSON.stringify(body),
  };
}

async function getUsers(params: any) {
  // DynamoDB에서 사용자 목록 조회
  return response(200, { users: [] });
}

async function createUser(data: any) {
  return response(201, { id: 'new-user-id', ...data });
}

async function getUser(id: string) {
  return response(200, { id, name: 'User' });
}

DynamoDB 연동

> DynamoDB를 사용한 CRUD 유틸을 만들어줘.
// src/lib/dynamodb.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
  DynamoDBDocumentClient,
  GetCommand,
  PutCommand,
  QueryCommand,
  DeleteCommand,
} from '@aws-sdk/lib-dynamodb';

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

const TABLE_NAME = process.env.TABLE_NAME!;

export async function getItem<T>(pk: string, sk: string): Promise<T | null> {
  const { Item } = await docClient.send(
    new GetCommand({
      TableName: TABLE_NAME,
      Key: { PK: pk, SK: sk },
    })
  );
  return (Item as T) || null;
}

export async function putItem(item: Record<string, any>): Promise<void> {
  await docClient.send(
    new PutCommand({
      TableName: TABLE_NAME,
      Item: {
        ...item,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      },
    })
  );
}

export async function queryItems<T>(
  pk: string,
  skPrefix?: string
): Promise<T[]> {
  const params: any = {
    TableName: TABLE_NAME,
    KeyConditionExpression: skPrefix
      ? 'PK = :pk AND begins_with(SK, :sk)'
      : 'PK = :pk',
    ExpressionAttributeValues: { ':pk': pk },
  };

  if (skPrefix) {
    params.ExpressionAttributeValues[':sk'] = skPrefix;
  }

  const { Items } = await docClient.send(new QueryCommand(params));
  return (Items as T[]) || [];
}

AWS CDK로 인프라 정의

> CDK로 Lambda + API Gateway + DynamoDB
> 스택을 정의해줘.
// lib/api-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';

export class ApiStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // DynamoDB 테이블
    const table = new dynamodb.Table(this, 'MainTable', {
      partitionKey: { name: 'PK', type: dynamodb.AttributeType.STRING },
      sortKey: { name: 'SK', type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
      removalPolicy: cdk.RemovalPolicy.RETAIN,
    });

    // Lambda 함수
    const apiHandler = new NodejsFunction(this, 'ApiHandler', {
      entry: 'src/handlers/api.ts',
      handler: 'handler',
      runtime: lambda.Runtime.NODEJS_20_X,
      architecture: lambda.Architecture.ARM_64,
      memorySize: 256,
      timeout: cdk.Duration.seconds(30),
      environment: {
        TABLE_NAME: table.tableName,
        NODE_OPTIONS: '--enable-source-maps',
      },
      bundling: {
        minify: true,
        sourceMap: true,
      },
    });

    table.grantReadWriteData(apiHandler);

    // API Gateway
    const api = new apigateway.RestApi(this, 'Api', {
      restApiName: 'My API',
      deployOptions: { stageName: 'v1' },
    });

    const users = api.root.addResource('users');
    users.addMethod('GET', new apigateway.LambdaIntegration(apiHandler));
    users.addMethod('POST', new apigateway.LambdaIntegration(apiHandler));
  }
}

로컬 개발과 테스트

# SAM으로 로컬 실행
sam local start-api

# 특정 함수 테스트
sam local invoke ApiHandler -e events/get-users.json

# CDK 배포
cdk deploy --require-approval never

정리

AWS Lambda와 Claude Code를 조합하면 서버리스 아키텍처 설계부터 IaC 작성까지 효율적으로 진행할 수 있습니다. AWS 배포 가이드서버리스 함수 가이드도 함께 참고해 보세요.

AWS Lambda의 자세한 내용은 AWS Lambda 공식 문서에서 확인할 수 있습니다.

#Claude Code #AWS Lambda #serverless #AWS #클라우드

Claude Code 워크플로우를 한 단계 업그레이드하세요

지금 바로 Claude Code에 복사해 쓸 수 있는 검증된 프롬프트 템플릿 50선.

무료 제공

무료 PDF: 5분 완성 Claude Code 치트시트

주요 명령어, 단축키, 프롬프트 예시를 A4 한 장에 정리했습니다.

PDF 다운로드
M

이 글을 작성한 사람

Masa

Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.