Skip to main content

Overview

The SNSTopic construct creates an Amazon SNS topic for pub/sub messaging. Use it to fan out events to multiple subscribers (Lambda, SQS, HTTP endpoints) from a single publish call.

Import

import { SNSTopic } from "@fjall/components-infrastructure/lib/resources/aws/messaging/sns";

Basic Usage

const topic = new SNSTopic(scope, "Alerts", {});

Using the Messaging Factory

The recommended way to add SNS to a Fjall application is through the MessagingFactory:
import { MessagingFactory } from "@fjall/components-infrastructure/lib/patterns/aws/messaging";

const alerts = app.addMessaging(
  MessagingFactory.build("Alerts", {
    type: "topic",
  }),
);

Properties

PropertyTypeDefaultDescription
topicNamestringAuto-generatedTopic name
displayNamestringNoneHuman-readable name for SMS subscriptions
fifobooleanfalseCreate a FIFO topic (strict ordering)
contentBasedDeduplicationbooleantrue (FIFO)Content-based deduplication. Defaults to true on FIFO topics, ignored on standard topics
removalPolicy"DESTROY" | "RETAIN""RETAIN"What happens on stack deletion

Methods

MethodReturnsDescription
getTopicArn()stringTopic ARN
getTopicName()stringTopic name
getTopic()ITopicCDK Topic construct
grantPublish(grantee)GrantGrant permission to publish messages
grantSubscribe(grantee)GrantGrant permission to subscribe to the topic

Examples

Standard Topic

const notifications = app.addMessaging(
  MessagingFactory.build("Notifications", {
    type: "topic",
    displayName: "Order Notifications",
  }),
);

notifications.grantPublish(apiService);

FIFO Topic

FIFO topics deliver messages in order and support deduplication:
const events = app.addMessaging(
  MessagingFactory.build("Events", {
    type: "topic",
    fifo: true,
    contentBasedDeduplication: true,
  }),
);

Fan-Out to Multiple Queues

Combine SNS with SQS for fan-out patterns:
import { SqsSubscription } from "aws-cdk-lib/aws-sns-subscriptions";

const orderTopic = app.addMessaging(
  MessagingFactory.build("OrderEvents", {
    type: "topic",
  }),
);

const billingQueue = app.addMessaging(
  MessagingFactory.build("Billing", {
    type: "queue",
  }),
);

const shippingQueue = app.addMessaging(
  MessagingFactory.build("Shipping", {
    type: "queue",
  }),
);

// Subscribe queues to the topic
orderTopic
  .getTopic()
  .addSubscription(new SqsSubscription(billingQueue.getQueue()));
orderTopic
  .getTopic()
  .addSubscription(new SqsSubscription(shippingQueue.getQueue()));

CloudFormation Outputs

OutputDescription
{id}TopicArnTopic ARN
{id}TopicNameTopic name

Next Steps

Messaging Factory

Create messaging resources via the factory pattern

SQS Queue

Combine with SQS for fan-out patterns