pattern/messaging/event-notification
- Bun
- Bun RedisClient
- ElysiaJS
- Redis
- TypeScript
- Docker
O evento traz só o id do que mudou; quem precisa do detalhe chama a origem. Payload mínimo, dado sempre atual.
pattern/messaging/event-notification
Cenário
Pagamentos aprova um PIX e publica só o id; o notificador busca valor e contas na API antes de avisar o cliente.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
O evento traz só o id do que mudou e quem precisa do detalhe chama a origem
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Script Lua grava o pagamento e faz XADD no mesmo passo
A notificação traz só tipo e paymentId
O notificador lê pelo consumer group e chama GET /payments/:id
Avisa o cliente e confirma com XACK
Trade-offs
O que se ganha, o que se paga
Vantagens
Payload pequeno e estável
Dado sempre atual
Custos
Receptor depende da origem no ar
Uma chamada extra por evento
Código
pattern/messaging/event-notification
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec event-notification-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f event-notification-cacheSaída: evento só com tipo e paymentId, sem valor nem contas; notificação de ACC-1001: PIX de R$ 1500.00 para ACC-2002 aprovado.
Código
src/demo.ts// Demo: the event says only which payment changed; the customer notifier calls the payments API back for the details.
import { RedisClient } from "bun";
import { Elysia } from "elysia";
const PAYMENT_STREAM = "payment:v1:notifications";
const NOTIFIER_GROUP = "customer-notifier";
const PAYMENT_API_PORT = Number(Bun.env.EVENT_NOTIFICATION_API_PORT ?? 8118);
const redis = new RedisClient(Bun.env.EVENT_NOTIFICATION_REDIS_URL ?? "redis://localhost:6379");
await redis.send("DEL", [PAYMENT_STREAM, "payment:v1:PAY-001"]);
await redis.send("XGROUP", ["CREATE", PAYMENT_STREAM, NOTIFIER_GROUP, "0", "MKSTREAM"]);
// State and notification in one Lua step: never an event for a payment that was not written.
const PAYMENT_WRITE_SCRIPT = `
redis.call('HSET', KEYS[1], unpack(ARGV, 2))
redis.call('XADD', KEYS[2], '*', 'type', 'com.bank.payment.approved', 'paymentId', ARGV[1])`;
await redis.send("EVAL", [PAYMENT_WRITE_SCRIPT, "2", "payment:v1:PAY-001", PAYMENT_STREAM, "PAY-001", "accountFromId", "ACC-1001", "accountToId", "ACC-2002", "amountCents", "150000"]);
// The source of truth the receiver asks for the details.
const api = new Elysia()
.get("/payments/:paymentId", async ({ params }) => (await redis.send("HGETALL", [`payment:v1:${params.paymentId}`])) as Record<string, string>)
.listen(PAYMENT_API_PORT);
const reply = (await redis.send("XREADGROUP", ["GROUP", NOTIFIER_GROUP, "notifier-1", "COUNT", "10", "STREAMS", PAYMENT_STREAM, ">"])) as Record<string, [string, string[]][]>;
for (const [entryId, fields] of reply[PAYMENT_STREAM] ?? []) {
console.log(` [EVENT] ${JSON.stringify(fields)} (no amount, no accounts)`);
const paymentId = fields[fields.indexOf("paymentId") + 1]!;
// The price of the small event: one callback to the source, which always returns the current state.
const payment = (await (await fetch(`http://localhost:${PAYMENT_API_PORT}/payments/${paymentId}`)).json()) as Record<string, string>;
console.log(` [NOTIFY] ${payment.accountFromId}: PIX R$ ${(Number(payment.amountCents) / 100).toFixed(2)} to ${payment.accountToId} approved`);
await redis.send("XACK", [PAYMENT_STREAM, NOTIFIER_GROUP, entryId]);
}
await api.stop();
redis.close();
Nível
introdutório
2/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
Rediscache / estrutura de dados
redis:7-alpine:6379
Variáveis de ambiente
Trilhapasso 3 de 7
Event-driven
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Teste rápido
Qual é o próximo passo depois de Event Notification?
Evento passa a levar o estado. Abrir Event-Carried State Transfer
Seu progresso
0/157 estudados
Fica salvo só neste navegador.