AWS Lambda Durable Functions
AWS LabsOfficialPublished by AWS Labs
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The AWS Lambda Durable Functions skill provides a framework for orchestrating complex, multi-step applications that require long-running execution, automatic state persistence, and robust error handling. It enables developers to implement patterns like sagas, human-in-the-loop callbacks, and retries while ensuring progress is maintained across interruptions. The skill covers the replay model, step operations, and testing strategies for both TypeScript and Python environments, helping developers build reliable serverless architectures that can run for up to a year.
What it does
- Orchestrates multi-step serverless workflows with automatic state persistence.
- Implements complex error handling patterns including sagas and circuit breakers.
- Supports long-running executions with wait/callback patterns and human-in-the-loop integration.
- Provides a replay-aware environment to ensure determinism in distributed serverless functions.
- Offers testing utilities via LocalDurableTestRunner for local development and validation.
- Enables dynamic step naming and advanced concurrency patterns for AI agents and batch processing.
When to use it
- When building workflows that need to persist state across multiple Lambda invocations.
- When implementing long-running processes that require wait times or external system callbacks.
- When you need robust retry logic and error recovery for distributed serverless tasks.
- When developing complex state machines or saga-based transaction management in AWS.
- When creating AI agent workflows that require reasoning and multi-step tool execution.
Advantages
- Maintains reliable progress for workflows that may run for up to one year.
- Simplifies complex orchestration logic through a structured replay model.
- Provides built-in support for idempotent operations and retry strategies.
- Enables local testing of distributed stateful logic before cloud deployment.
- Reduces boilerplate code for managing state, timeouts, and error recovery.
Usage examples
- “How do I implement a retry strategy for a database update in a durable function?”
- The agent provides a code example using context.step with retry options, explaining how to classify errors as transient or permanent to ensure only appropriate operations are retried.
- “Show me how to wait for an external callback in a Python durable function.”
- The agent generates a Python snippet using context.wait_for_callback, including configuration for timeouts and fallback logic to handle cases where the callback is not received.
- “I am getting a non-deterministic error in my Lambda function, how do I fix it?”
- The agent explains the replay model, identifies non-deterministic code (like Date.now or API calls) outside of steps, and provides a refactored code block moving those calls into context.step.
- “How do I test my durable function locally?”
- The agent guides the user to use the LocalDurableTestRunner, providing a template for instantiating the runner with their handler and executing test cases to verify replay behavior.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/awslabs/aws-lambda-durable-functions/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip aws-lambda-durable-functions.zip -d .agents/skills
Documentation by AWS Labs
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-identityRuntime 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.)
Deployment capability exists (one of):
AWS SAM CLI (
sam --version) 1.153.1 or higherAWS CDK (
cdk --version) v2.237.1 or higherDirect Lambda deployment access
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-testingFor Python:
pip install aws-durable-execution-sdk-python
pip install aws-durable-execution-sdk-python-testingWhen 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 resultCritical Rules
All non-deterministic code MUST be in steps (Date.now, Math.random, API calls)
Cannot nest durable operations - use
runInChildContextto group operationsClosure 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.jsonIAM Permissions
Your Lambda execution role MUST have the AWSLambdaBasicDurableExecutionRolePolicy managed policy attached. This includes:
lambda:CheckpointDurableExecution- Persist execution statelambda:GetDurableExecutionState- Retrieve execution stateCloudWatch Logs permissions
Additional permissions needed for:
Durable invokes:
lambda:InvokeFunctionon target function ARNsExternal 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 stepsNested durable operations in step functions: Cannot call
context.step(),context.wait(), orcontext.invoke()inside a step function — usecontext.runInChildContext()insteadClosure 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
Files
- ATTRIBUTION.mdAdded by AutoGineer942 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer89 B
- SKILL.md9.0 KiB
- references/advanced-error-handling.md4.9 KiB
- references/advanced-patterns.md9.8 KiB
- references/concurrent-operations.md8.4 KiB
- references/deployment-iac.md14.3 KiB
- references/error-handling.md10.9 KiB
- references/getting-started.md11.1 KiB
- references/replay-model-rules.md8.3 KiB
- references/step-operations.md7.4 KiB
- references/testing-patterns.md17.4 KiB
- references/troubleshooting-executions.md8.2 KiB
- references/wait-operations.md9.5 KiB
references/getting-started.md
Getting Started with AWS Lambda durable functions
Quick start guide for building your first durable function.
Language selection
Default: TypeScript
Override syntax:
"use Python" → Generate Python code
"use JavaScript" → Generate JavaScript code
When not specified, ALWAYS use TypeScript
Error Scenarios: Unsupported Language
List detected language
State: "Durable Execution SDK is not yet available for [framework]"
Suggest supported languages as alternatives
Basic Handler
TypeScript:
import { withDurableExecution, DurableContext } from '@aws/durable-execution-sdk-js';
export const handler = withDurableExecution(async (event, context: DurableContext) => {
// Execute a step with automatic retry
const userData = await context.step('fetch-user', async () =>
fetchUserFromDB(event.userId)
);
// Wait without compute charges
await context.wait({ seconds: 5 });
// Process in another step
const result = await context.step('process', async () =>
processUser(userData)
);
return { success: true, data: result };
});Python:
from aws_durable_execution_sdk_python import durable_execution, DurableContext, durable_step, StepContext
from aws_durable_execution_sdk_python.config import Duration
@durable_step
def fetch_user(step_ctx: StepContext, user_id: str):
return fetch_user_from_db(user_id)
@durable_step
def process_user_data(step_ctx: StepContext, user_data: dict):
return process_user(user_data)
@durable_execution
def handler(event: dict, context: DurableContext) -> dict:
user_data = context.step(fetch_user(event['userId']))
context.wait(duration=Duration.from_seconds(5))
result = context.step(process_user_data(user_data))
return {'success': True, 'data': result}Common Patterns
Multi-Step Workflow
TypeScript:
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const validated = await context.step('validate', async () =>
validateInput(event)
);
const processed = await context.step('process', async () =>
processData(validated)
);
await context.wait('cooldown', { seconds: 30 });
await context.step('notify', async () =>
sendNotification(processed)
);
return { success: true };
});GenAI Agent (Agentic Loop)
TypeScript:
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const messages = [{ role: 'user', content: event.prompt }];
while (true) {
const { response, tool } = await context.step('invoke-model', async () =>
invokeAIModel(messages)
);
if (tool == null) return response;
const toolResult = await context.step(`tool-${tool.name}`, async () =>
executeTool(tool, response)
);
messages.push({ role: 'assistant', content: toolResult });
}
});Python:
# Note: invoke_ai_model and execute_tool are decorated with @durable_step
@durable_execution
def handler(event: dict, context: DurableContext) -> str:
messages = [{"role": "user", "content": event["prompt"]}]
while True:
result = context.step(invoke_ai_model(messages))
if result.get("tool") is None:
return result["response"]
tool = result["tool"]
tool_result = context.step(execute_tool(tool, result["response"]))
messages.append({"role": "assistant", "content": tool_result})Human-in-the-Loop Approval
TypeScript:
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const plan = await context.step('generate-plan', async () =>
generatePlan(event)
);
const answer = await context.waitForCallback(
'wait-for-approval',
async (callbackId) => sendApprovalEmail(event.approverEmail, plan, callbackId),
{ timeout: { hours: 24 } }
);
if (answer === 'APPROVED') {
await context.step('execute', async () => performAction(plan));
return { status: 'completed' };
}
return { status: 'rejected' };
});Python:
from aws_durable_execution_sdk_python.config import WaitForCallbackConfig
@durable_execution
def handler(event: dict, context: DurableContext) -> dict:
# Note: generate_plan and perform_action are decorated with @durable_step
plan = context.step(generate_plan(event))
# Wait for external approval
def submit_approval(callback_id: str, ctx):
send_approval_email(event['approver_email'], plan, callback_id)
answer = context.wait_for_callback(
submitter=submit_approval,
name='wait-for-approval',
config=WaitForCallbackConfig(timeout=Duration.from_hours(24))
)
if answer == 'APPROVED':
context.step(perform_action(plan))
return {'status': 'completed'}
return {'status': 'rejected'}Saga Pattern (Compensating Transactions)
TypeScript:
export const handler = withDurableExecution(async (event, context: DurableContext) => {
const compensations: Array<{ name: string; fn: () => Promise<void> }> = [];
try {
await context.step('book-flight', async () => flightClient.book(event));
compensations.push({
name: 'cancel-flight',
fn: () => flightClient.cancel(event)
});
await context.step('book-hotel', async () => hotelClient.book(event));
compensations.push({
name: 'cancel-hotel',
fn: () => hotelClient.cancel(event)
});
return { success: true };
} catch (error) {
for (const comp of compensations.reverse()) {
await context.step(comp.name, async () => comp.fn());
}
throw error;
}
});Project Structure
TypeScript
my-durable-function/
├── src/
│ ├── handler.ts # Main handler
│ ├── steps/ # Step functions
│ │ ├── validate.ts
│ │ └── process.ts
│ └── utils/ # Utilities
│ └── retry-strategies.ts
├── tests/
│ └── handler.test.ts # Tests with LocalDurableTestRunner
├── infrastructure/
│ └── template.yaml # SAM/CloudFormation
├── eslint.config.js # ESLint configuration
├── jest.config.js # Jest configuration
├── tsconfig.json # TypeScript configuration
└── package.jsonPython
my-durable-function/
├── src/
│ ├── handler.py # Main handler
│ ├── steps/ # Step functions
│ │ ├── __init__.py
│ │ ├── validate.py
│ │ └── process.py
│ └── utils/
│ └── retry_strategies.py
├── tests/
│ └── test_handler.py # Tests with DurableFunctionTestRunner
├── infrastructure/
│ └── template.yaml # SAM/CloudFormation
└── pyproject.toml # Project configurationESLint Plugin Setup
Install the ESLint plugin to catch common durable function mistakes at development time:
npm install --save-dev @aws/durable-execution-sdk-js-eslint-pluginOption A: Flat Config (eslint.config.js)
import durableExecutionPlugin from '@aws/durable-execution-sdk-js-eslint-plugin';
export default [
{
plugins: {
'@aws/durable-execution-sdk-js': durableExecutionPlugin,
},
rules: {
'@aws/durable-execution-sdk-js/no-nested-durable-operations': 'error',
},
},
];Option B: Recommended Config
import durableExecutionPlugin from '@aws/durable-execution-sdk-js-eslint-plugin';
export default [
durableExecutionPlugin.configs.recommended,
// Your other configs...
];Option C: Legacy .eslintrc.json
{
"plugins": ["@aws/durable-execution-sdk-js-eslint-plugin"],
"extends": ["plugin:@aws/durable-execution-sdk-js-eslint-plugin/recommended"],
"rules": {
"@aws/durable-execution-sdk-js-eslint-plugin/no-nested-durable-operations": "error"
}
}What the plugin catches:
Nested durable operations inside step functions
Incorrect usage of durable context outside handler
Common replay model violations
Jest Configuration
jest.config.js:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
],
};Key Configuration:
preset: 'ts-jest'- Essential for TypeScript supporttransform- Maps .ts files to ts-jest transformertestMatch- Specifies test file patterns
Python Project Setup
Add aws-durable-execution-sdk-python-testing to your dev/test dependencies in pyproject.toml.
Development Workflow
TypeScript
Write handler with durable operations
Test locally with
LocalDurableTestRunnerValidate replay rules (no non-deterministic code outside steps)
Deploy with qualified ARN (version or alias)
Monitor execution state and logs
Python
Write handler with
@durable_executiondecoratorTest locally with
DurableFunctionTestRunnerand pytestValidate replay rules (no non-deterministic code outside steps)
Deploy with qualified ARN (version or alias)
Monitor execution state and logs
Key Concepts
Steps: Atomic operations with automatic retry and checkpointing
Waits: Suspend execution without compute charges (up to 1 year)
Child Contexts: Group multiple durable operations
Callbacks: Wait for external systems to respond
Map/Parallel: Process arrays or run operations concurrently
Setup Checklist
When starting a new durable function project:
TypeScript
[ ] Install dependencies (
@aws/durable-execution-sdk-js, testing & eslint packages)[ ] Create
jest.config.jswith ts-jest preset[ ] Configure
tsconfig.jsonwith proper module resolution[ ] Set up ESLint with durable execution plugin
[ ] Create handler with
withDurableExecutionwrapper[ ] Write tests using
LocalDurableTestRunner[ ] Use
skipTime: truefor fast test execution[ ] Verify TypeScript compilation:
npx tsc --noEmit[ ] Run tests to confirm setup:
npm test[ ] Review replay model rules (no non-deterministic code outside steps)
Python
[ ] Install
aws-durable-execution-sdk-python[ ] Install
aws-durable-execution-sdk-python-testingandpytestfor testing[ ] Create handler with
@durable_executiondecorator[ ] Define step functions with
@durable_stepdecorator[ ] Write tests using
DurableFunctionTestRunnerclass[ ] Run tests:
pytest[ ] Review replay model rules (no non-deterministic code outside steps)
Error Scenarios
Unsupported Language
List detected language
State: "Durable Execution SDK is not yet available for [language]"
List supported languages as alternatives
Next Steps
Review replay-model-rules.md to avoid common pitfalls
Explore step-operations.md for retry strategies
Learn wait-operations.md for external integrations
Check testing-patterns.md for comprehensive testing
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs a command-line tool, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS Labs
- Publisher
- AWS Labs (Official)
- Source
- awslabs/agent-plugins · plugins/aws-serverless/skills/aws-lambda-durable-functions · commit fbefb37
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS Labs.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-lambda-durable-functions.zip