SNS Example in AWS CDK [SQS, Lambda] - Complete Guide

avatar
Borislav Hadzhiev

Last updated: Jan 26, 2024
3 min

banner

# Table of Contents

  1. SNS Topic with Lambda subscription in AWS CDK
  2. SNS Topic with SQS subscription in AWS CDK

# Create an SNS Topic in AWS CDK

We are going to:

  • Create an SNS topic.
  • Subscribe a Lambda function to the SNS topic.
  • Subscribe an SQS queue to the SNS topic.

# SNS Topic with Lambda subscription in AWS CDK

Let's start by creating an SNS topic in CDK, by instantiating the Topic class.

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
import * as lambda from 'aws-cdk-lib/aws-lambda'; import {NodejsFunction} from 'aws-cdk-lib/aws-lambda-nodejs'; import * as sns from 'aws-cdk-lib/aws-sns'; import * as subs from 'aws-cdk-lib/aws-sns-subscriptions'; import * as sqs from 'aws-cdk-lib/aws-sqs'; import * as cdk from 'aws-cdk-lib'; import * as path from 'path'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ create sns topic const topic = new sns.Topic(this, 'sns-topic', { displayName: 'My SNS topic', }); // ๐Ÿ‘‡ create lambda function const myLambda = new NodejsFunction(this, 'my-lambda', { memorySize: 1024, timeout: cdk.Duration.seconds(5), runtime: lambda.Runtime.NODEJS_18_X, handler: 'main', entry: path.join(__dirname, `/../src/my-lambda/index.ts`), }); // ๐Ÿ‘‡ subscribe Lambda to SNS topic topic.addSubscription(new subs.LambdaSubscription(myLambda)); new cdk.CfnOutput(this, 'snsTopicArn', { value: topic.topicArn, description: 'The arn of the SNS topic', }) } }
If you still use CDK version 1, switch to the cdk-v1 branch in the GitHub repository.

Let's go over what we did in the code sample:

  1. We created an SNS topic.
  2. We created a lambda function, for which we'll set up an SNS trigger source.
  3. We subscribed the lambda function to the SNS topic.
  4. We created an Output with the ARN of the SNS topic. We will write the topic ARN to a file, so we can easily test our application via the AWS CLI.

Create the Lambda function at src/my-lambda/index.ts and add the following code to the file.

src/my-lambda/index.ts
import {APIGatewayProxyResultV2, SNSEvent} from 'aws-lambda'; export async function main(event: SNSEvent): Promise<APIGatewayProxyResultV2> { const records = event.Records.map(record => { const {Message, Subject, Type} = record.Sns; return {subject: Subject, message: Message, type: Type}; }); console.log('records: ๐Ÿ‘‰', JSON.stringify(records, null, 2)); return { body: JSON.stringify({records}), statusCode: 2000, }; }

The lambda function simply gathers the SNS records into an object and prints them to the console.

Let's run the deploy command:

shell
npx aws-cdk deploy \ --outputs-file ./cdk-outputs.json

We wrote the SNS topic ARN to a file named cdk-outputs.json in the root directory.

If we take a look at the Triggers section in the Lambda management console, we can see that SNS is configured as a trigger for the function:

sns trigger lambda

The SNS management console also shows the subscription has been set up:

  • the Protocol is set to Lambda
  • the Endpoint is the function's ARN

sns subscription lambda

Let's publish a message to the SNS topic, you can grab your topic ARN from the cdk-outputs.json file in the root directory:

shell
aws sns publish \ --subject "My Subject ๐Ÿš€" \ --message "Hello world ๐ŸŠ" \ --topic-arn "YOUR SNS TOPIC ARN"

If we look at the CloudWatch logs for the Lambda function, we can see that our function has been triggered by SNS:

sns triggered lambda

# SNS Topic with SQS subscription in AWS CDK

Let's subscribe an SQS queue to our SNS topic as well. In order to create the queue we will instantiate the Queue class.

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
import * as sqs from 'aws-cdk-lib/aws-sqs'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props) // ... rest // ๐Ÿ‘‡ create queue const queue = new sqs.Queue(this, 'sqs-queue'); // ๐Ÿ‘‡ subscribe queue to topic topic.addSubscription(new subs.SqsSubscription(queue)); } }

We created an SQS queue and subscribed the queue to our SNS topic.

Let's deploy the changes.

shell
npx aws-cdk deploy \ --outputs-file ./cdk-outputs.json

The SNS management console shows that the SQS subscription has also been set up.

sns subscription sqs

The SQS queue currently has 0 messages available.

sqs queue empty

Let's publish another message to the SNS topic to test the SQS integration.

shell
aws sns publish \ --subject "My Subject ๐Ÿš€" \ --message "Hello world ๐ŸŠ" \ --topic-arn "YOUR SNS TOPIC ARN"

After I've published a message to the SNS topic, the queue has 1 message available.

sqs queue one message

# Clean up

To delete the resources we've provisioned, issue the destroy command.

shell
npx aws-cdk destroy

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev