Pular para o conteúdo

Event-Carried State Transfer

O evento carrega o estado completo: o receptor mantém réplica própria e nunca chama a origem. Payload maior em troca de autonomia.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

Relatórios mostra saldo e status da conta com o serviço de contas fora do ar.

Planta

Sequência
3/3
XADD account.updated (estado completo)1XREADGROUP2HSET com o estado do evento3origem fora do ar: a réplica responde sozinhaServiço de contasRedis Stream account:v1:eventsRelatórios (grupo report)Réplica report:v1:account
3

3 passos — reproduza para seguir o fluxo

Como funciona

4passos

O evento carrega o estado completo e o receptor mantém réplica própria sem chamar a origem

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Contas publica account.updated com o estado inteiro no stream

  2. 2

    Relatórios lê pelo próprio consumer group

  3. 3

    Grava num Hash por conta e confirma com XACK

  4. 4

    A consulta lê só a réplica local

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Receptor autônomo

  • Nenhuma chamada de volta

Custos

  • Payload maior em todo evento

  • Réplica eventualmente consistente

Código

pattern/messaging/event-carried-state-transfer

6 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec event-carried-state-transfer-cache redis-cli ping >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f event-carried-state-transfer-cache

Saída: réplica aplica v1 e v2 de ACC-1001; relatório local: Ana Beatriz Costa, v2, R$ 6920.50, active.

Requisitos
BunDocker
Sobe junto
Redis

Código

src/demo.ts

// Demo: the accounts service publishes the full account state in each event; the report service keeps its own replica and never calls back.
import { RedisClient } from "bun";

const ACCOUNT_STREAM = "account:v1:events";
const REPORT_GROUP = "report";

type AccountState = { accountId: string; holderName: string; balanceCents: number; status: "active" | "blocked"; version: number };

const redis = new RedisClient(Bun.env.EVENT_CARRIED_STATE_TRANSFER_REDIS_URL ?? "redis://localhost:6379");
await redis.send("DEL", [ACCOUNT_STREAM, "report:v1:account:ACC-1001"]);
await redis.send("XGROUP", ["CREATE", ACCOUNT_STREAM, REPORT_GROUP, "0", "MKSTREAM"]);

// Producer: the event carries the whole account, so a receiver never needs a missing field from the source.
async function accountUpdatedPublish(state: AccountState): Promise<void> {
  await redis.send("XADD", [ACCOUNT_STREAM, "*", "type", "com.bank.account.updated", "data", JSON.stringify(state)]);
}

await accountUpdatedPublish({ accountId: "ACC-1001", holderName: "Ana Beatriz Costa", balanceCents: 842_050, status: "active", version: 1 });
await accountUpdatedPublish({ accountId: "ACC-1001", holderName: "Ana Beatriz Costa", balanceCents: 692_050, status: "active", version: 2 });

// Receiver: reads through its consumer group and writes the carried state into its own replica.
const reply = (await redis.send("XREADGROUP", ["GROUP", REPORT_GROUP, "report-1", "COUNT", "50", "STREAMS", ACCOUNT_STREAM, ">"])) as Record<string, [string, string[]][]>;
for (const [entryId, fields] of reply[ACCOUNT_STREAM] ?? []) {
  const state = JSON.parse(fields[fields.indexOf("data") + 1]!) as AccountState;
  await redis.send("HSET", [`report:v1:account:${state.accountId}`, ...Object.entries(state).flatMap(([name, value]) => [name, String(value)])]);
  await redis.send("XACK", [ACCOUNT_STREAM, REPORT_GROUP, entryId]);
  console.log(`  [REPORT] ${state.accountId} v${state.version} applied`);
}

// The accounts service could be down now: the report answers from its replica alone.
const replica = (await redis.send("HGETALL", ["report:v1:account:ACC-1001"])) as Record<string, string>;
console.log(`  [REPORT] ${replica.accountId} ${replica.holderName}, v${replica.version}, R$ ${(Number(replica.balanceCents) / 100).toFixed(2)}, ${replica.status}`);
redis.close();

Nível

introdutório

2/13

Linhas de TypeScript
26
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

Infraestrutura

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Variáveis de ambiente

EVENT_CARRIED_STATE_TRANSFER_REDIS_URL
redis://localhost:6379
Redis holding the account event stream and the report replica.

Trilhapasso 4 de 7

Event-driven

  1. 1Message Broker
  2. 2Pub/Sub
  3. 3Event Notification
  4. 4Event-Carried State Transfer
  5. 5Event Sourcing
  6. 6Snapshot
  7. 7CQRS (Command Query Responsibility Segregation)

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Event-Carried State Transfer?

Próximo projeto, Mensageria & EventosEvent Collaboration
Esc

↑ ↓ navegarEnter abrir239 resultados