Skip to content

Commit 7891a63

Browse files
authored
Merge pull request #2743 from avnishamzn/avnishamzn-feature-ddbstream-lambda-sfn-cdk-ts
Avnishamzn/Saptob feature ddbstream lambda sfn cdk ts
2 parents 434cbb5 + 28b9211 commit 7891a63

12 files changed

+1054
-0
lines changed

ddbstream-lambda-sfn-cdk-ts/README.md

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
2+
# Amazon DynamoDB Stream to AWS Step Functions Trigger
3+
4+
This Pattern demonstrates how to automatically trigger AWS Step Functions workflows in response to changes in DynamoDB tables. The CDK construct `DynamoWorkflowTrigger` lets you connect DynamoDB and Step Functions by allowing you to define event handlers that monitor specific changes in your DynamoDB tables and trigger workflows in response. It leverages Lambda functions to evaluate conditions and start Step Functions state machines with inputs derived from the DynamoDB events.
5+
6+
Learn more about this pattern at Serverless Land Patterns: [https://serverlessland.com/patterns/ddbstream-lambda-sfn-cdk-ts](https://serverlessland.com/patterns/ddbstream-lambda-sfn-cdk-ts)
7+
8+
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.
9+
10+
## Requirements
11+
12+
* [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.
13+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
14+
* [Node and NPM](https://nodejs.org/en/download/) installed
15+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
16+
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) (AWS CDK) installed
17+
18+
## Deployment Instructions
19+
20+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
21+
```
22+
git clone https://github.com/aws-samples/serverless-patterns
23+
```
24+
2. Change directory to the pattern directory:
25+
```
26+
cd ddbstream-lambda-sfn-cdk-ts
27+
```
28+
3. To deploy from the command line use the following:
29+
```bash
30+
npm install
31+
npm run lambda
32+
cdk deploy
33+
```
34+
**The deployment will take a couple of minutes**
35+
36+
4. Note the outputs from the CDK deployment process. These contain the `<table_name>`, `<state-machine-arn>` and `<lambda-function-name>` which are used for testing.
37+
38+
39+
40+
## How It Works
41+
42+
![Architecture Diagram](ddbstream-lambda-sfn-cdk-ts.png)
43+
44+
The `DdbstreamLambdaSfnExampleStack` demonstrates how to use the the pattern:
45+
46+
1. It creates a DynamoDB table (`TestTable`) with streaming enabled
47+
2. It creates a simple Step Functions state machine (`TestStateMachine`)
48+
3. It sets up a trigger with the following behavior:
49+
- It applies a filter to ignore events where a `SkipMe` attribute exists in the new image
50+
- It only processes `MODIFY` events (updates to existing items)
51+
- It checks two conditions:
52+
- The new value of `testKey` must be "test8"
53+
- The old value of `testKey` must have been "test9"
54+
- When all conditions are met, it triggers the state machine with input parameters extracted from the DynamoDB event:
55+
- `Index` taken from the item's partition key
56+
- `MapAttribute` taken from the first element in a list attribute
57+
58+
This workflow allows you to respond to specific data changes in DynamoDB by executing custom workflows with Step Functions.
59+
60+
61+
#### Features
62+
63+
- Dead letter queue for failed invocations
64+
- VPC support
65+
- Custom security groups
66+
- Fine-grained event filtering
67+
- Multiple event handlers per construct
68+
- JSONPath-based condition evaluation
69+
- Input mapping for state machines
70+
71+
#### Limitations
72+
73+
- Tables must have streams enabled with `NEW_AND_OLD_IMAGES`
74+
- Conditions currently only support exact matches via the `value` property
75+
- For complex filtering, use Lambda event source filters
76+
77+
## Testing
78+
79+
You can test the workflow using the AWS CLI to create and modify items in the DynamoDB table. Here are some example commands to test different scenarios:
80+
81+
1. First, create an item that shouldn't trigger the workflow (initial state):
82+
```bash
83+
aws dynamodb put-item \
84+
--table-name <table_name> \
85+
--item '{
86+
"Index": {"S": "test-item-1"},
87+
"testKey": {"S": "test9"},
88+
"ListAttribute": {"L": [{"S": "first-element"}]}
89+
}'
90+
```
91+
92+
2. Update the item to trigger the workflow (meets all conditions):
93+
```bash
94+
aws dynamodb update-item \
95+
--table-name <table_name> \
96+
--key '{"Index": {"S": "test-item-1"}}' \
97+
--update-expression "SET testKey = :newval" \
98+
--expression-attribute-values '{":newval": {"S": "test8"}}'
99+
```
100+
101+
3. Test the SkipMe filter by creating an item that should be ignored:
102+
```bash
103+
aws dynamodb put-item \
104+
--table-name <table_name> \
105+
--item '{
106+
"Index": {"S": "test-item-2"},
107+
"testKey": {"S": "test9"},
108+
"SkipMe": {"S": "true"}
109+
}'
110+
```
111+
This should not trigger DDBEventTrigger lambda at all.
112+
113+
To verify the results:
114+
115+
1. Check if the Step Function was triggered:
116+
```bash
117+
aws stepfunctions list-executions \
118+
--state-machine-arn <state-machine-arn>
119+
```
120+
121+
2. View the execution details:
122+
```bash
123+
aws stepfunctions get-execution-history \
124+
--execution-arn <execution-arn-from-previous-command>
125+
```
126+
127+
3. Monitor Lambda function logs:
128+
```bash
129+
aws logs tail /aws/lambda/<lambda-function-name> --follow
130+
```
131+
132+
133+
#### Troubleshooting
134+
135+
- Check Amazon CloudWatch Logs for the Lambda function
136+
- Monitor the dead letter queue for failed events
137+
- Ensure Amazon IAM permissions are correct for DynamoDB stream access and Step Functions execution
138+
139+
## Cleanup
140+
141+
1. From the command line, use the following in the source folder
142+
```bash
143+
cdk destroy
144+
```
145+
2. Confirm the removal and wait for the resource deletion to complete.
146+
----
147+
148+
149+
150+
Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
151+
152+
SPDX-License-Identifier: MIT-0

ddbstream-lambda-sfn-cdk-ts/app.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/env node
2+
import 'source-map-support/register';
3+
import * as cdk from 'aws-cdk-lib';
4+
import { DdbstreamLambdaSfnExampleStack } from './src/lib/ddbstream-lambda-sfn-example-stack';
5+
6+
const app = new cdk.App();
7+
new DdbstreamLambdaSfnExampleStack(app, 'DDBEventTrigger', {
8+
/* If you don't specify 'env', this stack will be environment-agnostic.
9+
* Account/Region-dependent features and context lookups will not work,
10+
* but a single synthesized template can be deployed anywhere. */
11+
12+
/* Uncomment the next line to specialize this stack for the AWS Account
13+
* and Region that are implied by the current CLI configuration. */
14+
// env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
15+
16+
/* Uncomment the next line if you know exactly what Account and Region you
17+
* want to deploy the stack to. */
18+
//env: { account: 'AWS_ACCOUNT', region: 'REGION' },
19+
20+
/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
21+
});

ddbstream-lambda-sfn-cdk-ts/cdk.json

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"app": "npx ts-node --prefer-ts-exts app.ts",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"**/*.d.ts",
11+
"**/*.js",
12+
"tsconfig.json",
13+
"package*.json",
14+
"yarn.lock",
15+
"node_modules",
16+
"test"
17+
]
18+
},
19+
"context": {
20+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
21+
"@aws-cdk/core:checkSecretUsage": true,
22+
"@aws-cdk/core:target-partitions": [
23+
"aws",
24+
"aws-cn"
25+
],
26+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
27+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
28+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
29+
"@aws-cdk/aws-iam:minimizePolicies": true,
30+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
31+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
32+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
33+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
34+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
35+
"@aws-cdk/core:enablePartitionLiterals": true,
36+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
37+
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
38+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
39+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
40+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
41+
"@aws-cdk/aws-route53-patters:useCertificate": true,
42+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
43+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
44+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
45+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
46+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
47+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
48+
"@aws-cdk/aws-redshift:columnId": true
49+
}
50+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
{
2+
"title": "Amazon DynamoDB Stream to AWS Step Functions Trigger",
3+
"description": "Trigger AWS Step Functions workflows in response to changes in DynamoDB tables using a CDK construct that connects DynamoDB and Step Functions.",
4+
"language": "TypeScript",
5+
"level": "300",
6+
"framework": "AWS CDK",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This pattern demonstrates how to automatically trigger AWS Step Functions workflows in response to changes in DynamoDB tables.",
11+
"The CDK construct 'DynamoWorkflowTrigger' connects DynamoDB and Step Functions by allowing you to define event handlers that monitor specific changes in your DynamoDB tables.",
12+
"It leverages Lambda functions to evaluate conditions and start Step Functions state machines with inputs derived from the DynamoDB events.",
13+
"The pattern includes features like dead letter queues, VPC support, custom security groups, and fine-grained event filtering."
14+
]
15+
},
16+
"gitHub": {
17+
"template": {
18+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/ddbstream-lambda-sfn-cdk-ts",
19+
"templateURL": "serverless-patterns/ddbstream-lambda-sfn-cdk-ts",
20+
"projectFolder": "ddbstream-lambda-sfn-cdk-ts",
21+
"templateFile": "lib/ddbstream-lambda-sfn-example-stack.ts"
22+
}
23+
},
24+
"resources": {
25+
"bullets": [
26+
{
27+
"text": "AWS DynamoDB Streams Documentation",
28+
"link": "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html"
29+
},
30+
{
31+
"text": "AWS Step Functions Documentation",
32+
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html"
33+
},
34+
{
35+
"text": "AWS CDK Documentation",
36+
"link": "https://docs.aws.amazon.com/cdk/latest/guide/home.html"
37+
}
38+
]
39+
},
40+
"deploy": {
41+
"text": [
42+
"Clone the repository: <code>git clone https://github.com/aws-samples/serverless-patterns</code>",
43+
"Change directory: <code>cd ddbstream-lambda-sfn-cdk-ts</code>",
44+
"Install dependencies: <code>npm install && npm run lambda</code>",
45+
"Deploy the CDK stack: <code>cdk deploy</code>"
46+
]
47+
},
48+
"testing": {
49+
"text": [
50+
"1. Create an initial item in DynamoDB: <code>aws dynamodb put-item --table-name <table_name> --item '{ \"Index\": {\"S\": \"test-item-1\"}, \"testKey\": {\"S\": \"test9\"}, \"ListAttribute\": {\"L\": [{\"S\": \"first-element\"}]} }'</code>",
51+
"2. Update the item to trigger workflow: <code>aws dynamodb update-item --table-name <table_name> --key '{\"Index\": {\"S\": \"test-item-1\"}}' --update-expression \"SET testKey = :newval\" --expression-attribute-values '{\":newval\": {\"S\": \"test8\"}}'</code>",
52+
"3. Check Step Functions execution: <code>aws stepfunctions list-executions --state-machine-arn <state-machine-arn></code>",
53+
"4. Monitor Lambda logs: <code>aws logs tail /aws/lambda/<lambda-function-name> --follow</code>"
54+
]
55+
},
56+
"cleanup": {
57+
"text": ["Delete the stack: <code>cdk destroy</code>"]
58+
},
59+
"authors": [
60+
{
61+
"name": "Avnish Kumar",
62+
"image": "https://i.postimg.cc/W1SVxLxR/avnish-profile.jpg",
63+
"bio": "Senior Software Engineer, Amazon Web Services",
64+
"linkedin": "avnish-kumar-40a54328"
65+
},
66+
{
67+
"name": "Saptarshi Banerjee",
68+
"bio": "Senior Solutions Architect, Amazon Web Services",
69+
"linkedin": "saptarshi-banerjee-83472679"
70+
}
71+
],
72+
"patternArch": {
73+
"icon1": {
74+
"x": 20,
75+
"y": 50,
76+
"service": "dynamodb",
77+
"label": "Amazon DynamoDB"
78+
},
79+
"icon2": {
80+
"x": 50,
81+
"y": 50,
82+
"service": "lambda",
83+
"label": "AWS Lambda"
84+
},
85+
"icon3": {
86+
"x": 80,
87+
"y": 50,
88+
"service": "sfn",
89+
"label": "AWS Step Function"
90+
},
91+
"line1": {
92+
"from": "icon1",
93+
"to": "icon2",
94+
"label": "DDB Stream"
95+
},
96+
"line2": {
97+
"from": "icon2",
98+
"to": "icon3",
99+
"label": ""
100+
}
101+
}
102+
}
Loading

0 commit comments

Comments
 (0)