The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 306 lines 8.89 KB
Raw
1 ---
2 title: SNS
3 description: Create an SNS Topic, publish to it from a Lambda with the Publish binding, fan messages out to SQS queues, and consume notifications as a typed Stream.
4 ---
5
6 **SNS** is AWS's pub/sub layer: publishers send a message to a
7 **topic** once, and SNS pushes a copy to every subscriber —
8 Lambda functions, SQS queues, HTTPS endpoints, email. In Alchemy
9 it's the `Topic` and `Subscription` resources, producer bindings
10 (`Publish`, `PublishBatch`, and the `Stream`-sink-shaped
11 `TopicSink`), and a consumer side:
12 `SNS.consumeTopicNotifications` subscribes a Lambda to the topic
13 as a typed `Stream` of notifications, creating the subscription
14 and invoke permission for you.
15
16 ## Create a topic
17
18 ```typescript
19 // src/topic.ts
20 import * as SNS from "@alchemy.run/aws/SNS";
21
22 export const Orders = SNS.Topic("Orders");
23 ```
24
25 No name required — Alchemy generates one from the app, stage,
26 and logical ID. Raw SNS topic attributes (delivery policies,
27 KMS keys, display names) go through the `attributes` prop:
28
29 ```typescript
30 export const Orders = SNS.Topic("Orders", {
31 attributes: {
32 DisplayName: "Order events",
33 },
34 });
35 ```
36
37 FIFO topics are a flag:
38
39 ```typescript
40 export const OrdersFifo = SNS.Topic("OrdersFifo", {
41 fifo: true,
42 attributes: {
43 ContentBasedDeduplication: "true",
44 },
45 });
46 ```
47
48 Changing `fifo` or the topic name **replaces** the topic —
49 everything else updates in place.
50
51 ## Publish from a Lambda
52
53 Bind `SNS.Publish(topic)` in the function's Construction phase and call
54 it from runtime handlers. The binding quietly attaches
55 `sns:Publish` scoped to the topic ARN to the function's
56 execution role:
57
58 ```typescript
59 // src/api.ts
60 import * as AWS from "@alchemy.run/aws";
61 import * as SNS from "@alchemy.run/aws/SNS";
62 import * as Effect from "effect/Effect";
63 import * as HttpServerResponse from "effect/http/HttpServerResponse";
64 import { Orders } from "./topic.ts";
65
66 export default class Api extends AWS.Lambda.Function<Api>()(
67 "Api",
68 { main: import.meta.url, functionUrl: true },
69 Effect.gen(function* () {
70 const topic = yield* Orders;
71 const publish = yield* SNS.Publish(topic);
72
73 return {
74 fetch: Effect.gen(function* () {
75 const response = yield* publish({
76 Message: JSON.stringify({ orderId: "o_123" }),
77 Subject: "OrderCreated",
78 });
79 return yield* HttpServerResponse.json({
80 id: response.MessageId,
81 });
82 }).pipe(Effect.orDie),
83 };
84 }).pipe(Effect.provide(SNS.PublishHttp)),
85 ) {}
86 ```
87
88 `SNS.PublishHttp` is the runtime layer that backs the binding
89 with the SNS HTTP API — provide it on the function like any
90 other binding layer.
91
92 ## Publish in batches
93
94 `SNS.PublishBatch(topic)` ships up to 10 messages per API call
95 (runtime layer: `SNS.PublishBatchHttp`):
96
97 ```typescript
98 const publishBatch = yield* SNS.PublishBatch(topic);
99
100 // runtime
101 const response = yield* publishBatch({
102 PublishBatchRequestEntries: messages.map((message, index) => ({
103 Id: `${index}`,
104 Message: message,
105 })),
106 });
107 // response.Successful / response.Failed
108 ```
109
110 ## Forward a stream with `TopicSink`
111
112 If you have a `Stream<string>` of payloads — DynamoDB change
113 records, SQS messages, anything — `SNS.TopicSink(topic)` is the
114 sink-shaped producer: it batches items and publishes each chunk
115 through `PublishBatch`:
116
117 ```typescript
118 const sink = yield* SNS.TopicSink(topic);
119
120 // runtime
121 yield* Stream.fromIterable(payloads).pipe(Stream.run(sink));
122 ```
123
124 `TopicSinkHttp` is implemented on top of the `PublishBatch`
125 binding, so provide it in two tiers with `Layer.provideMerge` —
126 the sink on top, the batch layer beneath:
127
128 ```typescript
129 Effect.provide(
130 Layer.provideMerge(SNS.TopicSinkHttp, SNS.PublishBatchHttp),
131 )
132 ```
133
134 ## Consume notifications on a Lambda
135
136 `SNS.consumeTopicNotifications(topic, ...)` hands your handler a typed `Stream` of SNS
137 notifications you compose with any operator. Behind the scenes
138 it creates the SNS subscription (protocol `lambda`, endpoint =
139 this function) and the `lambda:InvokeFunction` permission for
140 `sns.amazonaws.com`:
141
142 ```typescript
143 // src/worker.ts
144 import * as AWS from "@alchemy.run/aws";
145 import * as SNS from "@alchemy.run/aws/SNS";
146 import * as Console from "effect/Console";
147 import * as Effect from "effect/Effect";
148 import * as Stream from "effect/Stream";
149 import { Orders } from "./topic.ts";
150
151 export default class Worker extends AWS.Lambda.Function<Worker>()(
152 "OrdersWorker",
153 { main: import.meta.url, functionUrl: false },
154 Effect.gen(function* () {
155 const topic = yield* Orders;
156
157 yield* SNS.consumeTopicNotifications(topic, (stream) =>
158 stream.pipe(
159 Stream.runForEach((notification) =>
160 Console.log(
161 `${notification.Subject}: ${notification.Message}`,
162 ),
163 ),
164 ),
165 );
166
167 return {};
168 }).pipe(Effect.provide(AWS.Lambda.TopicEventSource)),
169 ) {}
170 ```
171
172 Each notification carries the SNS message shape — `Message`,
173 `Subject`, `MessageId`, `TopicArn`, and friends. The
174 consumer-side machinery ships in `AWS.Lambda.TopicEventSource`;
175 provide it on the function.
176
177 ## Filter what the consumer sees
178
179 Pass subscription attributes as an optional middle argument —
180 `FilterPolicy` makes SNS drop non-matching messages before they
181 ever invoke your function:
182
183 ```typescript
184 yield* SNS.consumeTopicNotifications(
185 topic,
186 {
187 attributes: {
188 FilterPolicy: JSON.stringify({ type: ["order.created"] }),
189 },
190 },
191 (stream) =>
192 stream.pipe(
193 Stream.runForEach((notification) =>
194 Console.log(notification.Message),
195 ),
196 ),
197 );
198 ```
199
200 ## Fan out to SQS queues
201
202 The classic SNS pattern is topic-to-queues fan-out: one publish,
203 one copy per queue, each queue drained by its own consumer at
204 its own pace. Subscriptions are their own resource, so wiring a
205 queue to a topic is one declaration:
206
207 ```typescript
208 // alchemy.run.ts (inside the Stack's Effect.gen)
209 import * as SNS from "@alchemy.run/aws/SNS";
210 import * as SQS from "@alchemy.run/aws/SQS";
211
212 const topic = yield* Orders;
213
214 const emails = yield* SQS.Queue("EmailJobs");
215 const analytics = yield* SQS.Queue("AnalyticsJobs");
216
217 yield* SNS.Subscription("EmailSubscription", {
218 topicArn: topic.topicArn,
219 protocol: "sqs",
220 endpoint: emails.queueArn,
221 });
222
223 yield* SNS.Subscription("AnalyticsSubscription", {
224 topicArn: topic.topicArn,
225 protocol: "sqs",
226 endpoint: analytics.queueArn,
227 });
228 ```
229
230 One AWS-side requirement: the queue's access policy must let SNS
231 deliver to it. Grant it with the queue's `policy` prop, scoped
232 to the topic:
233
234 ```typescript
235 const emails = yield* SQS.Queue("EmailJobs", {
236 policy: {
237 Version: "2012-10-17",
238 Statement: [
239 {
240 Effect: "Allow",
241 Principal: { Service: "sns.amazonaws.com" },
242 Action: "sqs:SendMessage",
243 Resource: "*",
244 Condition: {
245 ArnEquals: { "aws:SourceArn": topic.topicArn },
246 },
247 },
248 ],
249 },
250 });
251 ```
252
253 By default SNS wraps each delivery in a JSON envelope
254 (`Message`, `Subject`, `TopicArn`, ...). Set
255 `RawMessageDelivery` on the subscription to receive the bare
256 message body instead:
257
258 ```typescript
259 yield* SNS.Subscription("AnalyticsSubscription", {
260 topicArn: topic.topicArn,
261 protocol: "sqs",
262 endpoint: analytics.queueArn,
263 attributes: {
264 RawMessageDelivery: "true",
265 },
266 });
267 ```
268
269 Changing a subscription's `protocol`, `topicArn`, or `endpoint`
270 **replaces** the subscription; `attributes` update in place.
271 From here each queue is a normal SQS consumer —
272 [`SQS.consumeQueueMessages`](/aws/messaging/sqs) picks the messages up on
273 whatever Lambda you point at it.
274
275 ## SNS vs EventBridge vs SQS
276
277 All three move messages; they sit at different points:
278
279 - **[SQS](/aws/messaging/sqs)** is one queue, one consumer group.
280 Point-to-point work distribution: producers enqueue, a pool of
281 workers drains. No fan-out — a message is consumed once.
282 - **SNS** is broadcast. Every subscriber gets its own copy, with
283 per-subscription filter policies. Reach for it when several
284 independent systems must react to the same event, or when you
285 want push delivery (Lambda, HTTPS, email) rather than polling.
286 Pair it with SQS (fan-out above) when each subscriber also
287 needs buffering and retries.
288 - **[EventBridge](/aws/messaging/eventbridge)** is a routed event bus:
289 rules match on the event *content* and route to targets, with
290 first-class support for AWS service events, schedules, and
291 third-party sources. Choose it for event-driven architectures
292 with many event types on one bus; choose SNS when you have one
293 well-known channel and want the simplest possible
294 publish/subscribe with high fan-out.
295
296 ## Where next
297
298 - [SQS](/aws/messaging/sqs) — the queue side of the fan-out pattern:
299 consumers, batching, dead-letter queues.
300 - [EventBridge](/aws/messaging/eventbridge) — content-based routing when
301 one topic per channel stops scaling.
302 - [Lambda](/aws/compute/lambda) — the runtime both the publisher and
303 consumer above are built on.
304 - [`Topic` reference](/providers/aws/sns/topic) and
305 [`Subscription` reference](/providers/aws/sns/subscription) —
306 every prop and attribute.