diff --git a/README.md b/README.md
index f205ee7a2..da198b4ce 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,7 @@ serverless deploy
| [Node SQS Producer Consumer on AWS](https://github.com/serverless/examples/tree/v4/aws-node-sqs-worker)
This template demonstrates how to develop and deploy a simple SQS-based producer-consumer service running on AWS Lambda using the traditional Serverless Framework. | nodeJS |
| [AWS Stripe Integration example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-stripe-integration)
This example for Stripe integration using AWS Lambda and API Gateway. | nodeJS |
| [Simple Telegram bot](https://github.com/serverless/examples/tree/v4/aws-node-telegram-echo-bot)
This is a simple echo bot on Telegram. | nodeJS |
-| [AWS Data Processing example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-text-analysis-via-sns-post-processing)
This example demonstrates how to setup a simple data processing pipeline. | nodeJS |
+| [AWS Data Processing example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-text-analysis-via-sns-post-processing)
This example shows how a Lambda function behind an HTTP API publishes a note to an Amazon SNS topic and a second function subscribed to the topic analyzes it. | nodeJS |
| [AWS Send SMS Message with Twilio example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-twilio-send-text-message)
This example demonstrates how to send SMS messages with the Twilio SDK and AWS lambda. | nodeJS |
| [AWS Apollo Lambda (NodeJS & Typescript)](https://github.com/serverless/examples/tree/v4/aws-node-typescript-apollo-lambda)
This example provides a setup for a Lambda Graphql API with apollo | nodeJS |
| [AWS Kinesis Data Streams Example (NodeJS & Typescript)](https://github.com/serverless/examples/tree/v4/aws-node-typescript-kinesis)
Produce and Consume data on a Kinesis Data Stream with Typescript. | nodeJS |
diff --git a/aws-node-text-analysis-via-sns-post-processing/README.md b/aws-node-text-analysis-via-sns-post-processing/README.md
index 11f9540ce..53e5f1aa1 100644
--- a/aws-node-text-analysis-via-sns-post-processing/README.md
+++ b/aws-node-text-analysis-via-sns-post-processing/README.md
@@ -1,6 +1,6 @@
-# Data processing
-This example demonstrates how to setup a simple data processing pipeline. The service exposes one HTTP endpoint that allows you to add a text note. This HTTP endpoint returns instantly to provide a good user experience while the actual analysis is deferred. Only messages above a certain sentiment level are actually saved.
+# Post-process requests with Amazon SNS and Lambda
-Instead of invoking another Lambda function directly it's considered best practice to store the note as a message in a SNS queue. The queue has certain benefits compared to invoking the `analyzeNote` function directly. The queue supports retries in case the analyzeNote function fails as well as back-off to avoid too many concurrent invocations.
+[](https://github.com/serverless/examples/blob/verified/results.json)
-## Setup
+An HTTP endpoint can answer right away and leave slow work for later: it publishes the request to an Amazon SNS topic, and a second function subscribed to the topic does the work. The [`sns` event](https://www.serverless.com/framework/docs/providers/aws/events/sns) of the Serverless Framework creates the topic, the subscription and the permission that lets SNS invoke the function. This example accepts a text note at `POST /notes`, publishes it to a topic, and has a subscriber function analyze the note and log the result.
-```bash
-npm install
-```
+## What it deploys
-The SNS topic ARN is built automatically at deploy time from your AWS account ID and region (`${aws:accountId}` / `${aws:region}`), so there's no manual configuration needed.
+- An HTTP API with one route, `POST /notes`, and a Lambda function, `addNote`, that publishes each note to the topic.
+- An SNS topic named `text-analysis-sns--notes`.
+- A Lambda function, `analyzeNote`, subscribed to the topic, which counts the words, sentences and characters of each note and logs them.
+- An IAM role that lets the functions write their logs and lets `addNote` publish to this topic only, and a CloudWatch Logs log group for each function.
-# Explanation
+## Prerequisites
-- sns topic will be added by default
+- The Serverless Framework CLI: `npm i -g serverless`, which needs [Node.js](https://nodejs.org/). See [Getting started](https://www.serverless.com/framework/docs/getting-started).
+- An AWS account, with credentials configured on your machine. See [AWS credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials).
+- A Serverless account, or a license key in `SERVERLESS_LICENSE_KEY`. The CLI asks you to sign in the first time you run it.
+- `curl`, to send a note. The commands in Try it are written for Bash.
## Deploy
-In order to deploy the you endpoint simply run
+Deploy from this directory:
```bash
serverless deploy
```
-The expected result should be similar to:
+Without options, the deploy uses the stage `dev` and the Region `us-east-1`. To change them, pass `--stage` or `--region`, and pass the same options to every later command, including `serverless remove`.
-```bash
-Deploying text-analysis-sns to stage dev (us-east-1)
+You should see output like this:
-✔ Service deployed to stack text-analysis-sns-dev (38s)
+```text
+Deploying "text-analysis-sns" to stage "dev" (us-east-1)
+✔ Service deployed to stack text-analysis-sns-dev (83s)
+endpoint: POST - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/notes
-endpoint: POST - https://5cvfn0wwv7.execute-api.us-east-1.amazonaws.com/dev/notes
functions:
- addNote: text-analysis-sns-dev-addNote (1.2 kB)
- analyzeNote: text-analysis-sns-dev-analyzeNote (1.2 kB)
+ addNote: text-analysis-sns-dev-addNote (6.4 kB)
+ analyzeNote: text-analysis-sns-dev-analyzeNote (6.4 kB)
```
-## Usage
+## Try it
-In order to add a note run
+Copy the endpoint from the deploy output into a shell variable:
```bash
-curl -X POST https://XXXXXXXXX.execute-api.us-east-1.amazonaws.com/dev/notes --data '{ "note": "This is such a great Day" }'
+URL=https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/notes
```
-You should see the following output
+Send a note:
```bash
-{"message":"Successfully added the note."}%
+curl -X POST "$URL" -H 'content-type: application/json' \
+ --data '{"note": "Lambda read this note later. The API answered first!"}'
```
-To verify that the note has been processed run
+The API answers with status 202 and the ID of the SNS message, before the note is analyzed:
+
+```json
+{"messageId":"7414c426-1aa6-518d-8d0b-a7a74b40e013"}
+```
+
+SNS invokes `analyzeNote` a moment later. Its log shows the analysis under the same message ID, between the invocation's `START`, `END` and `REPORT` lines:
```bash
serverless logs --function analyzeNote
```
-This command will show you the logged output and looks liked this
+```text
+INFO Analyzed note 7414c426-1aa6-518d-8d0b-a7a74b40e013: 9 words, 2 sentences, 52 characters
+```
+
+If the command prints `No existing streams for the function`, or the line isn't there yet, the function hasn't run yet: wait a few seconds and run the command again. A body without a `note` string gets status 400 and `{"error":"Send a JSON body with a \"note\" string."}`, and nothing is published.
+
+## How it works
+
+The `sns` event in [`serverless.yml`](https://github.com/serverless/examples/blob/v4/aws-node-text-analysis-via-sns-post-processing/serverless.yml) names a topic, so the Framework creates the topic, subscribes `analyzeNote` to it and lets SNS invoke the function. The `addNote` function gets the topic's ARN in an environment variable, and its role may publish to that topic only:
+
+```yaml
+custom:
+ topicName: ${self:service}-${sls:stage}-notes
+ topicArn: arn:aws:sns:${aws:region}:${aws:accountId}:${self:custom.topicName}
+
+provider:
+ iam:
+ role:
+ statements:
+ - Effect: Allow
+ Action:
+ - sns:Publish
+ Resource: ${self:custom.topicArn}
+
+functions:
+ addNote:
+ handler: handler.addNote
+ environment:
+ TOPIC_ARN: ${self:custom.topicArn}
+ events:
+ - httpApi:
+ path: /notes
+ method: post
+
+ analyzeNote:
+ handler: handler.analyzeNote
+ events:
+ - sns:
+ topicName: ${self:custom.topicName}
+```
+
+Topic names are unique per account and Region, so the name includes the stage: two stages get two topics.
+
+[`handler.mjs`](https://github.com/serverless/examples/blob/v4/aws-node-text-analysis-via-sns-post-processing/handler.mjs) holds both functions. `addNote` publishes the note with the AWS SDK for JavaScript v3, which the Node.js runtime includes, and returns the message ID without waiting for the analysis:
+
+```javascript
+const { MessageId } = await sns.send(new PublishCommand({ TopicArn: process.env.TOPIC_ARN, Message: note }));
+return { statusCode: 202, body: JSON.stringify({ messageId: MessageId }) };
+```
+
+SNS invokes `analyzeNote` asynchronously with the message in `event.Records`, and the function reads the text from `Sns.Message`:
+
+```javascript
+for (const record of event.Records) {
+ const { MessageId, Message } = record.Sns;
+ // ...
+ console.log(`Analyzed note ${MessageId}: ${words} words, ${sentences} sentences, ${Message.length} characters`);
+}
+```
+
+Because the topic sits between the two functions, more subscribers (another function, an SQS queue, an email address) can receive the same notes without a change to `addNote`. When `analyzeNote` returns an error, Lambda retries the asynchronous invocation; see [Using Lambda with Amazon SNS](https://docs.aws.amazon.com/lambda/latest/dg/with-sns.html).
+
+## Cost and cleanup
+
+While the example is deployed, API Gateway bills each request to the HTTP API, Amazon SNS bills each published message and its deliveries, Lambda bills each invocation and the functions' compute time, and CloudWatch Logs bills the functions' stored log data. See [API Gateway pricing](https://aws.amazon.com/api-gateway/pricing/), [Amazon SNS pricing](https://aws.amazon.com/sns/pricing/), [Lambda pricing](https://aws.amazon.com/lambda/pricing/) and [CloudWatch pricing](https://aws.amazon.com/cloudwatch/pricing/).
+
+Remove the API, the topic, the functions and their log groups:
```bash
-START RequestId: 75a970ba-ab11e6-809d-435833490828 Version: $LATEST
-2026-07-15T17:56:32.497Z 75a970ba-ab11e6-809d-435833490828 Positive note - will be published: This is such a great Day
-END RequestId: 75a970ba-ab11e6-809d-435833490828
-REPORT RequestId: 75a970ba-ab11e6-809d-435833490828 Duration: 3.45 ms Billed Duration: 100 ms Memory Size: 1024 MB Max Memory Used: 15 MB
+serverless remove
```
-You can play with the system and see which notes will be published and which won't.
+## Next steps
+
+- Read [SNS topic events](https://www.serverless.com/framework/docs/providers/aws/events/sns) for subscribing to an existing topic, filter policies that send each function only some messages, and a dead-letter queue for messages SNS can't deliver.
+- Send the notes to a queue instead, so a worker reads them in batches at its own pace, as the [SQS worker example](https://github.com/serverless/examples/tree/v4/aws-node-sqs-worker) does.
+- Store each analysis in a table, as the [HTTP API with DynamoDB example](https://github.com/serverless/examples/tree/v4/aws-node-http-api-dynamodb) does for API requests.
diff --git a/aws-node-text-analysis-via-sns-post-processing/addNote.js b/aws-node-text-analysis-via-sns-post-processing/addNote.js
deleted file mode 100644
index 9d6ea9337..000000000
--- a/aws-node-text-analysis-via-sns-post-processing/addNote.js
+++ /dev/null
@@ -1,36 +0,0 @@
-import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
-
-const sns = new SNSClient({});
-
-export const addNote = async (event) => {
- const data = JSON.parse(event.body);
- if (typeof data.note !== 'string') {
- console.error('Validation Failed');
- return {
- statusCode: 400,
- headers: { 'Content-Type': 'text/plain' },
- body: "Couldn't add the note.",
- };
- }
-
- try {
- await sns.send(
- new PublishCommand({
- Message: data.note,
- TopicArn: process.env.SNS_TOPIC_ARN,
- })
- );
- } catch (error) {
- console.error(error);
- return {
- statusCode: 501,
- headers: { 'Content-Type': 'text/plain' },
- body: "Couldn't add the note due an internal error. Please try again later.",
- };
- }
-
- return {
- statusCode: 200,
- body: JSON.stringify({ message: 'Successfully added the note.' }),
- };
-};
diff --git a/aws-node-text-analysis-via-sns-post-processing/analyzeNote.js b/aws-node-text-analysis-via-sns-post-processing/analyzeNote.js
deleted file mode 100644
index 8c30b3b80..000000000
--- a/aws-node-text-analysis-via-sns-post-processing/analyzeNote.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import Sentiment from 'sentiment';
-
-const sentiment = new Sentiment();
-
-export const analyzeNote = (event) => {
- const note = event.Records[0].Sns.Message;
- const result = sentiment.analyze(note);
- if (result.score > 2) {
- console.log(`Positive note - will be published: ${note}`);
- } else {
- console.log(`Negative note - won't be published: ${note}`);
- }
-};
diff --git a/aws-node-text-analysis-via-sns-post-processing/example.json b/aws-node-text-analysis-via-sns-post-processing/example.json
new file mode 100644
index 000000000..b43d6c2ff
--- /dev/null
+++ b/aws-node-text-analysis-via-sns-post-processing/example.json
@@ -0,0 +1,30 @@
+{
+ "title": "AWS Data Processing example in NodeJS",
+ "description": "This example shows how a Lambda function behind an HTTP API publishes a note to an Amazon SNS topic and a second function subscribed to the topic analyzes it.",
+ "language": "node",
+ "platform": "AWS",
+ "framework": "v4",
+ "priority": 10,
+ "author": {
+ "name": "Adam Bergman",
+ "link": "https://github.com/adambrgmn",
+ "avatar": "https://avatars1.githubusercontent.com/u/13746650?v=4&s=140"
+ },
+ "services": [
+ "lambda",
+ "apigateway",
+ "sns",
+ "iam",
+ "logs"
+ ],
+ "test": {
+ "tier": "fast",
+ "checks": [
+ {
+ "script": {
+ "path": "test/smoke.mjs"
+ }
+ }
+ ]
+ }
+}
diff --git a/aws-node-text-analysis-via-sns-post-processing/handler.mjs b/aws-node-text-analysis-via-sns-post-processing/handler.mjs
new file mode 100644
index 000000000..7461440ec
--- /dev/null
+++ b/aws-node-text-analysis-via-sns-post-processing/handler.mjs
@@ -0,0 +1,32 @@
+import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
+
+const sns = new SNSClient();
+
+// POST /notes with {"note": "..."}: publishes the note to the topic and answers
+// right away. The analysis happens later, in analyzeNote.
+export const addNote = async (event) => {
+ let note;
+ try {
+ const body = event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString('utf8') : event.body;
+ note = JSON.parse(body ?? '').note;
+ } catch {
+ // Not JSON: answered below.
+ }
+ if (typeof note !== 'string' || note.trim() === '') {
+ return { statusCode: 400, body: JSON.stringify({ error: 'Send a JSON body with a "note" string.' }) };
+ }
+
+ const { MessageId } = await sns.send(new PublishCommand({ TopicArn: process.env.TOPIC_ARN, Message: note }));
+ console.log(`Published note ${MessageId}`);
+ return { statusCode: 202, body: JSON.stringify({ messageId: MessageId }) };
+};
+
+// Invoked by SNS for every message published to the topic.
+export const analyzeNote = async (event) => {
+ for (const record of event.Records) {
+ const { MessageId, Message } = record.Sns;
+ const words = Message.split(/\s+/).filter(Boolean).length;
+ const sentences = Message.split(/[.!?]+/).filter((s) => s.trim() !== '').length;
+ console.log(`Analyzed note ${MessageId}: ${words} words, ${sentences} sentences, ${Message.length} characters`);
+ }
+};
diff --git a/aws-node-text-analysis-via-sns-post-processing/package.json b/aws-node-text-analysis-via-sns-post-processing/package.json
deleted file mode 100644
index bc870a583..000000000
--- a/aws-node-text-analysis-via-sns-post-processing/package.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "name": "aws-text-analysis-via-sns-post-processing",
- "version": "1.0.0",
- "type": "module",
- "description": "Example demonstrates how to setup a simple data processing pipeline",
- "author": "",
- "license": "MIT",
- "dependencies": {
- "@aws-sdk/client-sns": "^3.700.0",
- "sentiment": "^5.0.2"
- }
-}
diff --git a/aws-node-text-analysis-via-sns-post-processing/serverless.yml b/aws-node-text-analysis-via-sns-post-processing/serverless.yml
index 0835f63ce..445102225 100644
--- a/aws-node-text-analysis-via-sns-post-processing/serverless.yml
+++ b/aws-node-text-analysis-via-sns-post-processing/serverless.yml
@@ -2,32 +2,37 @@ service: text-analysis-sns
frameworkVersion: '4'
+custom:
+ # The stage in the name lets two stages of this service share an account.
+ topicName: ${self:service}-${sls:stage}-notes
+ topicArn: arn:aws:sns:${aws:region}:${aws:accountId}:${self:custom.topicName}
+
provider:
name: aws
runtime: nodejs24.x
architecture: arm64
- region: us-east-1
- stage: dev
- environment:
- SNS_TOPIC_ARN: arn:aws:sns:${aws:region}:${aws:accountId}:analyzeNote
iam:
role:
statements:
+ # addNote may publish to this service's topic and nothing else.
- Effect: Allow
- Resource: ${self:provider.environment.SNS_TOPIC_ARN}
Action:
- sns:Publish
+ Resource: ${self:custom.topicArn}
functions:
addNote:
- handler: addNote.addNote
+ handler: handler.addNote
+ environment:
+ TOPIC_ARN: ${self:custom.topicArn}
events:
- - http:
- path: notes
+ - httpApi:
+ path: /notes
method: post
- cors: true
analyzeNote:
- handler: analyzeNote.analyzeNote
+ handler: handler.analyzeNote
events:
- - sns: analyzeNote
+ # Creates the topic and subscribes this function to it.
+ - sns:
+ topicName: ${self:custom.topicName}
diff --git a/aws-node-text-analysis-via-sns-post-processing/test/smoke.mjs b/aws-node-text-analysis-via-sns-post-processing/test/smoke.mjs
new file mode 100644
index 000000000..439ee955d
--- /dev/null
+++ b/aws-node-text-analysis-via-sns-post-processing/test/smoke.mjs
@@ -0,0 +1,87 @@
+// Does what the README's Try it does: posts a note to the HTTP API, which
+// publishes it to the SNS topic, then waits for the analyzeNote function's log
+// line for that message and checks the analysis it logged.
+//
+// Run by the example test runner, with the stack outputs in EXAMPLE_OUTPUTS,
+// EXAMPLE_REGION set and AWS credentials in the environment. It reads the
+// analyzeNote function's log group with the aws CLI (logs filter-log-events).
+
+import { execFileSync } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
+
+const WAIT_MS = 90_000;
+const DELAY_MS = 3_000;
+
+const outputs = JSON.parse(process.env.EXAMPLE_OUTPUTS ?? '{}');
+const apiUrl = outputs.HttpApiUrl;
+const functionArn = outputs.AnalyzeNoteLambdaFunctionQualifiedArn;
+if (!apiUrl || !functionArn) {
+ fail(`stack outputs HttpApiUrl and AnalyzeNoteLambdaFunctionQualifiedArn needed; got ${Object.keys(outputs).join(', ')}`);
+}
+// arn:aws:lambda:::function::
+const logGroup = `/aws/lambda/${functionArn.split(':')[6]}`;
+const region = ['--region', process.env.EXAMPLE_REGION ?? 'us-east-1'];
+
+const tag = randomBytes(4).toString('hex');
+const note = `Smoke test note ${tag} arrived. It has two sentences!`;
+const expected = '9 words, 2 sentences, 55 characters';
+
+// A new HTTP API can take a moment to answer, so the first request retries.
+const start = Date.now();
+let res;
+let text;
+for (;;) {
+ try {
+ res = await fetch(`${apiUrl}/notes`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ note }),
+ });
+ text = await res.text();
+ if (res.status === 202) break;
+ } catch (err) {
+ text = `request error: ${err.message}`;
+ }
+ if (Date.now() - start >= WAIT_MS) fail(`POST /notes: expected status 202; last: ${res?.status} ${text.slice(0, 300)}`);
+ await sleep(DELAY_MS);
+}
+const { messageId } = JSON.parse(text);
+if (!messageId) fail(`POST /notes: expected a messageId; got ${text.slice(0, 300)}`);
+
+// SNS invokes analyzeNote asynchronously, so its log line appears after a moment.
+const wanted = `Analyzed note ${messageId}:`;
+let line;
+for (;;) {
+ try {
+ const out = aws(['logs', 'filter-log-events', ...region, '--log-group-name', logGroup,
+ '--filter-pattern', `"${messageId}"`, '--start-time', String(start - 60_000), '--output', 'json']);
+ line = JSON.parse(out).events.map((e) => e.message).find((m) => m.includes(wanted));
+ } catch (err) {
+ // The log group exists only after the first invocation.
+ line = undefined;
+ text = err.message;
+ }
+ if (line) break;
+ if (Date.now() - start >= 2 * WAIT_MS) fail(`${logGroup}: no "${wanted}" line within ${(2 * WAIT_MS) / 1000} s; last: ${text.slice(0, 300)}`);
+ await sleep(DELAY_MS);
+}
+
+if (!line.includes(`${wanted} ${expected}`)) fail(`${logGroup}: expected "${wanted} ${expected}"; got "${line.trim()}"`);
+console.log(`POST /notes -> SNS message ${messageId} -> analyzeNote logged "${expected}"`);
+
+function aws(args) {
+ try {
+ return execFileSync('aws', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (err) {
+ throw new Error(`aws ${args.slice(0, 2).join(' ')}: exit ${err.status}, ${String(err.stderr ?? '').trim().slice(0, 300)}`);
+ }
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function fail(message) {
+ console.error(`smoke test failed: ${message}`);
+ process.exit(1);
+}
diff --git a/examples.json b/examples.json
index 81996ef9d..13f3f9f4f 100644
--- a/examples.json
+++ b/examples.json
@@ -798,14 +798,15 @@
{
"title": "AWS Data Processing example in NodeJS",
"name": "aws-node-text-analysis-via-sns-post-processing",
- "description": "This example demonstrates how to setup a simple data processing pipeline.",
+ "description": "This example shows how a Lambda function behind an HTTP API publishes a note to an Amazon SNS topic and a second function subscribed to the topic analyzes it.",
"githubUrl": "https://github.com/serverless/examples/tree/v4/aws-node-text-analysis-via-sns-post-processing",
"framework": "v4",
"language": "node",
"platform": "aws",
"authorLink": "https://github.com/adambrgmn",
"authorName": "Adam Bergman",
- "authorAvatar": "https://avatars1.githubusercontent.com/u/13746650?v=4&s=140"
+ "authorAvatar": "https://avatars1.githubusercontent.com/u/13746650?v=4&s=140",
+ "priority": 10
},
{
"title": "AWS Send SMS Message with Twilio example in NodeJS",