Efficiently Developing Serverless Functions: Claude Code 활용 가이드
efficiently developing serverless functions: Claude Code 활용. 실용적인 코드 예시를 포함합니다.
서버리스개발にClaude Code를 사용하는メリット
서버리스함수はコールドスタート対策、메모리최적화、ペイロードサイズ制限など、固有の制約があります。Claude Code는 이것らの制約を理解した上で、최적화されたコードを생성します。
AWS Lambda함수の개발
> AWS Lambda + API Gatewayで이미지リサイズAPI를 생성해줘。
> SAM템플릿も생성して。TypeScriptで구현して。
Lambda함수
// src/handlers/resize-image.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import sharp from 'sharp';
const s3 = new S3Client({});
interface ResizeRequest {
key: string;
width: number;
height?: number;
quality?: number;
}
export async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> {
try {
const body = JSON.parse(event.body || '{}') as ResizeRequest;
if (!body.key || !body.width) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'key and width are required' }),
};
}
// S3から元이미지を취득
const { Body, ContentType } = await s3.send(new GetObjectCommand({
Bucket: process.env.BUCKET_NAME!,
Key: body.key,
}));
const buffer = Buffer.from(await Body!.transformToByteArray());
// リサイズ
const resized = await sharp(buffer)
.resize(body.width, body.height, { fit: 'cover', withoutEnlargement: true })
.webp({ quality: body.quality || 80 })
.toBuffer();
// リサイズ後の이미지を저장
const outputKey = body.key.replace(/\.[^.]+$/, `-${body.width}w.webp`);
await s3.send(new PutObjectCommand({
Bucket: process.env.BUCKET_NAME!,
Key: outputKey,
Body: resized,
ContentType: 'image/webp',
}));
return {
statusCode: 200,
body: JSON.stringify({
key: outputKey,
size: resized.length,
width: body.width,
}),
};
} catch (err) {
console.error('Resize error:', err);
return {
statusCode: 500,
body: JSON.stringify({ error: 'Internal server error' }),
};
}
}
SAM템플릿
# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: nodejs20.x
Timeout: 30
MemorySize: 512
Environment:
Variables:
BUCKET_NAME: !Ref ImageBucket
Resources:
ResizeFunction:
Type: AWS::Serverless::Function
Properties:
Handler: dist/handlers/resize-image.handler
Events:
Api:
Type: Api
Properties:
Path: /resize
Method: post
Policies:
- S3CrudPolicy:
BucketName: !Ref ImageBucket
Metadata:
BuildMethod: esbuild
BuildProperties:
Minify: true
Target: es2022
External:
- sharp
ImageBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub '${AWS::StackName}-images'
Outputs:
ApiUrl:
Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/'
Cloudflare Workersの개발
> Cloudflare Workersで短縮URL생성サービス를 생성해줘。
> KVストアを使ってURLマッピングを관리して。
// src/worker.ts
interface Env {
URL_STORE: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// 短縮URLのリダイレクト
if (request.method === 'GET' && url.pathname.length > 1) {
const slug = url.pathname.slice(1);
const targetUrl = await env.URL_STORE.get(slug);
if (targetUrl) {
return Response.redirect(targetUrl, 302);
}
return new Response('Not found', { status: 404 });
}
// URL短縮の생성
if (request.method === 'POST' && url.pathname === '/api/shorten') {
const { url: targetUrl } = await request.json<{ url: string }>();
if (!targetUrl || !isValidUrl(targetUrl)) {
return Response.json({ error: 'Invalid URL' }, { status: 400 });
}
const slug = generateSlug();
await env.URL_STORE.put(slug, targetUrl, { expirationTtl: 86400 * 365 });
return Response.json({
shortUrl: `${url.origin}/${slug}`,
slug,
originalUrl: targetUrl,
});
}
return new Response('Method not allowed', { status: 405 });
},
};
function generateSlug(): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return Array.from(crypto.getRandomValues(new Uint8Array(7)))
.map(b => chars[b % chars.length])
.join('');
}
function isValidUrl(str: string): boolean {
try {
const url = new URL(str);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
}
Vercel Edge Functionsの개발
// app/api/og/route.tsx
import { ImageResponse } from 'next/og';
export const runtime = 'edge';
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const title = searchParams.get('title') || 'My Blog';
return new ImageResponse(
(
<div
style={{
height: '100%',
width: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#1a1a2e',
color: '#ffffff',
fontFamily: 'sans-serif',
}}
>
<h1 style={{ fontSize: 60, textAlign: 'center', padding: '0 40px' }}>
{title}
</h1>
</div>
),
{ width: 1200, height: 630 }
);
}
コールドスタート対策
// Lambda のコールドスタート対策
// 接続の再利用
let dbConnection: PrismaClient | null = null;
function getDB() {
if (!dbConnection) {
dbConnection = new PrismaClient();
}
return dbConnection;
}
// ウォームアップ用핸들러ー
export async function warmupHandler(event: ScheduledEvent) {
// CloudWatch Eventsで定期実行してコールドスタートを防ぐ
console.log('Warmup invocation');
return { statusCode: 200 };
}
테스트
import { handler } from './resize-image';
import { mockClient } from 'aws-sdk-client-mock';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
const s3Mock = mockClient(S3Client);
describe('resize-image handler', () => {
beforeEach(() => {
s3Mock.reset();
});
it('should return 400 when key is missing', async () => {
const event = { body: JSON.stringify({ width: 200 }) } as any;
const result = await handler(event);
expect(result.statusCode).toBe(400);
});
it('should resize and upload image', async () => {
s3Mock.on(GetObjectCommand).resolves({
Body: createMockStream(testImageBuffer),
ContentType: 'image/jpeg',
});
s3Mock.on(PutObjectCommand).resolves({});
const event = {
body: JSON.stringify({ key: 'test.jpg', width: 200 }),
} as any;
const result = await handler(event);
expect(result.statusCode).toBe(200);
});
});
정리
Claude Code를 활용하면 Lambda・Cloudflare Workers・Vercel Functionsなど각種서버리스プラット폼に최적화された함수を효율적으로개발할 수 있습니다。プラット폼固有の制約を理解した上でコードを생성してくれるため、コールドスタート対策や메모리최적화も적절하게行われます。AWSでの本格的な운영에 대해서는AWS배포の자동화도 참고하세요.개발の기본적인효율화は生産性を3倍にするTipsで紹介しています。
Claude Code의 상세 정보는Anthropic공식 문서를 확인하세요.
#Claude Code
#serverless
#Lambda
#Cloudflare Workers
#Vercel
Related Posts
Use Cases
Use Cases
Claude Code로 리팩토링을 자동화하는 방법
Claude Code를 활용해 코드 리팩토링을 효율적으로 자동화하는 방법을 알아봅니다. 실전 프롬프트와 구체적인 리팩토링 패턴을 소개합니다.
Use Cases
Use Cases
Claude Code로 사이드 프로젝트 개발 속도를 극대화하는 방법 [예제 포함]
Claude Code를 활용해 개인 프로젝트 개발 속도를 획기적으로 높이는 방법을 알아봅니다. 실전 예제와 아이디어부터 배포까지의 워크플로를 포함합니다.
Use Cases
Use Cases
Complete CORS Configuration Guide: Claude Code 활용 가이드
complete cors configuration guide: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.