Skip to content

Resources / Messaging

SNS topic

An sns-topic is an Amazon SNS topic: you publish a message once and every subscriber gets its own copy. Use it when one event needs several independent reactions, such as an order that triggers a receipt, an inventory update and analytics. A standard topic costs $0.50 per million publishes in US East after the first million each month, and delivery to Lambda and SQS is free.

SNS doesn't store messages. With one consumer, an SQS queue is simpler and keeps messages until they're processed. To route on fields inside the message, use an event bus.

Basic example

A topic needs no properties. Subscribers are Lambda functions with an SNS event:

TypeScript
export default defineConfig(() => {  const orderEvents = new SnsTopic({});  const sendReceipt = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/send-receipt.ts' }),    events: [{ type: 'sns', properties: { snsTopicName: 'orderEvents' } }]  });  const recordAnalytics = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/record-analytics.ts' }),    events: [{ type: 'sns', properties: { snsTopicName: 'orderEvents' } }]  });  return {    resources: { orderEvents, sendReceipt, recordAnalytics }  };});

Each published message runs both functions. Filters, retries and the event shape are on SNS events.

Publish messages

connectTo gives a workload permission to publish and injects the topic's ARN and NAME:

TypeScript
const api = new LambdaFunction({  packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/api.ts' }),  connectTo: [orderEvents]});
TypeScript
import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';const sns = new SNSClient({});await sns.send(  new PublishCommand({    TopicArn: process.env.STP_ORDER_EVENTS_ARN,    Message: JSON.stringify({ type: 'order-placed', orderId: '456' })  }));

For a topic named orderEvents, the variables are STP_ORDER_EVENTS_ARN and STP_ORDER_EVENTS_NAME. Containers publish the same way. See Connecting resources.

A message can be up to 256 KB. For a larger payload, upload the data to an S3 bucket and publish the object key.

Fan out to SQS queues

A Lambda subscriber loses a message after Lambda's retries run out. When each consumer needs a buffer, its own retries and a dead-letter queue, subscribe an SQS queue per consumer. Stacktape has no property for this subscription, so add it as a raw CloudFormation resource, and allow the topic to send to the queue:

TypeScript
export default defineConfig(() => {  const orderEvents = new SnsTopic({});  const billingQueue = new SqsQueue({    policyStatements: [      {        Effect: 'Allow',        Principal: { Service: 'sns.amazonaws.com' },        Action: ['sqs:SendMessage'],        Condition: { ArnEquals: { 'aws:SourceArn': $ResourceParam('orderEvents', 'arn') } }      }    ]  });  return {    resources: { orderEvents, billingQueue },    cloudformationResources: {      BillingQueueSubscription: {        Type: 'AWS::SNS::Subscription',        Properties: {          TopicArn: $ResourceParam('orderEvents', 'arn'),          Protocol: 'sqs',          Endpoint: $ResourceParam('billingQueue', 'arn'),          RawMessageDelivery: true        }      }    }  };});

RawMessageDelivery: true puts the published message in the SQS body as is, without the SNS envelope. Consume each queue with an SQS event or a worker.

Standard or FIFO

StandardFIFO
OrderBest effortKept within each message group
DuplicatesA message is sometimes delivered twiceDuplicate publishes within 5 minutes are dropped
SubscribersLambda, SQS, HTTP, email, SMSSQS queues only
ThroughputPractically unlimitedLimited per topic, see the AWS quotas

A standard topic bills per publish, and each 64 KB of a message counts as one. Delivery to Lambda and SQS is free; HTTP, email and SMS deliveries are charged. A FIFO topic bills per published and delivered message and per GB of payload, so each extra subscriber adds cost. See SNS pricing.

Use a standard topic unless the order matters. fifoEnabled: true creates a FIFO topic. Each publish then needs a MessageGroupId and a deduplication ID, or set contentBasedDeduplication: true to use a hash of the body.

TypeScript
new SnsTopic({ fifoEnabled: true, contentBasedDeduplication: true })

A FIFO topic can't invoke Lambda. Subscribe FIFO queues and consume them with SQS events to keep the order. It can also deliver to standard queues, but those don't keep the order or drop duplicates.

SMS sender name

smsDisplayName (up to 11 characters) is the sender name on SMS messages sent through the topic. SMS has its own price per message by country, and new AWS accounts start in an SMS sandbox that only sends to verified numbers.

Configuration reference

SnsTopicProps3 properties
  • contentBasedDeduplicationbooleanDefault false

    Automatically deduplicates messages based on content (SHA-256 hash) within a 5-minute window.

  • fifoEnabledbooleanDefault false

    Guarantees message order and exactly-once delivery. Use for financial transactions, sequential workflows.

  • Sender name shown on SMS messages sent to subscribers (e.g., "MyApp"). Max 11 characters.

Referenceable parameters

Reference these parameters with the $ResourceParam directive: $ResourceParam('<resource-name>', '<parameter>'). See referenceable parameters.

Next steps

  • SNS events: subscribe functions, filter messages and handle failures.
  • SQS queue: buffer messages for one consumer.
  • Event bus: route events by their content.