Publishing to SNS with the AWS SDK v3, message attributes and filtering, FIFO topics, batch publishing, fanning out to SQS with raw delivery, verifying HTTPS subscriptions, and a typed Pub/Sub alternative that provisions SNS and SQS in your own AWS account.

Amazon SNS is the AWS service you publish to when one event has to reach several consumers, such as an order that triggers a receipt and a warehouse pick. Publishing from Node.js takes a few lines with the AWS SDK v3.
Most bugs come from the wiring instead, since each consumer needs its own SQS queue, queue policy and subscription. This guide covers publishing, attributes, FIFO and batching, the fan-out setup, and a typed alternative.
Install the SNS client from the modular AWS SDK for JavaScript v3 and create one client per process, so connections are reused across requests:
// publish.ts
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";
const sns = new SNSClient({ region: process.env.AWS_REGION ?? "eu-west-1" });
const topicArn = process.env.ORDER_EVENTS_TOPIC_ARN!;
export async function publishOrderPlaced(order: { id: string; totalCents: number; country: string }) {
const result = await sns.send(
new PublishCommand({
TopicArn: topicArn,
Message: JSON.stringify({ type: "order.placed", orderId: order.id, totalCents: order.totalCents }),
MessageAttributes: {
eventType: { DataType: "String", StringValue: "order.placed" },
country: { DataType: "String", StringValue: order.country },
},
}),
);
return result.MessageId;
}
The SDK resolves credentials from the default provider chain, which picks up the task role on ECS, the execution role on Lambda and your profile locally, so the code should never carry access keys. The caller needs sns:Publish on the topic ARN, and if the topic uses a customer managed KMS key, kms:GenerateDataKey and kms:Decrypt on that key too.
Message attributes travel next to the body, and subscriptions can carry a filter policy that matches on them, so a subscriber only receives what it asks for. A queue that should only see German orders gets this policy on its subscription:
{
"eventType": ["order.placed"],
"country": ["DE"]
}
Filter policies can also match on the message body when the subscription's FilterPolicyScope is MessageBody. Filtering in SNS is cheaper than delivering everything and discarding in the consumer, and it keeps the filter visible in one place instead of spread across handlers.
FIFO topics, whose names end in .fifo, keep order within a message group and drop duplicates for five minutes. Every publish needs a MessageGroupId, and a MessageDeduplicationId unless the topic has content-based deduplication on. Use the entity ID as the group, so updates to one order stay ordered while different orders process in parallel.
To cut API calls, PublishBatchCommand sends up to 10 messages per request and reports success or failure per entry, so the code has to check Failed and retry those entries rather than assuming the whole batch worked, as the PublishBatch reference describes.
Message size is the other limit to plan for: the SNS quotas page puts the default at 256 KiB, adjustable up to 1 MiB per topic, so large payloads belong in S3 with the object key in the message.
SNS pushes and does not store messages for later, so durable consumers almost always read from an SQS queue subscribed to the topic. Each consumer needs three pieces:
maxReceiveCount on the main queue's redrive policy.sns.amazonaws.com call sqs:SendMessage, with an aws:SourceArn condition naming the topic.sqs and RawMessageDelivery set to true, so consumers get the original message body instead of the SNS JSON envelope, as the raw message delivery docs explain.Miss the queue policy and SNS reports successful publishes while nothing arrives, which is the most common fan-out bug. The consumer then polls with ReceiveMessageCommand, processes, and deletes each message, and because delivery is at least once, it has to treat a second copy of the same orderId as a no-op.
For an HTTPS endpoint, SNS first posts a SubscriptionConfirmation message with a SubscribeURL you must call, then posts each notification as JSON. Verify every message's signature against the certificate at SigningCertURL, and check that the URL is on an amazonaws.com SNS host before fetching it, following the signature verification guide. HTTPS delivery retries on failure but has no queue behind it, so a slow or offline endpoint loses messages once the retry policy runs out unless the subscription has its own dead-letter queue.
Encore brings infrastructure from code, so a topic and its subscribers are typed TypeScript declarations, and on AWS Encore provisions them as an SNS topic with an SQS queue per subscription in your own account, including the subscriptions and dead-letter queues from the previous section. The example publishes OrderPlaced from an orders service and creates a pick list in a warehouse service.
Run in your terminal to get started locally.
The topic lives in the orders service, typed with the event shape, so a publisher that forgets a field fails to compile:
// orders/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("orders");
// orders/orders.ts
import { api } from "encore.dev/api";
import { Topic } from "encore.dev/pubsub";
export interface OrderPlaced {
orderId: string;
skus: string[];
totalCents: number;
}
export const orderPlaced = new Topic<OrderPlaced>("order-placed", {
deliveryGuarantee: "at-least-once",
});
interface PlaceOrderParams {
orderId: string;
skus: string[];
totalCents: number;
}
export const placeOrder = api(
{ expose: true, method: "POST", path: "/orders" },
async (p: PlaceOrderParams): Promise<{ messageId: string }> => {
const messageId = await orderPlaced.publish({
orderId: p.orderId,
skus: p.skus,
totalCents: p.totalCents,
});
return { messageId };
},
);
The warehouse service subscribes and writes the pick list with ON CONFLICT DO NOTHING, so a redelivered message cannot create a second one:
-- warehouse/migrations/1_pick_lists.up.sql
CREATE TABLE pick_lists (
order_id TEXT PRIMARY KEY,
skus TEXT[] NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// warehouse/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("warehouse");
// warehouse/picks.ts
import { Subscription } from "encore.dev/pubsub";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { orderPlaced } from "../orders/orders";
const db = new SQLDatabase("warehouse", { migrations: "./migrations" });
new Subscription(orderPlaced, "create-pick-list", {
handler: async (event) => {
await db.exec`
INSERT INTO pick_lists (order_id, skus)
VALUES (${event.orderId}, ${event.skus})
ON CONFLICT (order_id) DO NOTHING
`;
},
});
encore run starts an in-memory Pub/Sub broker and Postgres locally, so the publish and the subscriber run end to end before any AWS resource exists, and the local dashboard shows the message in the request trace. A handler that throws is retried and, after the retry limit, goes to the dead-letter queue. The Pub/Sub docs cover retry policies and ordering, and the AWS infrastructure page shows what is created in your account.
A coding agent adding a third consumer, say an analytics writer, adds one Subscription in the same change as its handler and runs it locally, and the queue and subscription it would otherwise have to create in Terraform come with the deploy.
Best fit: backends on AWS that fan events out to several services and want typed topics on SNS and SQS in their own account, testable locally.
SNSClient per process and rely on the default credential chain.MessageGroupId on FIFO topics.Failed entries on every PublishBatchCommand.Install @aws-sdk/client-sns, create an SNSClient for your region and send a PublishCommand with TopicArn and Message. For FIFO topics also set MessageGroupId, and MessageDeduplicationId unless content-based deduplication is enabled on the topic.
The default maximum is 256 KiB per message, including attributes. You can raise it to 1 MiB with the topic's MaximumMessageSize attribute, and for larger payloads store the data in S3 and publish a reference to it.
Subscribe the queue to the topic with protocol sqs, add a queue policy that allows sns.amazonaws.com to call sqs:SendMessage with the topic ARN as the source, and enable RawMessageDelivery on the subscription so consumers receive the message body instead of the SNS JSON envelope.
No. Standard topics deliver at least once and can deliver duplicates or out of order, so consumers must be idempotent. FIFO topics deduplicate within a five-minute window and keep order per message group, but the consumer should still tolerate a retried message.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.