Skip to content

Commit 624c9e9

Browse files
authored
Merge pull request #2975 from sin-ak/sinak-feature-stepfunction-durable-lambda-function
New serverless pattern - Step Function to durable Lambda function
2 parents 9ba4b7f + 4b2315b commit 624c9e9

15 files changed

Lines changed: 767 additions & 0 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
*.swp
2+
package-lock.json
3+
__pycache__
4+
.pytest_cache
5+
.venv
6+
*.egg-info
7+
8+
# CDK asset staging directory
9+
.cdk.staging
10+
cdk.out
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
# AWS Step Functions to AWS Lambda durable functions
2+
3+
This pattern demonstrates how to integrate AWS Lambda durable functions into an AWS Step Functions workflow. This pattern covers both the synchronous invocation (using default Request Response pattern) and asynchronous invocation (using the Step Function Wait for Callback with Task Token integration pattern) of the durable Lambda function. It addresses the challenge of running long-running Lambda functions (beyond 15 minutes) within a Step Functions orchestration, using asynchronous invocation and durable checkpointing.
4+
5+
Announced at re:Invent 2025, [Lambda durable functions](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) introduce a checkpoint/replay mechanism that allows Lambda executions to run for up to one year, automatically recovering from interruptions. This pattern shows how to combine durable functions with Step Functions in a hybrid architecture: durable functions handle application-level logic within Lambda, while Step Functions coordinates the high-level workflow across multiple AWS services.
6+
7+
Learn more about this pattern at Serverless Land Patterns: [cdk-stepfunction-durable-lambda-function](https://serverlessland.com/patterns/cdk-stepfunction-durable-lambda-function)
8+
9+
Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
10+
11+
## When to Use This Pattern
12+
Use this pattern when you need both Step Functions workflow orchestration and durable function reliability within individual Lambda functions. Common scenarios include:
13+
- You have an existing Step Functions workflow and want to add long-running or stateful Lambda logic without splitting it across multiple functions and states
14+
- You want Step Functions to coordinate high-level workflows across AWS services while keeping complex application logic encapsulated in durable Lambda functions
15+
- You need to reduce the number of Lambda functions and Step Functions states by consolidating multi-step business logic into a single durable function
16+
17+
Many applications benefit from using both services. A common pattern is using durable functions for application-level logic within Lambda, while Step Functions coordinates high-level workflows across multiple AWS services beyond Lambda functions.
18+
19+
For guidance on choosing between durable functions and Step Functions for standalone use, see [Durable functions or Step Functions](https://docs.aws.amazon.com/lambda/latest/dg/durable-step-functions.html) in the AWS documentation.
20+
21+
22+
## Requirements
23+
24+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
25+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
26+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
27+
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html) (AWS CDK >= 2.240.0) Installed
28+
* [Python](https://www.python.org/downloads/) (3.12 or later)
29+
30+
## Deployment Instructions
31+
32+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
33+
```
34+
git clone https://github.com/aws-samples/serverless-patterns
35+
```
36+
1. Change directory to the pattern directory:
37+
```
38+
cd cdk-stepfunction-durable-lambda-function
39+
```
40+
1. Create a virtual environment for python:
41+
```bash
42+
python3 -m venv .venv
43+
```
44+
1. Activate the virtual environment:
45+
```bash
46+
source .venv/bin/activate
47+
```
48+
49+
If you are in Windows platform, you would activate the virtualenv like this:
50+
51+
```
52+
% .venv\Scripts\activate.bat
53+
```
54+
55+
1. Install python modules:
56+
```bash
57+
python3 -m pip install -r requirements.txt
58+
```
59+
1. From the command line, use CDK to synthesize the CloudFormation template and check for errors:
60+
61+
```bash
62+
cdk synth
63+
```
64+
NOTE: You may need to perform a one time cdk bootstrapping using the following command. See [CDK Bootstrapping](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) for more details.
65+
```bash
66+
cdk bootstrap aws://<ACCOUNT-NUMBER-1>/<REGION-1>
67+
```
68+
69+
1. From the command line, use CDK to deploy the stack:
70+
71+
```bash
72+
cdk deploy
73+
```
74+
75+
Expected result:
76+
77+
```bash
78+
✅ CdkStepfunctionDurableLambdaFunctionStack
79+
80+
Outputs:
81+
CdkStepfunctionDurableLambdaFunctionStack.AsyncDurableFunctionName = sfn-dfn-async-durable-fn
82+
CdkStepfunctionDurableLambdaFunctionStack.StepFunctionDFArn = arn:aws:states:us-east-1:XXXXXXXXXXXX:stateMachine:sfn-dfn-integration-pattern-cdk
83+
CdkStepfunctionDurableLambdaFunctionStack.SyncDurableFunctionName = sfn-dfn-sync-durable-fn
84+
Stack ARN:
85+
arn:aws:cloudformation:us-east-1:XXXXXXXXXXXX:stack/CdkStepfunctionDurableLambdaFunctionStack/e4d30000-0000-0000-0000-000000007503
86+
87+
```
88+
89+
1. Note the outputs from the CDK deployment process. These contain the resource names and/or ARNs which are used for testing.
90+
91+
92+
93+
## How it works
94+
95+
Once the CDK stack is deployed successfully, a Step Function workflow is created along with two durable Lambda functions in the account & region provided during the bootstrap step. Go to AWS Step Function Console to understand the basic state machine created.
96+
97+
- The `sfn-dfn-async-durable-fn` durable Lambda function simulates a long running task that takes more than 15 mins (using a Wait condition). To avoid hitting Lambda function's 15 mins timeout, the function is configured with a durable execution timeout of 1 hr. As a result, this Lambda function can only be invoked asynchronously by setting the [InvocationType](https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html#lambda-Invoke-request-InvocationType) parameter to `Event`.
98+
- The `sfn-dfn-sync-durable-fn` durable Lambda function simulates a short running task that completes within the 15 mins timeout. It is configured with a durable execution timeout of 15 mins which matches the standard Lambda function timeout. This Lambda function can be invoked synchronously without specifying any InvocationType parameter (or using `RequestResponse` value, which is also the default).
99+
100+
See AWS documentation for more details on [Invoking durable Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/durable-invoking.html).
101+
102+
#### Step Functions State Machine
103+
![image](./resources/stepfunctions_graph.png)
104+
105+
The state machine invokes these 2 durable Lambda functions in the following pattern:
106+
1. When the state machine starts, it first executes the 'Async Durable Lambda Fn Invoke' task, which invokes the `sfn-dfn-async-durable-fn` Lambda function. Since Step Functions' default `LambdaInvoke` uses synchronous invocation, we need to change to the '[Wait for Callback with Task Token](https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token)' integtation pattern with asynchronous invocation, otherwise Step Function task will throw an error -
107+
```
108+
Lambda.InvalidParameterValueException: You cannot synchronously invoke a durable function with an executionTimeout greater than 15 minutes.
109+
```
110+
The below state machine ASL snippet shows this configuration:
111+
```bash
112+
"Async Durable Lambda Fn Invoke": {
113+
"Type": "Task",
114+
"Resource": "arn:aws:states:::lambda:invoke.waitForTaskToken", # wait for callback integration pattern
115+
"InvocationType": "Event", # set InvocationType = 'Event' for async Lambda invocation
116+
"Arguments": {
117+
"FunctionName": "arn:aws:lambda:us-east-1:XXXXXXXXXXXX:function:sfn-dfn-async-durable-fn:1", # durable Lambda functions must be invoked with a qualified ARN (version or alias)
118+
"Payload": {
119+
"TaskToken": "{% $states.context.Task.Token %}", # pass the task-token to Lambda for a callback later.
120+
"minutes_to_wait": "{% $states.input.minutes_to_wait %}"
121+
},
122+
"HeartbeatSeconds": 3600, # set a heartbeat timeout of 1 hr before task is considered failed
123+
},
124+
"Output": "{% $states.result %}"
125+
}
126+
```
127+
> Note: Durable functions require qualified identifiers for invocation. You must invoke durable functions using a version number, alias, or $LATEST. You can use either a full qualified ARN or a function name with version/alias suffix. You cannot use an unqualified identifier (without a version or alias suffix). See AWS Documentation for more details on [Qualified ARNs requirement](https://docs.aws.amazon.com/lambda/latest/dg/durable-invoking.html#durable-invoking-qualified-arns).
128+
129+
Since this durable Lambda function has an artificial wait time of X mins (specified as a Step Function input), both the Step Functions execution and durable Lambda function execution will pause, without consuming any CPU. Once the wait timer expires, durable Lambda function will resume execution from this point, having checkpointed the previous steps. Since this Lambda was invoked asynchronously, we need to call Step Functions' `send_task_success` or `send_task_failure` API and pass the task-token that was sent as an event parameter to the Lambda from Step Function. This will enable the Step Functions to resume its state machine.
130+
131+
IMPORTANT: When using Step Function WAIT_FOR_TASK_TOKEN pattern, wrap SendTaskSuccess in context.step() in your Lambda code to make it durable. If placed outside context.step(), it will execute on every replay causing duplicate callbacks, or may never execute if Lambda is interrupted, leaving Step Functions waiting indefinitely. Also, send callback as the FINAL durable step.
132+
133+
2. The state machine then executes the 'synchronous Durable Lambda Fn Invoke' task which invokes the `sfn-dfn-sync-durable-fn` Lambda function. Since this function can be invoked synchronously, we use the default Step Function task configuration, as shown below -
134+
```bash
135+
"Synchronous Durable Lambda Fn Invoke": {
136+
"Type": "Task",
137+
"Resource": "arn:aws:states:::lambda:invoke", # default request-response pattern to invoke Lambda synchronously
138+
"Arguments": {
139+
"FunctionName": "arn:aws:lambda:us-east-1:XXXXXXXXXXXX:function:sfn-dfn-sync-durable-fn:1", # durable Lambda functions must be invoked with a qualified ARN (version or alias)
140+
"Payload": "{% $states.input %}"
141+
},
142+
"Output": "{% $states.result.Payload %}",
143+
"End": true
144+
}
145+
},
146+
```
147+
Once the Lambda function completes its execution and returns a response, Step Functions completes the task execution and end the state machine flow.
148+
149+
## Testing
150+
151+
Go to the AWS Step Functions Console and select the Step Function created by CDK (look for a name starting with `sfn-dfn-integration-pattern-cdk`). Execute the step function workflow and provide the input parameters as described below - this makes the Lambda durable function wait for 20 mins, which is more than the standard Lambda execution timeout. Since the durable execution configuration is set at 1 hr, Lambda will pause and resume execution after 20 mins, instead of timing out.
152+
```bash
153+
{
154+
"minutes_to_wait": 20
155+
}
156+
```
157+
158+
Wait for the Step Function workflow to complete. You can check the progress of the execution steps under the Executions section.
159+
160+
> NOTE: Since we have artificially added a wait condition in the `sfn-dfn-async-durable-fn` durable Lambda function which will wait for the duration specified in the state machine execution input parameters, the function will pause until the timer expires. For testing purposes, change the timeout to a smaller value
161+
162+
You can check the Durable executions section on the AWS Lambda service console for the `sfn-dfn-async-durable-fn` durable Lambda function to see how the various steps are checkpointed.
163+
164+
#### Durable execution in the Lambda console
165+
![durable](./resources/Lambda-durable-execution.png)
166+
167+
## Best practices for Lambda durable functions and Step Functions integration
168+
Durable functions use a replay-based execution model that requires different patterns than traditional Lambda functions. Follow these best practices to build reliable, cost-effective workflows. Please see AWS documentation for more details on [Best practices for Lambda durable functions](https://docs.aws.amazon.com/lambda/latest/dg/durable-best-practices.html).
169+
170+
- Synchronous invocation is not supported for durable functions with execution_timeout > 15 minutes. Always use WAIT_FOR_TASK_TOKEN + invocation_type=EVENT.
171+
- `SendTaskSuccess` must be a durable step. Placing it outside context.step() risks duplicate callbacks on replay or missed callbacks on interruption.
172+
- Durable and standard Lambdas can coexist in the same workflow.
173+
174+
175+
## Cleanup
176+
1. Delete the stack
177+
```bash
178+
cdk destroy
179+
```
180+
181+
## Tutorial
182+
183+
See [this useful workshop](https://cdkworkshop.com/30-python.html) on working with the AWS CDK for Python projects.
184+
185+
## Useful commands
186+
187+
* `cdk ls` list all stacks in the app
188+
* `cdk synth` emits the synthesized CloudFormation template
189+
* `cdk deploy` deploy this stack to your default AWS account/region
190+
* `cdk diff` compare deployed stack with current state
191+
* `cdk docs` open CDK documentation
192+
193+
----
194+
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.
195+
196+
SPDX-License-Identifier: MIT-0
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/usr/bin/env python3
2+
import os
3+
4+
import aws_cdk as cdk
5+
6+
from cdk_stepfunction_durable_lambda_function.cdk_stepfunction_durable_lambda_function_stack import CdkStepfunctionDurableLambdaFunctionStack
7+
8+
9+
app = cdk.App()
10+
CdkStepfunctionDurableLambdaFunctionStack(app, "CdkStepfunctionDurableLambdaFunctionStack",
11+
# If you don't specify 'env', this stack will be environment-agnostic.
12+
# Account/Region-dependent features and context lookups will not work,
13+
# but a single synthesized template can be deployed anywhere.
14+
15+
# Uncomment the next line to specialize this stack for the AWS Account
16+
# and Region that are implied by the current CLI configuration.
17+
18+
#env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')),
19+
20+
# Uncomment the next line if you know exactly what Account and Region you
21+
# want to deploy the stack to. */
22+
23+
#env=cdk.Environment(account='123456789012', region='us-east-1'),
24+
25+
# For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
26+
)
27+
28+
app.synth()
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
from aws_durable_execution_sdk_python.config import Duration
2+
from aws_durable_execution_sdk_python.context import DurableContext, StepContext, durable_step
3+
from aws_durable_execution_sdk_python.execution import durable_execution
4+
import random
5+
import datetime
6+
import boto3
7+
import json
8+
9+
@durable_step
10+
def create_order(context: StepContext):
11+
order_id = f"order-{random.randint(1, 100)}"
12+
context.logger.info(f"Creating order... : {order_id}")
13+
return {
14+
"order_id": order_id,
15+
"total": 50.00,
16+
"status": "Created"
17+
}
18+
19+
@durable_step
20+
def send_notification(context: StepContext, order_id: str):
21+
context.logger.info(f"Sending notification...")
22+
return {
23+
"sent": True,
24+
"order_id": order_id,
25+
"recipient": "customer@example.com",
26+
"timestamp": datetime.datetime.now().isoformat()
27+
}
28+
29+
@durable_step
30+
def send_sfn_task_success(context: StepContext, task_token: str, response: dict):
31+
sfn_client = boto3.client("stepfunctions")
32+
try:
33+
sfn_client.send_task_success(
34+
taskToken=task_token,
35+
output=json.dumps(response, default=str),
36+
)
37+
except Exception as e:
38+
context.logger.error(f"send_task_success failed: {e}. Sending task failure to Step Functions.")
39+
sfn_client.send_task_failure(
40+
taskToken=task_token,
41+
error=type(e).__name__,
42+
cause=str(e)[:256]
43+
)
44+
raise
45+
46+
@durable_execution
47+
def lambda_handler(event: dict, context: DurableContext) -> dict:
48+
context.logger.info(f"Async Durable Lambda Event: {event}")
49+
50+
# Extract Step Function Task Token outside durable step
51+
# Only deterministic operations like event.pop("TaskToken") are safe outside steps.
52+
task_token = event.pop("TaskToken", None)
53+
minutes_to_wait = event.pop("minutes_to_wait", 1)
54+
55+
# Step 1: Create the order
56+
order_details = context.step(create_order())
57+
context.logger.info(f"Order created: {order_details['order_id']}")
58+
59+
# Step 2: Wait X minutes - simulate a long running task
60+
context.logger.info(f"Waiting {minutes_to_wait} minutes before sending notification...")
61+
context.wait(Duration.from_minutes(minutes_to_wait))
62+
63+
# Step 3: Send notification
64+
context.logger.info(f"Waited for {minutes_to_wait} minutes without consuming CPU.")
65+
notification_details = context.step(send_notification(order_details['order_id']))
66+
context.logger.info("Notification sent successfully...")
67+
68+
response = {
69+
"success": True,
70+
"notification": notification_details
71+
}
72+
73+
# IMPORTANT: When using Step Function WAIT_FOR_TASK_TOKEN pattern,
74+
# wrap SendTaskSuccess in context.step() to make it durable.
75+
# If placed outside context.step(), it will execute on every
76+
# replay causing duplicate callbacks, or may never execute if
77+
# Lambda is interrupted, leaving Step Functions waiting indefinitely.
78+
# Send callback as the FINAL durable step
79+
if task_token:
80+
context.logger.info("Resuming Step Function by calling send_task_success with task_token")
81+
context.step(send_sfn_task_success(task_token, response))
82+
83+
return response

0 commit comments

Comments
 (0)