Serverless computing abstracts infrastructure management for scalable applications.
Function Design#
1// Initialize outside handler (reused across invocations)
2import { DynamoDB } from '@aws-sdk/client-dynamodb';
3const db = new DynamoDB({});
4
5export async function handler(event) {
6 // Process event
7 const result = await processData(event);
8
9 return {
10 statusCode: 200,
11 body: JSON.stringify(result),
12 };
13}Cold Start Optimization#
- Keep functions small
- Initialize SDK clients outside handler
- Use provisioned concurrency for latency-sensitive functions
- Choose appropriate memory settings
Event Patterns#
1// SQS consumer
2export async function handler(event: SQSEvent) {
3 await Promise.all(event.Records.map(async (record) => {
4 const message = JSON.parse(record.body);
5 await processMessage(message);
6 }));
7}
8
9// API Gateway
10export async function handler(event: APIGatewayProxyEvent) {
11 const body = JSON.parse(event.body || '{}');
12 const result = await processRequest(body);
13
14 return {
15 statusCode: 200,
16 headers: { 'Content-Type': 'application/json' },
17 body: JSON.stringify(result),
18 };
19}Step Functions for Workflows#
1{
2 "StartAt": "ProcessOrder",
3 "States": {
4 "ProcessOrder": {
5 "Type": "Task",
6 "Resource": "arn:aws:lambda:...:processOrder",
7 "Next": "SendNotification"
8 },
9 "SendNotification": {
10 "Type": "Task",
11 "Resource": "arn:aws:lambda:...:sendNotification",
12 "End": true
13 }
14 }
15}Design for statelessness, embrace event-driven patterns, and monitor cold starts.