Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions lambda-durable-webhook-sam-nodejs/README.md
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please align your README.md with the one listed here: https://github.com/aws-samples/serverless-patterns/tree/main/_pattern-model

  • Order of items
  • How It Works, Webhook Processing Workflow (3 Steps), Key Features can be condensed in one item
  • Required IAM Permissions - can be removed
  • Components section can be removed entirely
  • API Endpoints, Monitoring, Error Handling, Cost Optimization, Security Considerations, NodeJS Implementation Notes can be removed
  • Learn More can be integrated into the first description using Links to the docs
  • The README does not mention that deployed resources may incur AWS charges. While the pattern uses pay-per-use services, a cost warning helps users understand they should clean up after testing.
  • The README does not mention that deployed resources may incur AWS charges. While the pattern uses pay-per-use services, a cost warning helps users understand they should clean up after testing.

If you like, you

  • can add numbers to your architecture diagram and move/re-use content blocks (please as short/crisp as possible) to the architecture diagram (below) in a written form.

Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Webhook Receiver with AWS Lambda durable functions - NodeJS

This serverless pattern demonstrates a serverless webhook receiver using AWS Lambda durable functions with NodeJS. The pattern receives webhook events via API Gateway, processes them durably with automatic checkpointing, and provides status query capabilities.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/testing/patterns/lambda-durable-webhook-sam-nodejs

To Learn more about Lambda durable functions:
- [AWS Lambda durable functions Documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html)
- [Lambda durable functions Best Practices](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions-best-practices.html)

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.

## Requirements

* [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.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed

## How It Works

This pattern demonstrates a serverless webhook receiver using AWS Lambda durable functions. The pattern receives webhook events via API Gateway, processes them durably with automatic checkpointing, and provides status query capabilities. The durable function processes webhooks in 3 checkpointed steps:

1. **Validate** - Verify webhook payload and structure
2. **Process** - Execute business logic on webhook data
3. **Finalize** - Complete processing and update final status

This pattern acheives the following key features:

- ✅ **Automatic Checkpointing** - Each processing step is checkpointed automatically
- ✅ **Failure Recovery** - Resumes from last checkpoint on failure
- ✅ **Asynchronous Processing** - Immediate 202 response, processing in background
- ✅ **State Persistence** - Execution state stored in DynamoDB with TTL
- ✅ **Status Query API** - Real-time status tracking via REST API

## Important

⚠️ **Important:** Please check the [AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html) for regions currently supported by AWS Lambda durable functions.

## Deployment

1. **Build the application**:
```bash
sam build
```

2. **Deploy to AWS**:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please note required inputs WebhookSecret

Plese enter required `WebhookSecret`

```bash
sam deploy --guided
```

Note the outputs after deployment:
- `WebhookApiUrl`: Use this for sending webhook POST requests
- `StatusQueryApiUrl`: Use this for querying execution status

## Testing
To test the set-up, utilize the below curl command by replacing the WebhookApiUrl copied from the above step:

```bash
# Send a test webhook
curl -X POST <WebhookApiUrl> \
-H "Content-Type: application/json" \
-d '{
"type": "order",
"orderId": "123456",
"data": {"amount": 100}
}'
```

Once the Webhook is submitted, to query the status of webhook, use the following curl command by replacing the StatusQueryApiUrl:

```bash
# Get execution status (use executionToken from webhook response)
curl <StatusQueryApiUrl>
```

**Success indicators:**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please ad a way testing the failure handling & timeout (set to a low limit) as it is described as a key capability of the sample

- Webhook returns 202 with `executionToken`
- Status query shows progression: `STARTED` → `VALIDATING` → `PROCESSING` → `COMPLETED`
- Execution state persists in DynamoDB with TTL

To simulate a failure scenario, perform the below curl command:

## Architecture

![Architecture Diagram](architecture.png)


## Cleanup

```bash
sam delete
```
----
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
70 changes: 70 additions & 0 deletions lambda-durable-webhook-sam-nodejs/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"title": "Webhook Receiver with AWS Lambda durable functions - NodeJS",
"description": "This serverless pattern demonstrates building a webhook receiver using AWS Lambda durable functions with automatic checkpointing and fault tolerance, implemented in Node.js",
"language": "Node.js",
"level": "200",
"framework": "AWS SAM",
"services": ["apigateway","lambda", "dynamoDB"],
"introBox": {
"headline": "How it works",
"text": [
"This pattern demonstrates a serverless webhook receiver using AWS Lambda durable functions. When a webhook POST request arrives via API Gateway, it triggers a durable function that processes the webhook in 3 checkpointed steps: Validate → Process → Finalize. Each step is automatically checkpointed, allowing the workflow to resume from the last successful step if interrupted. The pattern provides immediate 202 response while processing continues in the background, stores execution state in DynamoDB with TTL, and offers real-time status tracking via a REST API."
]
},
"testing": {
"headline": "Testing",
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"headline": "Cleanup",
"text": [
"Delete the stack: <code>sam delete</code>."
]
},
"deploy": {
"text": [
"sam build",
"sam deploy --guided"
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-webhook-sam-nodejs",
"templateURL":"serverless-patterns/lambda-durable-webhook-sam-nodejs",
"templateFile": "template.yaml",
"projectFolder": "lambda-durable-webhook-sam-nodejs"
}
},
"resources": {
"headline": "Additional resources",
"bullets": [
{
"text": "AWS Lambda durable functions Documentation",
"link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html"
},
{
"text": "Event Source Mappings with Lambda durable functions",
"link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-invoking-esm.html"
},
{
"text": "Lambda durable functions Best Practices",
"link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions-best-practices.html"
},
{
"text": "Node.js AWS SDK Documentation",
"link": "https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/"
}
]
},
"authors": [
{
"name": "Sahithi Ginjupalli",
"image": "https://drive.google.com/file/d/1YcKYuGz3LfzSxiwb2lWJfpyi49SbvOSr/view?usp=sharing",
"bio": "Cloud Engineer at AWS with a passion for diving deep into cloud and AI services to build innovative serverless applications.",
"linkedin": "ginjupalli-sahithi-37460a18b",
"twitter": ""
}
]
}
100 changes: 100 additions & 0 deletions lambda-durable-webhook-sam-nodejs/src/status_query/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb');

// Initialize AWS clients
const dynamodbClient = new DynamoDBClient({});
const dynamodb = DynamoDBDocumentClient.from(dynamodbClient);

/**
* Status query function for webhook processing
* Allows real-time status tracking via REST API
*/
exports.handler = async (event, context) => {
const executionToken = event.pathParameters?.executionToken;
const eventsTableName = process.env.EVENTS_TABLE_NAME;

console.log(`Querying status for execution token: ${executionToken}`);

if (!executionToken) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'Missing executionToken parameter'
})
};
}

try {
// Query execution state from DynamoDB
const result = await dynamodb.send(new GetCommand({
TableName: eventsTableName,
Key: { executionToken }
}));

if (!result.Item) {
return {
statusCode: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'Execution token not found',
executionToken: executionToken
})
};
}

// Format response based on current status
const execution = result.Item;
const response = {
executionToken: executionToken,
status: execution.status,
timestamp: execution.timestamp,
currentStep: execution.currentStep || 'unknown'
};

// Add additional fields based on status
if (execution.status === 'COMPLETED') {
response.result = execution.result;
response.completedAt = execution.completedAt;
}

if (execution.status === 'FAILED') {
response.error = execution.error;
}

if (execution.payload) {
response.originalPayload = execution.payload;
}

return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(response)
};

} catch (error) {
console.error(`Error querying status for ${executionToken}:`, error.message);

return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'Failed to query execution status',
executionToken: executionToken,
message: error.message
})
};
}
};
15 changes: 15 additions & 0 deletions lambda-durable-webhook-sam-nodejs/src/status_query/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "status-query-function",
"version": "1.0.0",
"description": "Status query function for webhook processing",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@aws-sdk/client-dynamodb": "^3.700.0",
"@aws-sdk/lib-dynamodb": "^3.700.0"
},
"author": "",
"license": "MIT"
}
Loading