pattern/messaging/sns-multi-channel-alerts
- AWS
- AWS SDK SNS
- Bun
- TypeScript
- LocalStack
- Docker
Um único Publish no tópico AWS SNS chega a todas as subscriptions, cada uma num canal.
pattern/messaging/sns-multi-channel-alerts
Cenário
Compra de R$ 8.500,00 às 3h na Nigéria: o alerta transaction.suspicious vai ao cliente (e-mail), ao analista (SQS) e ao app (webhook).
Planta
Fluxo5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Um único Publish no tópico AWS SNS chega a todas as subscriptions, cada uma num canal
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
FraudeValor > R$ 5.000,00, horário 00:00–05:59 ou país diferente
Um Publish no tópico
Tipo do evento em MessageAttributes para as filter policies
O SNS entrega uma cópia por subscription; a demo confere a do analista no SQS
Trade-offs
O que se ganha, o que se paga
Vantagens
Novo canal = nova subscription
Publisher desacoplado dos canais
Custos
Sem ordem nem entrega única por canal
Webhook precisa verificar a assinatura do SNS
Código
pattern/messaging/sns-multi-channel-alerts
7 arquivos./
localstack/
src/
Executar com Docker
./docker.shuntil curl -s localhost:4566/_localstack/init/ready | grep -q '"completed": true'; do sleep 1; donecp .env.example .env# variáveis de ambientebun install# dependênciasbun run demo# roda o cenáriodocker rm -f sns-multi-channel-alerts-brokerRoda local no LocalStack (emulador AWS), que o docker.sh sobe; localstack/init.sh cria os recursos quando ele fica pronto. Na AWS real, remova AWS_ENDPOINT_URL do .env.
Saída: alerta de ACC-1001 com R$ 8500.00 publicado no SNS e lido na fila SQS do analista com os 3 motivos.
Código
src/demo.ts// Demo: one suspicious card transaction becomes one SNS Publish; SNS fans it out to e-mail, the fraud SQS queue and the app webhook.
import { PublishCommand, SNSClient } from "@aws-sdk/client-sns";
import { DeleteMessageCommand, ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs";
// Above R$ 5,000.00, between 00:00 and 05:59, or abroad: any reason raises the alert.
const ALERT_AMOUNT_CENTS = 500_000;
const ALERT_TOPIC_ARN = Bun.env.SNS_MULTI_CHANNEL_ALERTS_TOPIC_ARN ?? "arn:aws:sns:sa-east-1:000000000000:transaction-suspicious";
const ALERT_ANALYST_QUEUE_URL = Bun.env.SNS_MULTI_CHANNEL_ALERTS_ANALYST_QUEUE_URL ?? "http://localhost:4566/queue/sa-east-1/000000000000/transaction-fraud-analyst";
const region = Bun.env.AWS_REGION ?? "sa-east-1";
const transaction = { accountId: "ACC-1001", amountCents: 850_000, country: "NG", hourLocal: 3, accountHomeCountry: "BR" };
const reasons = [
transaction.amountCents > ALERT_AMOUNT_CENTS ? "amount above limit" : "",
transaction.hourLocal < 6 ? "unusual hour" : "",
transaction.country === transaction.accountHomeCountry ? "" : "foreign location",
].filter(Boolean);
const alert = { alertId: crypto.randomUUID(), ...transaction, reasons, detectedAt: new Date().toISOString() };
// The publisher knows only the topic; each subscription's filter policy routes on the eventType attribute, not on the body.
const { MessageId } = await new SNSClient({ region }).send(
new PublishCommand({
TopicArn: ALERT_TOPIC_ARN,
Subject: "transaction.suspicious",
Message: JSON.stringify(alert),
MessageAttributes: { eventType: { DataType: "String", StringValue: "transaction.suspicious" } },
}),
);
console.log(` [PUBLISHER] ${alert.accountId} R$ ${(alert.amountCents / 100).toFixed(2)} (${reasons.join(", ")}) → SNS message ${MessageId}`);
// The SQS channel proves the fan-out: the analyst's queue holds the SNS envelope with the alert inside Message.
const sqs = new SQSClient({ region });
const { Messages = [] } = await sqs.send(new ReceiveMessageCommand({ QueueUrl: ALERT_ANALYST_QUEUE_URL, MaxNumberOfMessages: 1, WaitTimeSeconds: 10 }));
for (const message of Messages) {
const received = JSON.parse((JSON.parse(message.Body ?? "{}") as { Message: string }).Message) as typeof alert;
console.log(` [FRAUD ANALYST] ${received.accountId} R$ ${(received.amountCents / 100).toFixed(2)} ${received.country}: ${received.reasons.join(", ")}`);
await sqs.send(new DeleteMessageCommand({ QueueUrl: ALERT_ANALYST_QUEUE_URL, ReceiptHandle: message.ReceiptHandle }));
}
Nível
introdutório
2/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
localstack/localstack:3.8container
localstack/localstack:3.8:4566
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com SNS Multi-Channel Alerts?
Um tópico, vários canais. Abrir AWS SNS
Seu progresso
0/157 estudados
Fica salvo só neste navegador.