AWS Lambda Durable Functions
AWSOfficialPublished by AWS
- 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
This skill provides guidance and patterns for implementing durable, multi-step applications on AWS Lambda. It focuses on the replay model, which allows functions to maintain state across long-running executions—up to one year—by automatically checkpointing progress. The skill covers essential architectural patterns such as the saga pattern for error handling, wait/callback mechanisms for external system integration, and testing strategies using the local test runner. It emphasizes strict adherence to deterministic coding practices required by the replay model to ensure reliable execution.
What it does
- Enables state persistence for long-running Lambda functions.
- Provides patterns for implementing the saga pattern and compensating transactions.
- Supports wait/callback patterns for integrating with external systems.
- Offers guidance on testing durable functions locally and in the cloud.
- Defines rules for deterministic code to prevent state corruption during replays.
- Outlines requirements for qualified ARN invocation and IAM permissions.
When to use it
- When building workflows that require execution times longer than standard Lambda timeouts.
- When orchestrating multi-step processes that need to maintain state across interruptions.
- When implementing reliable, fault-tolerant serverless integrations.
- When managing complex state machines or human-in-the-loop approval processes.
- When you need automatic retry logic and checkpointing for critical business processes.
Advantages
- Resilient execution that survives infrastructure interruptions.
- Simplified state management without external databases for simple workflows.
- Native support for complex orchestration patterns like sagas and parallel execution.
- Built-in replay-aware logging and error handling.
- Local testing capabilities to validate complex workflow logic.
Usage examples
- “How do I implement a multi-step workflow with a wait period in AWS Lambda?”
- The agent provides a code example using context.step for logic and context.wait for the delay, ensuring the execution state is persisted correctly.
- “Why is my durable function failing during replay?”
- The agent helps diagnose non-deterministic code (like Date.now() or Math.random()) placed outside of steps, which causes state corruption.
- “How do I handle errors in a long-running durable function?”
- The agent explains the saga pattern and how to implement compensating transactions within steps to roll back state if a step fails.
- “What are the requirements for invoking a durable Lambda function?”
- The agent clarifies that durable functions must be invoked using a qualified ARN (version, alias, or $LATEST) and provides the corresponding AWS CLI command.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/aws/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
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.
Works best with the AWS MCP server but is not required. All AWS interactions in this skill use standard AWS CLI commands that work in any environment with configured AWS credentials.
Critical Rules
Read these before writing any code. Each one is a constraint that will silently break a function if violated.
Durable execution must be enabled at function creation time — it cannot be retrofitted. A new Lambda function must be created with durable execution turned on. Migrate the logic into the new function; do not attempt to install the SDK and wrap the handler of the existing function and expect it to work.
Durable functions must be invoked with a qualified ARN — a specific version, an alias, or the literal
$LATESTsuffix. An unqualified function name will fail. See the Invocation Requirements section below for examples.Durable operations cannot be nested. You cannot call
context.step(),context.wait(), orcontext.invoke()from inside another step's callback. Usecontext.runInChildContext()to group operations instead.All non-deterministic code must run inside steps.
Date.now(),Math.random(), UUID generation, API calls, and database queries outside a step will produce different values on replay and corrupt execution state.Closure mutations are lost on replay - return values from steps
Side effects outside steps repeat - use
context.logger(replay-aware)
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 resultPython 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:live 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
Security Considerations
Checkpoint data encryption: Execution state is persisted automatically. Enable KMS encryption on associated CloudWatch Log Groups to protect checkpointed data at rest.
Sensitive data in step results: Step return values are checkpointed and persisted. Do not return secrets, raw credentials, or PII from steps — store sensitive data in Secrets Manager or SSM Parameter Store and return references instead.
Input validation: Validate and sanitize event payloads at the handler entry point before passing data to steps.
Credential management: Retrieve secrets from AWS Secrets Manager or SSM Parameter Store within steps.
Callback payload validation: Data received via
waitForCallbackoriginates from external systems — validate and sanitize before processing.Logging: Avoid
DEBUGlog level in non-development environments as it may expose step results and execution state. Enable CloudWatch Logs encryption with KMS.
Resources
Files
- ATTRIBUTION.mdAdded by AutoGineer946 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer67 B
- SKILL.md8.9 KiB
- references/advanced-error-handling.md4.9 KiB
- references/advanced-patterns.md10.4 KiB
- references/concurrent-operations.md8.4 KiB
- references/deployment-iac.md14.0 KiB
- references/error-handling.md10.5 KiB
- references/getting-started.md12.6 KiB
- references/replay-model-rules.md8.3 KiB
- references/step-operations.md8.3 KiB
- references/testing-patterns.md17.4 KiB
- references/troubleshooting-executions.md8.5 KiB
- references/wait-operations.md9.5 KiB
references/advanced-patterns.md
Advanced Patterns
Advanced techniques and patterns for sophisticated durable function workflows.
Advanced GenAI Agent Patterns
Agent with Reasoning and Dynamic Step Naming
TypeScript:
export const handler = withDurableExecution(async (event, context: DurableContext) => {
context.logger.info('Starting AI agent', { prompt: event.prompt });
const messages = [{ role: 'user', content: event.prompt }];
while (true) {
// Invoke AI model with reasoning
const { response, reasoning, tool } = await context.step(
'invoke-model',
async (stepCtx) => {
stepCtx.logger.info('Invoking AI model', {
messageCount: messages.length
});
return await invokeAIModel(messages);
}
);
// Log AI's reasoning
if (reasoning) {
context.logger.debug('AI reasoning', { reasoning });
}
// If no tool needed, return response
if (tool == null) {
context.logger.info('AI agent completed - no tool needed');
return response;
}
// Execute tool with dynamic step naming
const toolResult = await context.step(
`execute-tool-${tool.name}`, // Dynamic step name
async (stepCtx) => {
stepCtx.logger.info('Executing tool', {
toolName: tool.name,
toolParams: tool.parameters
});
return await executeTool(tool, response);
}
);
// Add result to conversation
messages.push({
role: 'assistant',
content: toolResult,
});
context.logger.debug('Tool result added', {
toolName: tool.name,
resultLength: toolResult.length
});
}
});Python:
# Note: invoke_ai_model and execute_tool are decorated with @durable_step
@durable_execution
def handler(event: dict, context: DurableContext) -> str:
context.logger.info('Starting AI agent', extra={'prompt': event['prompt']})
messages = [{'role': 'user', 'content': event['prompt']}]
while True:
# Invoke AI model
result = context.step(invoke_ai_model(messages))
response = result['response']
reasoning = result.get('reasoning')
tool = result.get('tool')
if reasoning:
context.logger.debug('AI reasoning', extra={'reasoning': reasoning})
if tool is None:
context.logger.info('AI agent completed')
return response
# Execute tool with dynamic step naming
tool_result = context.step(
func=execute_tool(tool, response),
name=f"execute-tool-{tool['name']}"
)
messages.append({'role': 'assistant', 'content': tool_result})
context.logger.debug('Tool result added', extra={'tool': tool['name']})Step Semantics Deep Dive
AtMostOncePerRetry vs AtLeastOncePerRetry
TypeScript:
import { StepSemantics } from '@aws/durable-execution-sdk-js';
// AtLeastOncePerRetry (DEFAULT) - For operations that can execute multiple times
// Step may execute multiple times per retry attempt
// Use when idempotency is handled externally
await context.step(
'update-database',
async () => {
// This is idempotent - safe to retry
return await updateUserRecord(userId, data);
},
{ semantics: StepSemantics.AtLeastOncePerRetry }
);
// AtMostOncePerRetry - For non-idempotent operations
// Step executes at most once per retry attempt
// If step fails partway through, it won't re-execute the same attempt
await context.step(
'charge-payment',
async () => {
// Non-idempotent - duplicates would double-charge the customer
return await chargePayment(customerId, amount);
},
{
semantics: StepSemantics.AtMostOncePerRetry,
// Pair with shouldRetry: false to guarantee at-most-once overall,
// since the default retry strategy still allows multiple retry attempts.
retryStrategy: () => ({ shouldRetry: false }),
}
);When to use each:
| Semantic | Use When | Example Operations |
|---|---|---|
| AtLeastOncePerRetry (default) | Operation is idempotent, or external dedup exists | Database upserts, idempotency-keyed API calls, queuing systems |
| AtMostOncePerRetry | Operation is non-idempotent, duplicates must be avoided | Charge payment, send unique notification, non-idempotent external writes |
Completion Policies - Interaction and Combination
Combining Multiple Constraints
Completion policies can be combined, and execution stops when the first constraint is met:
TypeScript:
const results = await context.map(
'process-items',
items,
processFunc,
{
completionConfig: {
minSuccessful: 8, // Need at least 8 successes
toleratedFailureCount: 2, // OR can tolerate 2 failures
toleratedFailurePercentage: 20, // OR can tolerate 20% failures
}
}
);
// Execution stops when ANY of these conditions is met:
// 1. 8 successful items (minSuccessful reached)
// 2. 2 failures occur (toleratedFailureCount reached)
// 3. 20% of items fail (toleratedFailurePercentage reached)Understanding Stop Conditions
Example with 10 items:
const items = Array.from({ length: 10 }, (_, i) => i);
const results = await context.map(
'process',
items,
processFunc,
{
maxConcurrency: 3,
completionConfig: {
minSuccessful: 7,
toleratedFailureCount: 3
}
}
);
// Scenario 1: 7 successes, 0 failures
// ✅ Stops after 7th success (minSuccessful reached)
// Remaining 3 items are not processed
// Scenario 2: 5 successes, 3 failures
// ❌ Stops after 3rd failure (toleratedFailureCount reached)
// Remaining 2 items are not processed
// results.throwIfError() will throw because minSuccessful not met
// Scenario 3: 7 successes, 2 failures
// ✅ Stops after 7th success (minSuccessful reached)
// 1 item not processed, but completion policy satisfiedEarly Termination Pattern
Use completion policies for early termination when searching:
TypeScript:
// Stop after finding first match
const results = await context.map(
'find-match',
candidates,
async (ctx, candidate) => {
return await ctx.step(async () => checkMatch(candidate));
},
{
completionConfig: {
minSuccessful: 1 // Stop after first success
}
}
);
// Only one item processed (assuming first succeeds)
if (results.successCount > 0) {
const match = results.succeeded()[0];
context.logger.info('Found match', { match });
}Advanced Error Handling
For timeout handling (waitForCallback, Promise.race), conditional retries, and circuit breaker patterns, see advanced-error-handling.md.
Advanced and Retry Strategies
For conditional retry strategies and circuit breaker patterns, see advanced-error-handling.md.
Custom Serialization Patterns
Class with Date Fields
TypeScript:
import {
createClassSerdesWithDates
} from '@aws/durable-execution-sdk-js';
class User {
name: string = '';
email: string = '';
createdAt: Date = new Date();
updatedAt: Date = new Date();
}
const result = await context.step(
'create-user',
async () => {
const user = new User();
user.name = 'Alice';
user.email = '[email protected]';
user.createdAt = new Date();
user.updatedAt = new Date();
return user;
},
{
serdes: createClassSerdesWithDates(User, ['createdAt', 'updatedAt'])
}
);
// result is properly deserialized User instance with Date objects
console.log(result.createdAt instanceof Date); // trueComplex Object Graphs
TypeScript:
import { createClassSerdes } from '@aws/durable-execution-sdk-js';
class Order {
id: string = '';
items: OrderItem[] = [];
customer: Customer = new Customer();
}
class OrderItem {
sku: string = '';
quantity: number = 0;
}
class Customer {
id: string = '';
name: string = '';
}
// Create serdes for each class
const orderSerdes = createClassSerdes(Order);
const itemSerdes = createClassSerdes(OrderItem);
const customerSerdes = createClassSerdes(Customer);
const result = await context.step(
'process-order',
async () => {
const customer = new Customer();
customer.id = 'CUST-123';
customer.name = 'Alice';
const item1 = new OrderItem();
item1.sku = 'SKU-001';
item1.quantity = 2;
const item2 = new OrderItem();
item2.sku = 'SKU-002';
item2.quantity = 1;
const order = new Order();
order.id = 'ORD-456';
order.items = [item1, item2];
order.customer = customer;
return order;
},
{ serdes: orderSerdes }
);Nested Workflows
Parent-Child Workflow Pattern
TypeScript:
// Parent orchestrator
export const orchestrator = withDurableExecution(
async (event, context: DurableContext) => {
const childFunctionArn = process.env.CHILD_FUNCTION_ARN!;
// Invoke child workflows in parallel
const results = await context.parallel(
'process-batches',
[
{
name: 'batch-1',
func: async (ctx) => ctx.invoke(
'process-batch-1',
childFunctionArn,
{ batch: event.batches[0] }
)
},
{
name: 'batch-2',
func: async (ctx) => ctx.invoke(
'process-batch-2',
childFunctionArn,
{ batch: event.batches[1] }
)
}
]
);
return results.getResults();
}
);
// Child worker
export const worker = withDurableExecution(
async (event, context: DurableContext) => {
const items = event.batch.items;
const results = await context.map(
'process-items',
items,
async (ctx, item) => {
return await ctx.step(async () => processItem(item));
}
);
return results.getResults();
}
);Best Practices Summary
Dynamic Step Naming: Use template literals for dynamic operation names
Structured Logging: Log reasoning and context with each operation
Error Handling: See advanced-error-handling.md for timeout, retry, and circuit breaker patterns
Completion Policies: Understand how combined constraints interact
Custom Serialization: Use proper serdes for complex objects
Nested Workflows: Use invoke for modular, composable architectures
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
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
- Publisher
- AWS (Official)
- Source
- aws/agent-toolkit-for-aws · skills/specialized-skills/serverless-skills/aws-lambda-durable-functions · commit 0a218f8
- 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 or AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-lambda-durable-functions.zip