168 lines
4.9 KiB
Markdown
168 lines
4.9 KiB
Markdown
---
|
|
id: wiki-2026-0508-serverless-computing
|
|
title: Serverless Computing
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [FaaS, Function-as-a-Service, Lambda]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [serverless, cloud, faas, backend]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: typescript
|
|
framework: aws-lambda/cloudflare-workers
|
|
---
|
|
|
|
# Serverless Computing
|
|
|
|
## 매 한 줄
|
|
> **"매 server 관리 없이 event 단위로 코드를 실행"**. 매 2014 AWS Lambda 출시로 본격화. 매 2026 현재 Cloudflare Workers, Vercel Edge, AWS Lambda + Function URLs 의 edge-native serverless 가 mainstream — cold start 의 sub-10ms.
|
|
|
|
## 매 핵심
|
|
|
|
### 매 모델 비교
|
|
- **Container (ECS, Cloud Run)**: long-lived, scale-to-N. Cold start 100ms-2s.
|
|
- **Lambda (region)**: per-invocation, max 15min. Cold start 100-500ms.
|
|
- **Edge (Workers, Vercel)**: V8 isolate, sub-millisecond cold start, max 30s CPU.
|
|
- **Durable (Durable Objects, Lambda + DynamoDB)**: stateful + serverless.
|
|
|
|
### 매 trade-offs
|
|
- **장점**: pay-per-use, auto-scale, ops-free.
|
|
- **단점**: vendor lock-in, cold start, debugging 어려움, time/memory limit.
|
|
|
|
### 매 응용
|
|
1. API endpoint (Hono on Workers).
|
|
2. Event processing (S3 → Lambda → SNS).
|
|
3. Cron job (EventBridge schedule).
|
|
4. WebSocket (API Gateway + Lambda).
|
|
5. ML inference (Lambda + container image, 10GB).
|
|
|
|
## 💻 패턴
|
|
|
|
### AWS Lambda (TypeScript)
|
|
```ts
|
|
import { APIGatewayProxyHandler } from 'aws-lambda';
|
|
|
|
export const handler: APIGatewayProxyHandler = async (event) => {
|
|
const body = JSON.parse(event.body ?? '{}');
|
|
const result = await processOrder(body);
|
|
return { statusCode: 200, body: JSON.stringify(result) };
|
|
};
|
|
```
|
|
|
|
### Cloudflare Workers (Hono)
|
|
```ts
|
|
import { Hono } from 'hono';
|
|
|
|
const app = new Hono<{ Bindings: { DB: D1Database } }>();
|
|
|
|
app.get('/users/:id', async (c) => {
|
|
const id = c.req.param('id');
|
|
const user = await c.env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(id).first();
|
|
return c.json(user);
|
|
});
|
|
|
|
export default app;
|
|
```
|
|
|
|
### Cold start mitigation (provisioned concurrency)
|
|
```yaml
|
|
# serverless.yml
|
|
functions:
|
|
api:
|
|
handler: handler.api
|
|
provisionedConcurrency: 5 # always-warm
|
|
reservedConcurrency: 100 # max parallel
|
|
```
|
|
|
|
### Idempotent handler
|
|
```ts
|
|
const seen = new Map<string, any>();
|
|
export const handler = async (event: { id: string; data: any }) => {
|
|
if (seen.has(event.id)) return seen.get(event.id);
|
|
const result = await process(event.data);
|
|
seen.set(event.id, result);
|
|
return result;
|
|
};
|
|
// Production: use DynamoDB or Redis for cross-invocation idempotency
|
|
```
|
|
|
|
### Edge function (Vercel)
|
|
```ts
|
|
export const config = { runtime: 'edge' };
|
|
|
|
export default async function handler(req: Request) {
|
|
const url = new URL(req.url);
|
|
const cached = await caches.default.match(req);
|
|
if (cached) return cached;
|
|
const data = await fetch(`${process.env.UPSTREAM}${url.pathname}`);
|
|
const resp = new Response(data.body, { headers: { 'cache-control': 'max-age=300' } });
|
|
await caches.default.put(req, resp.clone());
|
|
return resp;
|
|
}
|
|
```
|
|
|
|
### Durable Object (stateful)
|
|
```ts
|
|
export class Counter {
|
|
constructor(private state: DurableObjectState) {}
|
|
async fetch(req: Request) {
|
|
let count = (await this.state.storage.get<number>('n')) ?? 0;
|
|
count++;
|
|
await this.state.storage.put('n', count);
|
|
return new Response(String(count));
|
|
}
|
|
}
|
|
```
|
|
|
|
### Event-driven (S3 → Lambda)
|
|
```python
|
|
def handler(event, context):
|
|
for record in event['Records']:
|
|
bucket = record['s3']['bucket']['name']
|
|
key = record['s3']['object']['key']
|
|
process_image(bucket, key)
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Approach |
|
|
|---|---|
|
|
| Low traffic API | Lambda or Workers |
|
|
| Global low-latency | Cloudflare Workers / Vercel Edge |
|
|
| Long-running (>15min) | Container (Cloud Run, Fargate) |
|
|
| Stateful realtime | Durable Objects |
|
|
| Heavy ML inference | Lambda container image or SageMaker |
|
|
|
|
**기본값**: Cloudflare Workers + Hono + D1 — 2026 의 best-DX serverless.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[Cloud Computing]] · [[Backend]]
|
|
- 변형: [[FaaS]] · [[Edge Functions]] · [[Durable Objects]]
|
|
- 응용: [[API Gateway]] · [[Event-Driven Architecture]]
|
|
- Adjacent: [[Containers]] · [[Microservices]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: handler boilerplate, IAM policy 생성, cold start 분석.
|
|
**언제 X**: cost optimization (cloud bill 의 actual 측정 필요).
|
|
|
|
## ❌ 안티패턴
|
|
- **Lambda monolith**: 1 function 의 multi-route → cold start blast radius.
|
|
- **Sync chain**: Lambda A calls Lambda B sync — double charge + timeout risk.
|
|
- **No timeout**: default 3s 의 leak.
|
|
- **Heavy init**: connection pool init at handler 매 invoke → 매번 cold.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified (AWS docs, Cloudflare docs, Vercel docs 2026).
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — Serverless 2026 state |
|