pattern/persistence/event-sourcing
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Cada mudança é um evento imutável num log append-only; o saldo é derivado dobrando os eventos com função pura.
pattern/persistence/event-sourcing
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.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Cada mudança é um evento imutável num log append-only e o saldo é derivado dobrando os eventos
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
O comando dobra os eventos com accountEventApply, sem I/O
Decide e gera o novo evento
Grava na versão + 1; (aggregate_id, version) única deixa passar só um dos saques simultâneos
Trigger recusa UPDATE e DELETE no log
Trade-offs
O que se ganha, o que se paga
Vantagens
Auditoria imutável por construção
Saldo em qualquer ponto do histórico
Custos
Leitura exige replay ou projeção
Log cresce e pede snapshot
Código
pattern/persistence/event-sourcing
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec event-sourcing-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f event-sourcing-dbSaí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.
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 = $1 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 ($1, $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 = $1", [accountId]).catch((error: Error) => error.message);
console.log(` [STORE] UPDATE on the log: ${refused}`);
await pool.end();
Nível
intermediário
4/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 5 de 7
Event-driven
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Combina com
Teste rápido
Qual é o próximo passo depois de Event Sourcing?
Encurta o replay. Abrir Snapshot
Seu progresso
0/157 estudados
Fica salvo só neste navegador.