关于 aws-serverless-eda
面向构建 Lambda 系统的开发者,提供 AWS 无服务器应用和事件驱动架构设计参考。内容结合 Well-Architected 原则,涵盖可靠性、编排与运维模式。
主要功能
- 01无服务器与事件驱动设计指导
- 02Lambda 并发与状态原则
- 03Step Functions 编排模式
- 04事件路由与队列模式
- 05可靠性、可观测性与安全指导
适用场景
- 01设计异步 Lambda 工作负载
- 02选择分布式事务模式
- 03规划弹性事件处理
- 04审查无服务器部署与监控
MCP 相关
使用 CDK MCP 服务提供构造建议,并通过 AWS Documentation MCP 核实 AWS 细节。文档还列出可单独使用的 AWS MCP 服务,支持无服务器生命周期、Lambda、Step Functions 和消息处理。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ zxkane/ aws-skills --skill aws-serverless-eda安装后在 Claude Code 中输入/aws-serverless-eda确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/deployment-best-practices.mdeda-patterns.mdobservability-best-practices.mdperformance-optimization.mdsecurity-best-practices.mdserverless-patterns.md详细介绍
AWS 无服务器与事件驱动架构
本技能基于 Well-Architected Framework 原则,为在 AWS 上构建无服务器应用程序和事件驱动架构提供全面指导。
AWS 文档要求
回答前,务必使用 MCP 工具(mcp__aws-mcp__* 或 mcp__*awsdocs*__*)核实 AWS 相关事实。aws-mcp-setup 依赖项会自动加载;如果 MCP 工具不可用,请引导用户完成该技能的设置流程。
无服务器 MCP 服务
本技能借助 CDK MCP 服务(由 aws-cdk-development 依赖项提供)和 AWS Documentation MCP,为无服务器开发提供指导。
注意:以下 AWS MCP 服务可通过 Full AWS MCP Server 单独获取(请参阅
aws-mcp-setup技能),不会随此插件一同提供:
- AWS Serverless MCP — SAM CLI 生命周期(init、deploy、local test)
- AWS Lambda Tool MCP — 直接调用 Lambda
- AWS Step Functions MCP — 工作流编排
- Amazon SNS/SQS MCP — 消息传递和队列管理
何时使用本技能
在以下情况下使用本技能:
- 使用 Lambda 构建无服务器应用程序
- 设计事件驱动架构
- 实现微服务模式
- 创建异步处理工作流
- 编排多服务事务
- 构建实时数据处理管道
- 为分布式事务实现 Saga 模式
- 设计可扩展且有弹性的系统
AWS Well-Architected 无服务器设计原则
1. 快速、简单、单一
函数应简洁且用途单一
// ✅ GOOD - Single purpose, focused function
export const processOrder = async (event: OrderEvent) => {
// Only handles order processing
const order = await validateOrder(event);
await saveOrder(order);
await publishOrderCreatedEvent(order);
return { statusCode: 200, body: JSON.stringify({ orderId: order.id }) };
};
// ❌ BAD - Function does too much
export const handleEverything = async (event: any) => {
// Handles orders, inventory, payments, shipping...
// Too many responsibilities
};
确保函数在环境方面高效且注重成本:
- 尽量缩短冷启动时间
- 优化内存分配
- 仅在需要时使用预置并发
- 利用连接复用
2. 考虑并发请求,而非请求总量
围绕并发而非请求量进行设计
Lambda 采用水平扩展,因此设计时应重点考虑:
- 并发执行限制
- 下游服务限流
- 共享资源争用
- 连接池大小
// Consider concurrent Lambda executions accessing DynamoDB
const table = new dynamodb.Table(this, 'Table', {
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, // Auto-scales with load
});
// Or with provisioned capacity + auto-scaling
const table = new dynamodb.Table(this, 'Table', {
billingMode: dynamodb.BillingMode.PROVISIONED,
readCapacity: 5,
writeCapacity: 5,
});
// Enable auto-scaling for concurrent load
table.autoScaleReadCapacity({ minCapacity: 5, maxCapacity: 100 });
table.autoScaleWriteCapacity({ minCapacity: 5, maxCapacity: 100 });
3. 不共享
函数运行时环境的生命周期很短
// ❌ BAD - Relying on local file system
export const handler = async (event: any) => {
fs.writeFileSync('/tmp/data.json', JSON.stringify(data)); // Lost after execution
};
// ✅ GOOD - Use persistent storage
export const handler = async (event: any) => {
await s3.putObject({
Bucket: process.env.BUCKET_NAME,
Key: 'data.json',
Body: JSON.stringify(data),
});
};
状态管理:
- 使用 DynamoDB 保存持久状态
- 使用 Step Functions 保存工作流状态
- 使用 ElastiCache 保存会话状态
- 使用 S3 存储文件
4. 假设硬件不固定
应用程序必须与硬件无关
基础设施可能在不预先通知的情况下发生变化:
- Lambda 函数可能运行在不同的硬件上
- 容器实例可能被替换
- 不要假设底层基础设施固定不变
设计时考虑可移植性:
- 使用环境变量进行配置
- 避免针对特定硬件进行优化
- 在不同环境中进行测试
5. 使用状态机编排,而非函数链式调用
使用 Step Functions 进行编排
// ❌ BAD - Lambda function chaining
export const handler1 = async (event: any) => {
const result = await processStep1(event);
await lambda.invoke({
FunctionName: 'handler2',
Payload: JSON.stringify(result),
});
};
// ✅ GOOD - Step Functions orchestration
const stateMachine = new stepfunctions.StateMachine(this, 'OrderWorkflow', {
definition: stepfunctions.Chain
.start(validateOrder)
.next(processPayment)
.next(shipOrder)
.next(sendConfirmation),
});
Step Functions 的优势:
- 以可视化方式呈现工作流
- 内置错误处理和重试机制
- 执行历史记录和调试功能
- 支持并行和顺序执行
- 无需编写代码即可集成服务
6. 使用事件触发事务
优先采用事件驱动,而非同步请求/响应
// Pattern: Event-driven processing
const bucket = new s3.Bucket(this, 'DataBucket');
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.LambdaDestination(processFunction),
{ prefix: 'uploads/' }
);
// Pattern: EventBridge integration
const rule = new events.Rule(this, 'OrderRule', {
eventPattern: {
source: ['orders'],
detailType: ['OrderPlaced'],
},
});
rule.addTarget(new targets.LambdaFunction(processOrderFunction));
优势:
- 服务之间松耦合
- 异步处理
- 容错能力更强
- 可独立扩展
7. 为故障和重复操作做好设计
操作必须具备幂等性
// ✅ GOOD - Idempotent operation
export const handler = async (event: SQSEvent) => {
for (const record of event.Records) {
const orderId = JSON.parse(record.body).orderId;
// Check if already processed (idempotency)
const existing = await dynamodb.getItem({
TableName: process.env.TABLE_NAME,
Key: { orderId },
});
if (existing.Item) {
console.log('Order already processed:', orderId);
continue; // Skip duplicate
}
// Process order
await processOrder(orderId);
// Mark as processed
await dynamodb.putItem({
TableName: process.env.TABLE_NAME,
Item: { orderId, processedAt: Date.now() },
});
}
};
使用指数退避实现重试逻辑:
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
throw new Error('Max retries exceeded');
}
架构模式
如需查看包含完整代码示例的详细实现模式,请参阅参考文档:
事件驱动架构模式
文件:references/eda-patterns.md
- 使用 EventBridge 的事件路由器(自定义事件总线、架构注册表、基于规则的路由)
- 使用 SQS 的队列处理(标准/FIFO、DLQ、Lambda 消费者)
- 使用 SNS + SQS 的发布/订阅扇出(多消费者、筛选)
- 使用 Step Functions 的 Saga 模式(分布式事务、补偿操作)
- 使用 DynamoDB Streams 的事件溯源(仅追加事件存储、投影)
无服务器架构模式
文件:references/serverless-patterns.md
- API 驱动的微服务(REST API + Lambda 后端)
- 使用 Kinesis 的流处理(实时、批处理窗口、出错时拆分)
- 使用 SQS 的异步任务处理(后台作业、并发控制)
- 使用 EventBridge 的定时作业(cron/rate 计划)
- Webhook 处理(签名验证、异步队列转发)
重要:使用参考资料中的 CDK 代码示例时,避免将资源名称硬编码(例如
restApiName、eventBusName)。让 CDK 自动生成唯一名称,以支持复用和并行部署。详情请参阅aws-cdk-development技能。
最佳实践
错误处理
实现全面的错误处理:
export const handler = async (event: SQSEvent) => {
const failures: SQSBatchItemFailure[] = [];
for (const record of event.Records) {
try {
await processRecord(record);
} catch (error) {
console.error('Failed to process record:', record.messageId, error);
failures.push({ itemIdentifier: record.messageId });
}
}
// Return partial batch failures for retry
return { batchItemFailures: failures };
};
死信队列
始终配置 DLQ 以处理错误:
const dlq = new sqs.Queue(this, 'DLQ', {
retentionPeriod: Duration.days(14),
});
const queue = new sqs.Queue(this, 'Queue', {
deadLetterQueue: {
queue: dlq,
maxReceiveCount: 3,
},
});
// Monitor DLQ depth
new cloudwatch.Alarm(this, 'DLQAlarm', {
metric: dlq.metricApproximateNumberOfMessagesVisible(),
threshold: 1,
evaluationPeriods: 1,
alarmDescription: 'Messages in DLQ require attention',
});
可观测性
启用跟踪和监控:
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
tracing: lambda.Tracing.ACTIVE, // X-Ray tracing
environment: {
POWERTOOLS_SERVICE_NAME: 'order-service',
POWERTOOLS_METRICS_NAMESPACE: 'MyApp',
LOG_LEVEL: 'INFO',
},
});
有效使用 MCP 服务
构建无服务器基础设施时,使用 CDK MCP 服务(通过 aws-cdk-development 依赖项)获取构造建议和 CDK 专属指导。
实施前,使用 AWS Documentation MCP 验证服务功能、区域可用性和 API 规范。
其他资源
此技能包含基于 AWS 最佳实践编写的全面参考文档:
-
无服务器模式:
references/serverless-patterns.md- 核心无服务器架构和 API 模式
- 数据处理和集成模式
- 使用 Step Functions 编排
- 应避免的反模式
-
事件驱动架构模式:
references/eda-patterns.md- 事件路由和处理模式
- 事件溯源和 Saga 模式
- 幂等性和错误处理
- 消息排序和去重
-
安全最佳实践:
references/security-best-practices.md- 共同责任模型
- IAM 最小权限模式
- 数据保护和加密
- 使用 VPC 实现网络安全
-
可观测性最佳实践:
references/observability-best-practices.md- 三大支柱:指标、日志、跟踪
- 使用 Lambda Powertools 进行结构化日志记录
- X-Ray 分布式跟踪
- CloudWatch 警报和控制面板
-
性能优化:
references/performance-optimization.md- 冷启动优化技术
- 内存和 CPU 优化
- 减小软件包大小
- 预置并发模式
-
部署最佳实践:
references/deployment-best-practices.md- CI/CD 流水线设计
- 测试策略(单元、集成、负载)
- 部署策略(金丝雀、蓝/绿)
- 回滚和安全机制
外部资源:
- AWS Well-Architected Serverless Lens:https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/
- ServerlessLand.com:预构建的无服务器模式
- AWS Serverless Workshops:https://serverlessland.com/learn?type=Workshops
如需了解详细的实施模式、反模式和代码示例,请参阅技能目录中的全面参考资料。