How to Use AWS SNS with Lambda: Simple Integration Guide
To use
AWS SNS with Lambda, create an SNS topic and subscribe your Lambda function to it. When a message is published to the SNS topic, it automatically triggers the Lambda function to run.Syntax
To connect SNS with Lambda, you need to create an SNS topic, a Lambda function, and then subscribe the Lambda function to the SNS topic. The subscription uses the Lambda function's ARN (Amazon Resource Name).
When SNS receives a message, it sends an event to the Lambda function, which processes the message.
bash
aws sns create-topic --name MyTopic aws lambda create-function --function-name MyFunction --runtime python3.9 --role <role-arn> --handler lambda_function.lambda_handler --zip-file fileb://function.zip aws sns subscribe --topic-arn <topic-arn> --protocol lambda --notification-endpoint <lambda-function-arn> aws lambda add-permission --function-name MyFunction --statement-id sns-invoke --action lambda:InvokeFunction --principal sns.amazonaws.com --source-arn <topic-arn>
Example
This example shows a simple Python Lambda function triggered by SNS. It logs the SNS message content.
python
import json def lambda_handler(event, context): for record in event['Records']: sns_message = record['Sns']['Message'] print(f"Received SNS message: {sns_message}") return {'statusCode': 200, 'body': json.dumps('Success')}
Output
Received SNS message: Hello from SNS!
Common Pitfalls
- Not adding permission for SNS to invoke Lambda causes invocation failures.
- Using wrong Lambda ARN or SNS topic ARN in subscription leads to errors.
- Lambda function timeout too short to process messages can cause retries.
- Not handling the SNS event structure correctly in Lambda code causes runtime errors.
bash
aws sns subscribe --topic-arn <topic-arn> --protocol lambda --notification-endpoint <wrong-lambda-arn> # Correct way: aws sns subscribe --topic-arn <topic-arn> --protocol lambda --notification-endpoint <correct-lambda-arn>
Quick Reference
| Step | Description |
|---|---|
| Create SNS Topic | Use AWS CLI or Console to create a topic. |
| Create Lambda Function | Write and deploy your Lambda code. |
| Subscribe Lambda to SNS | Subscribe Lambda ARN to SNS topic. |
| Add Permission | Allow SNS to invoke Lambda function. |
| Publish Message | Send message to SNS to trigger Lambda. |
Key Takeaways
Subscribe your Lambda function to an SNS topic to trigger it on message publish.
Always add permission for SNS to invoke your Lambda function.
Handle the SNS event format properly inside your Lambda code.
Use correct ARNs when subscribing Lambda to SNS.
Test by publishing messages to the SNS topic and checking Lambda logs.