SNS
Process SNS notifications in a Lambda subscribed to an SNS topic.
AWS documentation
What AWS sends
event.Records is an array of SNS records. Each record has EventSource: 'aws:sns' and Sns with Message (always a string, often JSON), MessageAttributes, Subject, Timestamp, TopicArn, and MessageId.
SNS typically delivers one record per Lambda invocation, but the schema is still an array - always iterate.
Recommended middlewares
| Middleware | Why |
|---|---|
@middy/event-normalizer | Parse Message as JSON, unwrap S3-via-SNS envelopes |
Example
import middy from '@middy/core'
import eventNormalizer from '@middy/event-normalizer'
const lambdaHandler = async (event, context, { signal }) => {
for (const record of event.Records) {
// record.Sns.Message is now parsed if it was JSON
const payload = record.Sns.Message
// ...
}
}
export const handler = middy()
.use(eventNormalizer())
.handler(lambdaHandler) Common gotchas
Sns.Messageis always a string. If you publish JSON, you have toJSON.parse(record.Sns.Message)or useeventNormalizer.- No partial-batch support. SNS-to-Lambda is fire-and-forget per record. For retry semantics, fan out via SQS (SNS -> SQS -> Lambda) and use the SQS event page.
- DLQ vs on-failure destination. Configure a DLQ or an
OnFailuredestination on the Lambda function for failed invocations; SNS itself does not redeliver. - Message size. SNS has a 256 KB message limit; use the Extended Client Library if you need larger.
Related
Last updated: