Generated banner for AWS Lambda Durable Functions
Generated logo for AWS Lambda Durable Functions

AWS Lambda Durable Functions

AWS LabsOfficialPublished by AWS Labs

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk

From the author

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.
— the description by AWS Labs

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/awslabs/aws-lambda-durable-functions/download
  2. Unzip 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:

  1. AWS CLI is installed (2.33.22 or higher) and configured:

    aws --version
    aws sts get-caller-identity
  2. 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.)

  3. 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

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
  1. All non-deterministic code MUST be in steps (Date.now, Math.random, API calls)

  2. Cannot nest durable operations - use runInChildContext to group operations

  3. Closure mutations are lost on replay - return values from steps

  4. 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_step decorator + context.step(my_step(args)), or inline context.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 DurableFunctionTestRunner class directly - instantiate with handler, use context manager, call run(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 state

  • lambda:GetDurableExecutionState - Retrieve execution state

  • CloudWatch Logs permissions

Additional permissions needed for:

  • Durable invokes: lambda:InvokeFunction on target function ARNs

  • External callbacks: Systems need lambda:SendDurableExecutionCallbackSuccess and lambda:SendDurableExecutionCallbackFailure

Validation Guidelines

When writing or reviewing durable function code, ALWAYS check for these replay model violations:

  1. Non-deterministic code outside steps: Date.now(), Math.random(), UUID generation, API calls, database queries must all be inside steps

  2. Nested durable operations in step functions: Cannot call context.step(), context.wait(), or context.invoke() inside a step function — use context.runInChildContext() instead

  3. Closure mutations that won't persist: Variables mutated inside steps are NOT preserved across replays — return values from steps instead

  4. Side effects outside steps that repeat on replay: Use context.logger for logging (it is replay-aware and deduplicates automatically)

When implementing or modifying tests for durable functions, ALWAYS verify:

  1. All operations have descriptive names

  2. Tests get operations by NAME, never by index

  3. Replay behavior is tested with multiple invocations

  4. Use LocalDurableTestRunner for 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

references/advanced-error-handling.md

Advanced Error Handling

Advanced error handling patterns for durable functions, including timeout handling, circuit breakers, and conditional retry strategies.

Timeout Handling with Callbacks

Pattern: Wait for an external callback with a timeout, and implement fallback logic if the timeout is reached.

Implementation approach:

  1. Use waitForCallback (TypeScript) or wait_for_callback (Python) with a timeout configuration set in the config argument

  2. Wrap in try-catch to handle timeout errors

  3. Check if the error is a timeout

  4. Implement fallback logic in a step (e.g., escalate to manager, use default value, retry with different parameters)

  5. Return appropriate status indicating timeout occurred

Key considerations:

  • Timeout errors are thrown when the callback doesn't complete within the specified duration

  • Fallback logic should be in a step to ensure it's checkpointed

  • Log timeout events for monitoring and debugging

Local Timeout with Promise.race in Typescript SDK

Pattern: Implement a timeout for a step operation within a single Lambda invocation.

Implementation approach:

  1. Use Promise.race() to race the step operation against a timeout promise

  2. The timeout promise rejects after the specified duration

  3. Catch the timeout error and implement fallback logic

  4. Execute fallback operation in a separate step

Important limitation: In TypeScript, native setTimeout (and patterns like Promise.race using it) will fail during execution replays. To create a reliable timeout that persists across execution (expands over multi invocations), always use the timeout parameter provided by waitForCallback or waitForCondition

Conditional Retry Based on Error Type

Pattern: Retry operations selectively based on the type of error encountered.

Implementation approach:

  1. Define a custom retry strategy function that examines the error

  2. For client errors (4xx): Don't retry - these are permanent failures

  3. For server errors (5xx): Retry with exponential backoff

  4. For network errors: Retry with fixed delay

  5. For unknown errors: Don't retry by default

Key considerations:

  • Client errors (400-499) typically indicate bad input and shouldn't be retried

  • Server errors (500-599) are often transient and benefit from retry

  • Network errors (connection refused, timeout) should retry with reasonable limits

  • Use exponential backoff for server errors to avoid overwhelming the service

  • Set maximum retry attempts to prevent infinite loops

Circuit Breaker Pattern

Pattern: Temporarily stop making requests to a failing external service to prevent cascading failures.

Implementation approach:

  1. Track failure count and last failure time (note: these reset on replay due to closure mutations)

  2. Check if circuit is "open" (too many recent failures)

  3. If open, throw a circuit breaker error and wait before retrying

  4. If closed, attempt the operation

  5. On success, reset failure count

  6. On failure, increment failure count and record timestamp

  7. Configure retry strategy to wait longer when circuit is open

Important caveat: The example implementations use closure variables (failureCount, lastFailureTime) which reset on replay. For production use, store circuit breaker state in:

  • A step return value that persists across replays

  • An external store like DynamoDB

  • A durable variable pattern

Key considerations:

  • Circuit breaker prevents cascading failures to downstream services

  • The "open" duration should be long enough for the service to recover

  • Reset the circuit on successful operations

  • Log circuit state changes for monitoring

Error Handling Best Practices

  1. Timeout Handling: Always implement fallback logic for callback timeouts - don't let executions fail silently

  2. Conditional Retries: Classify errors as transient vs permanent, only retry transient errors

  3. Circuit Breakers: Protect against cascading failures to external services, especially for high-volume operations

  4. Structured Logging: Log error context (error type, attempt count, operation name) for debugging

  5. Graceful Degradation: Return partial results when possible rather than failing completely

  6. Error Classification: Distinguish between client errors (don't retry), server errors (retry with backoff), and network errors (retry with fixed delay)

Common Error Patterns

Transient Errors (Should Retry)
  • Network timeouts

  • Service unavailable (503)

  • Rate limiting (429)

  • Database connection failures

  • Temporary infrastructure issues

Permanent Errors (Should Not Retry)
  • Invalid input (400)

  • Authentication failures (401, 403)

  • Resource not found (404)

  • Business logic violations

  • Validation errors

Timeout Errors (Need Fallback)
  • Callback timeouts - external system didn't respond in time

  • External system delays - service is slow or unresponsive

  • Long-running operations - operation exceeded expected duration

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