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

AWS Lambda Durable Functions

AWSOfficialPublished by AWS

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

From the author

Builds 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, durable execution, workflow orchestration, state machines, retry/checkpoint patterns, long-running stateful Lambda functions, saga pattern, human-in-the-loop callbacks, reliable serverless applications, context.step, context.wait, context.invoke, context.runInChildContext, withDurableExecution, DurableContext, UnrecoverableInvocationError, durable-execution-sdk, qualified ARN invocation, and durable handler replay.
— the description by AWS

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/aws/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

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.

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

  2. Durable functions must be invoked with a qualified ARN — a specific version, an alias, or the literal $LATEST suffix. An unqualified function name will fail. See the Invocation Requirements section below for examples.

  3. Durable operations cannot be nested. You cannot call context.step(), context.wait(), or context.invoke() from inside another step's callback. Use context.runInChildContext() to group operations instead.

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

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

  6. 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 result
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:live 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

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 waitForCallback originates from external systems — validate and sanitize before processing.

  • Logging: Avoid DEBUG log level in non-development environments as it may expose step results and execution state. Enable CloudWatch Logs encryption with KMS.

Resources

Files

references/concurrent-operations.md

Concurrent Operations

Process arrays and run operations in parallel with concurrency control.

Map Operations

Process arrays with automatic concurrency control and completion policies:

TypeScript:

const items = [1, 2, 3, 4, 5];

const results = await context.map(
  'process-items',
  items,
  async (ctx, item, index) => {
    return await ctx.step(`process-${index}`, async () => 
      processItem(item)
    );
  },
  {
    maxConcurrency: 3,
    completionConfig: {
      minSuccessful: 4,
      toleratedFailureCount: 1
    }
  }
);

results.throwIfError();
const allResults = results.getResults();

Python:

# Note: process is decorated with @durable_step
from aws_durable_execution_sdk_python.config import MapConfig, CompletionConfig

items = [1, 2, 3, 4, 5]

def process_item(ctx: DurableContext, item: int, index: int, items: list):
    return ctx.step(process(item), name=f'process-{index}')

results = context.map(
    inputs=items,
    func=process_item,
    name='process-items',
    config=MapConfig(
        max_concurrency=3,
        completion_config=CompletionConfig(
            min_successful=4,
            tolerated_failure_count=1
        )
    )
)

results.throw_if_error()
all_results = results.get_results()

Parallel Operations

Run heterogeneous operations concurrently:

TypeScript:

const results = await context.parallel(
  'parallel-ops',
  [
    {
      name: 'fetch-user',
      func: async (ctx) => ctx.step(async () => fetchUser(userId))
    },
    {
      name: 'fetch-orders',
      func: async (ctx) => ctx.step(async () => fetchOrders(userId))
    },
    {
      name: 'fetch-preferences',
      func: async (ctx) => ctx.step(async () => fetchPreferences(userId))
    }
  ],
  { maxConcurrency: 3 }
);

const [user, orders, preferences] = results.getResults();

Python:

# Note: fetch_user, fetch_orders, fetch_preferences are decorated with @durable_step
from aws_durable_execution_sdk_python.config import ParallelConfig

def fetch_user_data(ctx: DurableContext):
    return ctx.step(fetch_user(user_id))

def fetch_orders_data(ctx: DurableContext):
    return ctx.step(fetch_orders(user_id))

def fetch_prefs_data(ctx: DurableContext):
    return ctx.step(fetch_preferences(user_id))

results = context.parallel(
    [fetch_user_data, fetch_orders_data, fetch_prefs_data],
    name='parallel-ops',
    config=ParallelConfig(max_concurrency=3)
)

user, orders, preferences = results.get_results()

Completion Policies

Minimum Successful

Require a minimum number of successful operations:

TypeScript:

const results = await context.map(
  'process-batch',
  items,
  async (ctx, item, index) => ctx.step(async () => process(item)),
  {
    completionConfig: {
      minSuccessful: 8  // Need at least 8 successes
    }
  }
);
Tolerated Failures

Allow a specific number of failures:

TypeScript:

const results = await context.map(
  'process-batch',
  items,
  async (ctx, item, index) => ctx.step(async () => process(item)),
  {
    completionConfig: {
      toleratedFailureCount: 2  // Allow up to 2 failures
    }
  }
);
Tolerated Failure Percentage

Allow a percentage of failures:

TypeScript:

const results = await context.map(
  'process-batch',
  items,
  async (ctx, item, index) => ctx.step(async () => process(item)),
  {
    completionConfig: {
      toleratedFailurePercentage: 10  // Allow up to 10% failures
    }
  }
);

Python:

results = context.map(
    inputs=items,
    func=process_item,
    config=MapConfig(
        completion_config=CompletionConfig(
            tolerated_failure_percentage=10
        )
    ),
    name='process-batch'
)

Batch Result Handling

Check Status

TypeScript:

const results = await context.map('process', items, processFunc);

console.log(results.status);           // 'SUCCEEDED' | 'FAILED'
console.log(results.totalCount);       // Total items
console.log(results.startedCount);     // Items started
console.log(results.successCount);     // Successful items
console.log(results.failureCount);     // Failed items
console.log(results.hasFailure);     // Boolean
Get Results

TypeScript:

// Get all results (throws if any failed)
const allResults = results.getResults();

// Get successful results only
const successful = results.succeeded().map(item => item.result);

// Get failed items
const failed = results.failed().map(item => ({
  index: item.index,
  error: item.error
}));

// Get all items with status
const all = results.all.map(item => ({
  index: item.index,
  status: item.status,
  result: item.result,
  error: item.error
}));
Error Handling

TypeScript:

const results = await context.map('process', items, processFunc);

if (results.hasFailure) {
  context.logger.error('Some items failed', {
    failureCount: results.failureCount,
    failures: results.failed().map(f => f.index)
  });
  
  // Retry failed items
  const failedItems = results.failed().map(f => items[f.index]);
  await context.map('retry-failed', failedItems, processFunc);
}

Concurrency Control

Fixed Concurrency

TypeScript:

const results = await context.map(
  'process',
  items,
  processFunc,
  { maxConcurrency: 5 }  // Process 5 items at a time
);
Dynamic Concurrency

Adjust based on item characteristics:

TypeScript:

const results = await context.map(
  'process',
  items,
  async (ctx, item, index) => {
    // Heavy items get their own processing
    if (item.size > 1000) {
      return await ctx.step(`heavy-${index}`, async () => 
        processHeavy(item)
      );
    }
    
    // Light items can be batched
    return await ctx.step(`light-${index}`, async () => 
      processLight(item)
    );
  },
  { maxConcurrency: 10 }
);

Advanced Patterns

Map with Callbacks

TypeScript:

const results = await context.map(
  'process-with-approval',
  items,
  async (ctx, item, index) => {
    const processed = await ctx.step('process', async () => 
      process(item)
    );
    
    const approved = await ctx.waitForCallback(
      'approval',
      async (callbackId) => sendApproval(item, callbackId),
      { timeout: { hours: 24 } }
    );
    
    return { processed, approved };
  },
  { maxConcurrency: 3 }
);
Nested Map Operations

TypeScript:

const results = await context.map(
  'process-batches',
  batches,
  async (ctx, batch, batchIndex) => {
    return await ctx.map(
      `batch-${batchIndex}`,
      batch.items,
      async (itemCtx, item, itemIndex) => {
        return await itemCtx.step(async () => process(item));
      }
    );
  }
);
Map with Child Contexts

TypeScript:

const results = await context.map(
  'complex-process',
  items,
  async (ctx, item, index) => {
    return await ctx.runInChildContext(`item-${index}`, async (childCtx) => {
      const validated = await childCtx.step('validate', async () => 
        validate(item)
      );
      
      await childCtx.wait({ seconds: 1 });
      
      const processed = await childCtx.step('process', async () => 
        process(validated)
      );
      
      return processed;
    });
  },
  { maxConcurrency: 5 }
);

Performance Optimization

Batch Size Selection
// Small items: Higher concurrency
const results = await context.map(
  'small-items',
  smallItems,
  processFunc,
  { maxConcurrency: 20 }
);

// Large items: Lower concurrency
const results = await context.map(
  'large-items',
  largeItems,
  processFunc,
  { maxConcurrency: 3 }
);
Early Termination

Use completion policies to stop early:

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
    }
  }
);

Best Practices

  1. Set appropriate maxConcurrency based on downstream system capacity

  2. Use completion policies to handle partial failures gracefully

  3. Name all operations for debugging

  4. Handle batch results explicitly - check for failures

  5. Consider retry strategies for failed items

  6. Monitor concurrency limits to avoid overwhelming systems

  7. Use child contexts for complex per-item workflows

  8. Implement circuit breakers for external service calls

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