aws-serverless-eda について
Lambda ベースのシステムを構築する開発者向けに、AWS のサーバーレスアプリケーションとイベント駆動アーキテクチャの設計指針を提供します。Well-Architected の原則に基づき、信頼性、オーケストレーション、運用のパターンを扱います。
主な機能
- 01サーバーレスとイベント駆動設計の指針
- 02Lambda の同時実行と状態管理の原則
- 03Step Functions によるオーケストレーション
- 04イベントルーティングとキューのパターン
- 05信頼性、可観測性、セキュリティの指針
活用シーン
- 01非同期 Lambda ワークロードの設計
- 02分散トランザクションのパターン選定
- 03堅牢なイベント処理の計画
- 04サーバーレスのデプロイと監視の確認
MCP 対応
構成要素の提案には CDK MCP サーバーを使用し、AWS の詳細確認には AWS Documentation MCP を利用します。サーバーレスのライフサイクル、Lambda、Step Functions、メッセージング向けの別途提供される AWS MCP サーバーも記載しています。
インストール
コマンドをコピーしてターミナルで実行します。
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 のライフサイクル(初期化、デプロイ、ローカルテスト)
- 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 を使った Pub/Sub ファンアウト(複数コンシューマー、フィルタリング)
- 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- 3 つの柱:メトリクス、ログ、トレース
- 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
詳細な実装パターン、アンチパターン、コード例については、スキルディレクトリ内の包括的なリファレンスを参照してください。