Órbita
- Código
- Arquitetura
- Dados
- Integração
- Resiliência
Quando usar
Leitura e escrita com cargas e formatos muito diferentes
Órbita
Quando usar
Leitura e escrita com cargas e formatos muito diferentes
Problema
Modelo único sobrecarregado por leitura e escrita
Quando usar
Leitura e escrita com cargas e formatos muito diferentes
cqrs
Separa o modelo de escrita (commands) do modelo de leitura (queries).
Planta de sequência
Reproduzir passo a passoComo funciona
O command trava a conta com SELECT ... FOR UPDATE
Saldo validado contra o write model
Trigger atualiza account_summaries na mesma transação do INSERT
A query lê só o read model, por pool próprio, sem JOIN nem SUM
README.mdpattern/persistence/cqrs
thiagoeti/pattern/cqrsEscrita (commands) num modelo normalizado que valida regras; leitura (queries) num modelo desnormalizado e pré-calculado.
Depósitos e saques entram no livro; o app lê saldo e totais prontos do read model.
SELECT ... FOR UPDATEaccount_summaries na mesma transação do INSERTJOIN nem SUMsrc/demo.ts// Demo: commands write the normalized ledger and enforce the balance rule; the query reads only the precomputed summary.
import pg from "pg";
// One pool per side: moving the read side to a replica is only a change of its URL.
const poolWrite = new pg.Pool({ connectionString: Bun.env.CQRS_WRITE_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/cqrs_db" });
const poolRead = new pg.Pool({ connectionString: Bun.env.CQRS_READ_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/cqrs_db" });
const brl = (cents: number) => `R$ ${(cents / 100).toFixed(2)}`;
// Command: locks the account, checks the rule against the write model, and appends; the trigger projects in the same transaction.
async function transactionAppend(accountId: string, type: "deposit" | "withdrawal", amountCents: number): Promise<void> {
const client = await poolWrite.connect();
try {
await client.query("BEGIN");
const { rows: [account] } = await client.query<{ balance_cents: string }>("SELECT balance_cents FROM accounts WHERE id = ## Executar FOR UPDATE", [accountId]);
if (type === "withdrawal" && amountCents > Number(account!.balance_cents)) throw new Error(`balance ${brl(Number(account!.balance_cents))} below ${brl(amountCents)}`);
await client.query("UPDATE accounts SET balance_cents = balance_cents + $2 WHERE id = ## Executar", [accountId, type === "deposit" ? amountCents : -amountCents]);
await client.query("INSERT INTO transactions (account_id, type, amount_cents) VALUES (## Executar, $2, $3)", [accountId, type, amountCents]);
await client.query("COMMIT");
console.log(` [COMMAND] ${type} ${brl(amountCents)}`);
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
const { rows: [account] } = await poolWrite.query<{ id: string }>("INSERT INTO accounts (owner_name) VALUES ('Joao Silva') RETURNING id");
await transactionAppend(account!.id, "deposit", 150_000);
await transactionAppend(account!.id, "withdrawal", 20_000);
// Query: no JOIN, no SUM — the read model already holds the answer.
const { rows: [summary] } = await poolRead.query<{ owner_name: string; balance_cents: string; deposits_cents: string; withdrawals_cents: string; transaction_count: number }>("SELECT owner_name, balance_cents, deposits_cents, withdrawals_cents, transaction_count FROM account_summaries WHERE account_id = ## Executar", [account!.id]);
console.log(` [QUERY] ${summary!.owner_name}: balance ${brl(Number(summary!.balance_cents))}, in ${brl(Number(summary!.deposits_cents))}, out ${brl(Number(summary!.withdrawals_cents))}, ${summary!.transaction_count} transactions`);
await Promise.all([poolWrite.end(), poolRead.end()]);
./docker.sh
until docker exec cqrs-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 cqrs-db
Saída: depósito de R$ 1500.00 e saque de R$ 200.00 aceitos; a query lê Joao Silva com saldo R$ 1300.00, entradas R$ 1500.00, saídas R$ 200.00 e 2 transações.
| Vantagem | Desvantagem |
|---|---|
| Leitura rápida e escalável à parte | Dois modelos em sincronia |
| Regras isoladas na escrita | Read model em réplica pode atrasar |