Pular para o conteúdo
  1. Padrões
  2. Dados

event-sourcing

Persiste cada mudança como evento imutável e reconstrói o estado a partir deles.
Status
Em breve
Categoria
Dados
Implementação em Dados & Persistênciapattern/persistence/event-sourcingintermediário4 passos≈ 3 min

Órbita

  1. Código
  2. Arquitetura
  3. Dados
  4. Integração
  5. Resiliência

Quando usar

Auditoria completa, reprocessamento e linha do tempo

  1. Problema

    Estado atual sem histórico de como chegou até ali

  2. Quando usar

    Auditoria completa, reprocessamento e linha do tempo

  3. event-sourcing

    Persiste cada mudança como evento imutável e reconstrói o estado a partir deles.

Planta de sequência

Reproduzir passo a passo
SELECT eventos ORDER BY version1fold puro, saldo e versão atuais2decide: saldo cobre o saque3INSERT version + 14chave única (aggregate_id, version) barra escritor concorrenteUPDATE e DELETE barrados por triggerComandoevent_store

Como funciona

  1. 1

    O comando dobra os eventos com accountEventApply, sem I/O

  2. 2

    Decide e gera o novo evento

  3. 3

    Grava na versão + 1; (aggregate_id, version) única deixa passar só um dos saques simultâneos

  4. 4

    Trigger recusa UPDATE e DELETE no log

Nível
intermediário
Infraestrutura
B — um serviço (docker.sh)
Domínio financeiro
Saldo
Abrir a implementação completa

README.mdpattern/persistence/event-sourcing

thiagoeti/pattern/event-sourcing

Cada mudança é um evento imutável num log append-only; o saldo é derivado dobrando os eventos com função pura.

Cenário

Abertura, depósito e saque viram EventAccountOpened, EventAccountMoneyDeposited e EventAccountMoneyWithdrawn; dois saques simultâneos disputam a mesma versão e o saldo sai do replay.

Como funciona

  1. O comando dobra os eventos com accountEventApply, sem I/O
  2. Decide e gera o novo evento
  3. Grava na versão + 1; (aggregate_id, version) única deixa passar só um dos saques simultâneos
  4. Trigger recusa UPDATE e DELETE no log

Código

src/demo.ts

// Demo: every change to the account is an appended, immutable event; the balance is never stored, it is a fold over the stream.
import pg from "pg";

const pool = new pg.Pool({ connectionString: Bun.env.EVENT_SOURCING_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/eventsourcing_db" });

type EventAccount = { type: "EventAccountOpened" | "EventAccountMoneyDeposited" | "EventAccountMoneyWithdrawn"; payload: { amountCents?: number; ownerName?: string } };
type AccountState = { balanceCents: number; version: number };

// Pure fold: no I/O and no rule — a past fact is replayed, never refused.
const accountEventApply = (state: AccountState, event: EventAccount): AccountState => {
  const signedCents = event.type === "EventAccountMoneyDeposited" ? event.payload.amountCents! : event.type === "EventAccountMoneyWithdrawn" ? -event.payload.amountCents! : 0;
  return { balanceCents: state.balanceCents + signedCents, version: state.version + 1 };
};

async function accountLoad(accountId: string): Promise<AccountState> {
  const { rows } = await pool.query<{ event_type: EventAccount["type"]; payload: EventAccount["payload"] }>("SELECT event_type, payload FROM event_store WHERE aggregate_id = ## Executar ORDER BY version", [accountId]);
  return rows.map((row) => ({ type: row.event_type, payload: row.payload })).reduce(accountEventApply, { balanceCents: 0, version: 0 });
}

// Load, decide against the current state, append at version + 1: a concurrent writer of that version fails on the unique key.
async function eventAppend(accountId: string, state: AccountState, event: EventAccount): Promise<void> {
  await pool.query("INSERT INTO event_store (aggregate_id, version, event_type, payload) VALUES (## Executar, $2, $3, $4)", [accountId, state.version + 1, event.type, event.payload]);
  console.log(`  [STORE] v${state.version + 1} ${event.type} ${JSON.stringify(event.payload)}`);
}

async function accountCommand(accountId: string, decide: (state: AccountState) => EventAccount): Promise<void> {
  const state = await accountLoad(accountId);
  await eventAppend(accountId, state, decide(state));
}

const accountId = crypto.randomUUID();
await accountCommand(accountId, () => ({ type: "EventAccountOpened", payload: { ownerName: "Ana Lima" } }));
await accountCommand(accountId, () => ({ type: "EventAccountMoneyDeposited", payload: { amountCents: 200_000 } }));
const withdrawalDecide = (state: AccountState): EventAccount => {
  if (state.balanceCents < 30_000) throw new Error("balance insufficient");
  return { type: "EventAccountMoneyWithdrawn", payload: { amountCents: 30_000 } };
};
// Two tellers withdraw at once: both load v2 before either appends, so both write v3 and the unique key lets exactly one through.
const states = await Promise.all([accountLoad(accountId), accountLoad(accountId)]);
const outcomes = await Promise.allSettled(states.map((state) => eventAppend(accountId, state, withdrawalDecide(state))));
const conflicts = outcomes.filter((outcome) => outcome.status === "rejected");
console.log(`  [CONCURRENCY] 2 withdrawals at v2: ${outcomes.length - conflicts.length} appended, ${conflicts.length} rejected (${conflicts.map((outcome) => (outcome.reason as Error).message).join("; ")})`);

const state = await accountLoad(accountId);
console.log(`  [LOAD] balance R$ ${(state.balanceCents / 100).toFixed(2)} replayed from ${state.version} events`);
const refused = await pool.query("UPDATE event_store SET payload = '{}' WHERE aggregate_id = ## Executar", [accountId]).catch((error: Error) => error.message);
console.log(`  [STORE] UPDATE on the log: ${refused}`);
await pool.end();

Executar

./docker.sh
until docker exec event-sourcing-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
bun install
bun run demo
docker rm -f event-sourcing-db

Saída: v1 abertura, v2 depósito de 200000; dos dois saques simultâneos de 30000 na v2, 1 grava a v3 e 1 é recusado pela chave única uq_event_store_aggregate_version; o replay de 3 eventos dá R$ 1700.00 e o UPDATE no log é recusado.

Trade-offs

Vantagem Desvantagem
Auditoria imutável por construção Leitura exige replay ou projeção
Saldo em qualquer ponto do histórico Log cresce e pede snapshot
Esc

↑ ↓ navegarEnter abrir239 resultados