| name | serverless-patterns |
| description | Build and optimize serverless functions — AWS Lambda cold starts, Cloudflare Workers edge patterns, function composition, idempotency, dead-letter queues, concurrency limits, observability, and IaC deployment with SAM/SST. Use when asked about "Lambda", "serverless function", "cold start", "Cloudflare Workers", "edge function", "AWS SAM", "SST framework", "function timeout", "Lambda concurrency", "DLQ", "dead-letter queue", "idempotent Lambda", "serverless observability", or "deploy serverless". Do NOT use for: long-running container workloads — see kubernetes-patterns or docker-patterns.
|
| origin | yamtam-original |
| license | MIT © 2026 Vũ Văn Tâm |
| version | 1.0.0 |
| compatibility | AWS Lambda (Node.js 20/Python 3.12), Cloudflare Workers, SST v3, SAM CLI. |
When to Use
- Use when: building event-driven functions (S3 trigger, SQS consumer, API Gateway)
- Use when: cold start latency is causing p99 spikes
- Use when: functions need idempotency guarantees
- Use when: deploying to edge (< 5ms latency, no Node.js runtime)
- Do NOT use for: long-running batch jobs (> 15 min) — use ECS/k8s
- Do NOT use for: persistent WebSocket servers — see websocket-patterns
Lambda Handler Pattern
import { SQSEvent, SQSRecord, Context } from 'aws-lambda';
import { DynamoDBClient, PutItemCommand, ConditionalCheckFailedException } from '@aws-sdk/client-dynamodb';
const dynamo = new DynamoDBClient({});
export async function handler(event: SQSEvent, context: Context) {
const results = await Promise.allSettled(
event.Records.map(record => processRecord(record))
);
const failures = results
.map((r, i) => r.status === 'rejected' ? { itemIdentifier: event.Records[i].messageId } : null)
.filter(Boolean);
return { batchItemFailures: failures };
}
() {
body = .(record.);
idempotencyKey = record.;
{
dynamo.( ({
: ,
: { : { : idempotencyKey }, : { : (.(.() / ) + ) } },
: ,
}));
} (e) {
(e ) ;
e;
}
(body);
}
Cold Start Mitigation
export async function handler(event) {
const { S3Client } = await import('@aws-sdk/client-s3');
const { parse } = await import('csv-parse/sync');
}
import { S3Client } from '@aws-sdk/client-s3';
import { parse } from 'csv-parse/sync';
const s3 = new S3Client({});
export async function handler(event) { ... }
Properties:
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 5
Cloudflare Workers (Edge)
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === '/api/hello') {
return Response.json({ message: 'Hello from the edge' });
}
const cached = await env.CACHE.get(url.pathname);
if (cached) return new Response(cached, { headers: { 'X-Cache': 'HIT' } });
const data = await fetch('https://api.origin.com' + url.pathname);
const text = await data.text();
await env.CACHE.put(url.pathname, text, { expirationTtl: 300 });
return (text);
},
} <>;
Dead-Letter Queue
Resources:
OrderProcessor:
Type: AWS::Serverless::Function
Properties:
Handler: src/handler.handler
Runtime: nodejs20.x
Timeout: 30
MemorySize: 512
EventInvokeConfig:
MaximumRetryAttempts: 2
DestinationConfig:
OnFailure:
Type: SQS
Destination: !GetAtt DLQ.Arn
DLQ:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600
Concurrency + Throttling
Properties:
ReservedConcurrentExecutions: 50
const pool = new Pool({
max: 2,
idleTimeoutMillis: 1000,
connectionTimeoutMillis: 3000,
});
Observability
export async function handler(event: any, context: Context) {
const logger = {
info: (msg: string, meta = {}) =>
console.log(JSON.stringify({
level: 'INFO', message: msg,
requestId: context.awsRequestId,
functionName: context.functionName,
...meta,
})),
};
logger.info('Processing started', { eventType: event.type });
}
Anti-Fake-Pass Rules
Before claiming serverless function is production-ready, you MUST show:
Reference: gates/anti-fake-pass-gate.md