⚙️aws-lambda-durable-functions
- プラグイン
- aws-serverless
- ソース
- GitHub で見る ↗
説明
AWS Lambda の耐久性のある関数(durable functions)を使用して、自動的な状態の永続化、リトライロジック、および長時間実行に対応したオーケストレーションを備えた、耐障害性の高い・長時間稼働・複数ステップのアプリケーションを構築します。 以下の主要トピックをカバーします: - クリティカルなリプレイモデル - ステップ操作 - ウェイト/コールバックパターン - Saga パターンによるエラーハンドリング - `LocalDurableTestRunner` を使ったテスト 次のような場合に使用: lambda durable functions、ワークフローオーケストレーション、ステートマシン、リトライ/チェックポイントパターン、長時間稼働するステートフルな Lambda 関数、Saga パターン、ヒューマン・イン・ザ・ループコールバック、信頼性の高いサーバーレスアプリケーション
原文を表示
Build resilient, long-running, multi-step applications with AWS Lambda durable functions with automatic state persistence, retry logic, and orchestration for long-running executions. Covers the critical replay model, step operations, wait/callback patterns, error handling with saga pattern, testing with LocalDurableTestRunner. Triggers on phrases like: lambda durable functions, workflow orchestration, state machines, retry/checkpoint patterns, long-running stateful Lambda functions, saga pattern, human-in-the-loop callbacks, and reliable serverless applications.
ユースケース
- ✓ワークフローオーケストレーション
- ✓長時間稼働するLambda関数を構築
- ✓リトライ・チェックポイント対応が必要なとき
- ✓Sagaパターンでエラーハンドリングするとき
- ✓ステートマシン実装するとき
本文(日本語訳)
AWS Lambda 耐久性関数(Durable Functions)
中断が発生しても確実に進行状態を維持しながら、最大1年間実行可能な、 耐障害性の高いマルチステップアプリケーションおよびAIワークフローを構築します。
オンボーディング
ステップ 1: 前提条件の確認
AWS Lambda 耐久性関数を使用する前に、以下を確認してください:
-
AWS CLI がインストール済み(2.33.22 以上)かつ設定済みであること:
aws --version aws sts get-caller-identity -
ランタイム環境 が整っていること:
- TypeScript/JavaScript の場合: Node.js 22以上(
node --version) - Python の場合: Python 3.11以上(
python --version)注意: 現時点では、Durable Execution SDK がプリインストールされているのは Lambda ランタイム環境 3.13以上のみです。 Durable SDK 自体がサポートする最低 Python バージョンは 3.11 ですが、 OCI を使用して独自の Python ランタイムと Durable SDK を含むコンテナイメージを持ち込むことも可能です。
- TypeScript/JavaScript の場合: Node.js 22以上(
-
デプロイ手段 が存在すること(いずれか一つ):
- AWS SAM CLI(
sam --version)1.153.1 以上 - AWS CDK(
cdk --version)v2.237.1 以上 - Lambda への直接デプロイ権限
- AWS SAM CLI(
ステップ 2: 言語および IaC フレームワークの選択
言語の選択
デフォルト: TypeScript
上書き構文:
"use Python"→ Python コードを生成"use JavaScript"→ JavaScript コードを生成
指定がない場合は、常に TypeScript を使用してください。
IaC フレームワークの選択
デフォルト: CDK
上書き構文:
"use CloudFormation"→ YAML テンプレートを生成"use SAM"→ YAML テンプレートを生成
指定がない場合は、常に CDK を使用してください。
エラーシナリオ
サポートされていない言語
- 検出した言語を表示する
- 次のように通知する: 「Durable Execution SDK は [フレームワーク] にはまだ対応していません」
- サポートされている言語を代替として提案する
サポートされていない IaC フレームワーク
- 検出したフレームワークを表示する
- 次のように通知する: 「[フレームワーク] は Lambda 耐久性関数に未対応の可能性があります」
- サポートされているフレームワークを代替として提案する
Serverless MCP Server が利用不可の場合
- ユーザーに通知する: 「AWS Serverless MCP が応答していません」
- 確認を求める: 「MCP サポートなしで続行しますか?」
- ユーザーの確認なしに処理を続行しないこと
ステップ 3: SDK のインストール
TypeScript/JavaScript の場合:
npm install @aws/durable-execution-sdk-js
npm install --save-dev @aws/durable-execution-sdk-js-testing
Python の場合:
pip install aws-durable-execution-sdk-python
pip install aws-durable-execution-sdk-python-testing
リファレンスファイルの読み込みタイミング
ユーザーが取り組んでいる内容に応じて、適切なリファレンスファイルを参照してください:
-
入門・基本セットアップ・サンプル・ESLint・Jest セットアップ → getting-started.md を参照
-
リプレイモデルの理解・決定論・非決定論的エラー → replay-model-rules.md を参照
-
ステップの作成・アトミック操作・リトライロジック → step-operations.md を参照
-
待機・遅延・コールバック・外部システム・ポーリング → wait-operations.md を参照
-
並列実行・マップ操作・バッチ処理・並行性 → concurrent-operations.md を参照
-
エラーハンドリング・リトライ戦略・Saga パターン・補償トランザクション → error-handling.md を参照
-
高度なエラーハンドリング・タイムアウト処理・サーキットブレーカー・条件付きリトライ → advanced-error-handling.md を参照
-
テスト・ローカルテスト・クラウドテスト・テストランナー・フレイキーテスト → testing-patterns.md を参照
-
デプロイ・CloudFormation・CDK・SAM・ロググループ・インフラストラクチャ → deployment-iac.md を参照
-
高度なパターン・GenAI エージェント・完了ポリシー・ステップセマンティクス・カスタムシリアライゼーション → advanced-patterns.md を参照
-
トラブルシューティング・実行停止・実行失敗・実行 ID のデバッグ・実行履歴・実行エラー・実行失敗の原因・実行タイムアウト・コールバック未受信・実行診断・根本原因分析 → troubleshooting-executions.md を参照
クイックリファレンス
基本ハンドラーパターン
TypeScript:
import { withDurableExecution, DurableContext } from '@aws/durable-execution-sdk-js';
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const result = await context.step('process', async () => processData(event));
return result;
});
Python:
from aws_durable_execution_sdk_python import durable_execution, DurableContext
@durable_execution
def handler(event: dict, context: DurableContext) -> dict:
result = context.step(lambda _: process_data(event), name='process')
return result
重要なルール
- 非決定論的なコードはすべてステップ内に記述すること
(
Date.now、Math.random、API 呼び出し、など) - 耐久性操作のネストは不可 — 操作をまとめる場合は
runInChildContextを使用すること - リプレイ時にクロージャへの変更は失われる — ステップからは値を返すようにすること
- ステップ外のサイドエフェクトはリプレイ時に繰り返される — ロギングには
context.logger(リプレイ対応)を使用すること
Python API の相違点
Python SDK は TypeScript と以下の主要な点で異なります:
- ステップ:
@durable_stepデコレーターとcontext.step(my_step(args))を組み合わせて使用するか、 インラインでcontext.step(lambda _: ..., name='...')を使用します。 ステップ名の自動付与のため、デコレーターの使用を推奨します。 - 待機:
context.wait(duration=Duration.from_seconds(n), name='...') - 例外:
ExecutionError(永続的エラー)、InvocationError(一時的エラー)、CallbackError(コールバック失敗) - テスト:
DurableFunctionTestRunnerクラスを直接使用します。 ハンドラーでインスタンス化し、コンテキストマネージャーを使用してrun(input=...)を呼び出します。
呼び出し要件
耐久性関数の呼び出しには 修飾 ARN(バージョン、エイリアス、または $LATEST)が必要です:
# 有効
aws lambda invoke --function-name my-function:1 output.json
aws lambda invoke --function-name my-function:prod output.json
# 無効 — 失敗します
aws lambda invoke --function-name my-function output.json
IAM 権限
Lambda 実行ロールには、マネージドポリシー AWSLambdaBasicDurableExecutionRolePolicy が
アタッチされている必要があります。このポリシーには以下が含まれます:
lambda:CheckpointDurableExecution— 実行状態の永続化lambda:GetDurableExecutionState— 実行状態の取得- CloudWatch Logs 権限
以下の操作には追加権限が必要です:
- 耐久性のある呼び出し(Durable Invokes): 対象関数の ARN に対する
lambda:InvokeFunction - 外部コールバック: 外部システムには
lambda:SendDurableExecutionCallbackSuccessおよびlambda:SendDurableExecutionCallbackFailureが必要
バリデーションガイドライン
耐久性関数のコードを記述・レビューする際は、以下のリプレイモデル違反を必ず確認してください:
-
ステップ外の非決定論的コード:
Date.now()、Math.random()、UUID 生成、API 呼び出し、データベースクエリは すべてステップ内に記述すること -
ステップ関数内での耐久性操作のネスト: ステップ関数の内部で
context.step()、context.wait()、context.invoke()を 呼び出すことは不可 — 代わりにcontext.runInChildContext()を使用すること -
リプレイをまたいで保持されないクロージャへの変更: ステップ内部でミュートされた変数はリプレイをまたいで保持されません — ステップからは値を返すようにすること
-
リプレイ時に繰り返されるステップ外のサイドエフェクト: ロギングには
context.loggerを使用すること (リプレイ対応で自動的に重複を排除します)
耐久性関数のテストを実装・修正する際は、以下を必ず確認してください:
- すべての操作にわかりやすい名前が付いていること
- 操作をインデックスではなく名前で取得していること
- 複数回の呼び出しによりリプレイ動作がテストされていること
- ローカルテストには
LocalDurableTestRunnerを使用すること
MCP Server の設定
書き込みアクセスはデフォルトで有効です。
このプラグインは .mcp.json に --allow-write が設定された状態で提供されるため、
MCP Server はユーザーに代わってプロジェクトの作成、IaC の生成、デプロイを行うことができます。
Lambda および API Gateway のログなどの機密データへのアクセスはデフォルトでは無効です。
有効にするには、.mcp.json に --allow-sensitive-data-access を追加してください。
リソース
原文(English)を表示
AWS Lambda durable functions
Build resilient multi-step applications and AI workflows that can execute for up to 1 year while maintaining reliable progress despite interruptions.
Onboarding
Step 1: Validate Prerequisites
Before using AWS Lambda durable functions, verify:
-
AWS CLI is installed (2.33.22 or higher) and configured:
aws --version aws sts get-caller-identity -
Runtime environment is ready:
- For TypeScript/JavaScript: Node.js 22+ (
node --version) - For Python: Python 3.11+ (
python --version. Note that currently only Lambda runtime environments 3.13+ come with the Durable Execution SDK pre-installed. 3.11 is the min supported Python version by the Durable SDK itself, however, you could use OCI to bring your own container image with your own Python runtime + Durable SDK.)
- For TypeScript/JavaScript: Node.js 22+ (
-
Deployment capability exists (one of):
- AWS SAM CLI (
sam --version) 1.153.1 or higher - AWS CDK (
cdk --version) v2.237.1 or higher - Direct Lambda deployment access
- AWS SAM CLI (
Step 2: Select language and IaC framework
Language Selection
Default: TypeScript
Override syntax:
- "use Python" → Generate Python code
- "use JavaScript" → Generate JavaScript code
When not specified, ALWAYS use TypeScript
IaC framework selection
Default: CDK
Override syntax:
- "use CloudFormation" → Generate YAML templates
- "use SAM" → Generate YAML templates
When not specified, ALWAYS use CDK
Error Scenarios
Unsupported Language
- List detected language
- State: "Durable Execution SDK is not yet available for [framework]"
- Suggest supported languages as alternatives
Unsupported IaC Framework
- List detected framework
- State: "[framework] might not support Lambda durable functions yet"
- Suggest supported frameworks as alternatives
Serverless MCP Server Unavailable
- Inform user: "AWS Serverless MCP not responding"
- Ask: "Proceed without MCP support?"
- DO NOT continue without user confirmation
Step 3: Install SDK
For TypeScript/JavaScript:
npm install @aws/durable-execution-sdk-js
npm install --save-dev @aws/durable-execution-sdk-js-testing
For Python:
pip install aws-durable-execution-sdk-python
pip install aws-durable-execution-sdk-python-testing
When to Load Reference Files
Load the appropriate reference file based on what the user is working on:
- Getting started, basic setup, example, ESLint, or Jest setup -> see getting-started.md
- Understanding replay model, determinism, or non-deterministic errors -> see replay-model-rules.md
- Creating steps, atomic operations, or retry logic -> see step-operations.md
- Waiting, delays, callbacks, external systems, or polling -> see wait-operations.md
- Parallel execution, map operations, batch processing, or concurrency -> see concurrent-operations.md
- Error handling, retry strategies, saga pattern, or compensating transactions -> see error-handling.md
- Advanced error handling, timeout handling, circuit breakers, or conditional retries -> see advanced-error-handling.md
- Testing, local testing, cloud testing, test runner, or flaky tests -> see testing-patterns.md
- Deployment, CloudFormation, CDK, SAM, log groups, deploy, or infrastructure -> see deployment-iac.md
- Advanced patterns, GenAI agents, completion policies, step semantics, or custom serialization -> see advanced-patterns.md
- troubleshooting, stuck execution, failed execution, debug execution ID, execution history, execution error, why did my execution fail, execution timed out, callback not received, diagnose execution, or root cause execution -> see troubleshooting-executions.md
Quick Reference
Basic Handler Pattern
TypeScript:
import { withDurableExecution, DurableContext } from '@aws/durable-execution-sdk-js';
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const result = await context.step('process', async () => processData(event));
return result;
});
Python:
from aws_durable_execution_sdk_python import durable_execution, DurableContext
@durable_execution
def handler(event: dict, context: DurableContext) -> dict:
result = context.step(lambda _: process_data(event), name='process')
return result
Critical Rules
- All non-deterministic code MUST be in steps (Date.now, Math.random, API calls)
- Cannot nest durable operations - use
runInChildContextto group operations - Closure mutations are lost on replay - return values from steps
- Side effects outside steps repeat - use
context.logger(replay-aware)
Python API Differences
The Python SDK differs from TypeScript in several key areas:
- Steps: Use
@durable_stepdecorator +context.step(my_step(args)), or inlinecontext.step(lambda _: ..., name='...'). Prefer the decorator for automatic step naming. - Wait:
context.wait(duration=Duration.from_seconds(n), name='...') - Exceptions:
ExecutionError(permanent),InvocationError(transient),CallbackError(callback failures) - Testing: Use
DurableFunctionTestRunnerclass directly - instantiate with handler, use context manager, callrun(input=...)
Invocation Requirements
Durable functions require qualified ARNs (version, alias, or $LATEST):
# Valid
aws lambda invoke --function-name my-function:1 output.json
aws lambda invoke --function-name my-function:prod output.json
# Invalid - will fail
aws lambda invoke --function-name my-function output.json
IAM Permissions
Your Lambda execution role MUST have the AWSLambdaBasicDurableExecutionRolePolicy managed policy attached. This includes:
lambda:CheckpointDurableExecution- Persist execution statelambda:GetDurableExecutionState- Retrieve execution state- CloudWatch Logs permissions
Additional permissions needed for:
- Durable invokes:
lambda:InvokeFunctionon target function ARNs - External callbacks: Systems need
lambda:SendDurableExecutionCallbackSuccessandlambda:SendDurableExecutionCallbackFailure
Validation Guidelines
When writing or reviewing durable function code, ALWAYS check for these replay model violations:
- Non-deterministic code outside steps:
Date.now(),Math.random(), UUID generation, API calls, database queries must all be inside steps - Nested durable operations in step functions: Cannot call
context.step(),context.wait(), orcontext.invoke()inside a step function — usecontext.runInChildContext()instead - Closure mutations that won't persist: Variables mutated inside steps are NOT preserved across replays — return values from steps instead
- Side effects outside steps that repeat on replay: Use
context.loggerfor logging (it is replay-aware and deduplicates automatically)
When implementing or modifying tests for durable functions, ALWAYS verify:
- All operations have descriptive names
- Tests get operations by NAME, never by index
- Replay behavior is tested with multiple invocations
- Use
LocalDurableTestRunnerfor local testing
MCP Server Configuration
Write access is enabled by default. The plugin ships with --allow-write in .mcp.json, so the MCP server can create projects, generate IaC, and deploy on behalf of the user.
Access to sensitive data (like Lambda and API Gateway logs) is not enabled by default. To grant it, add --allow-sensitive-data-access to .mcp.json.
Resources
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。