pattern/persistence/cqrs-postgres-redis
- Bun
- Bun RedisClient
- PostgreSQL
- Redis
- TypeScript
- node-postgres
- Docker
Separa escrita (log de eventos no PostgreSQL) de leitura (pré-calculada no Redis). Use quando leitura e escrita têm forma e carga muito diferentes.
pattern/persistence/cqrs-postgres-redis
Cenário
ACC-001 recebe depósito de R$ 1.000,00 e saque de R$ 250,00; um saque de R$ 9.000,00 é recusado. O saldo vem só do Redis.
Planta
Fluxo5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Separa escrita (log de eventos no PostgreSQL) de leitura (pré-calculada no Redis)
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
O command side calcula o saldo pelo log de eventos e valida
Evento e pg_notify na mesma transação; o aviso só sai no COMMIT
O projector escuta o canal e atualiza o Redis
A consulta lê só o Redis (consistência eventual)
Trade-offs
O que se ganha, o que se paga
Vantagens
Leitura e escrita escalam separadas
Consulta sem agregação
Custos
Leitura atrasa em relação à escrita
Dois modelos e um projector para manter
Código
pattern/persistence/cqrs-postgres-redis
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec cqrs-postgres-redis-db sh -c 'pg_isready -h 127.0.0.1 -U postgres' >/dev/null 2>&1; do sleep 1; doneuntil docker exec cqrs-postgres-redis-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f cqrs-postgres-redis-db cqrs-postgres-redis-cacheSaída: depósito de R$ 1000.00 e saque de R$ 250.00 aceitos; saque de R$ 9000.00 recusado por saldo insuficiente; a query lê do Redis ACC-001 com R$ 750.00 e 2 transações.
Código
src/demo.ts// Demo: commands validate and append events to PostgreSQL; a projector updates a Redis read model; queries read only Redis.
import { RedisClient } from "bun";
import pg from "pg";
const ACCOUNT_CHANNEL = "account_events";
const accountReadKey = (accountId: string) => `account:read:${accountId}`;
const pool = new pg.Pool({ connectionString: Bun.env.CQRS_POSTGRES_REDIS_DATABASE_URL ?? "postgresql://postgres:postgres@localhost:5432/cqrs_db" });
const redis = new RedisClient(Bun.env.CQRS_POSTGRES_REDIS_REDIS_URL ?? "redis://localhost:6379");
type AccountCommand = { type: "deposit" | "withdraw"; accountId: string; amountCents: number };
// Command side: rules are checked against the event log, never against the read model.
async function commandHandle(command: AccountCommand): Promise<void> {
const { rows } = await pool.query<{ balance_cents: string }>(
"SELECT COALESCE(SUM(CASE event_type WHEN 'MoneyDeposited' THEN amount_cents ELSE -amount_cents END), 0) AS balance_cents FROM account_events WHERE account_id = $1",
[command.accountId],
);
if (command.type === "withdraw" && command.amountCents > Number(rows[0]!.balance_cents)) throw new Error("insufficient funds");
const client = await pool.connect();
try {
// NOTIFY inside the transaction is delivered only on COMMIT.
await client.query("BEGIN");
const eventType = command.type === "deposit" ? "MoneyDeposited" : "MoneyWithdrawn";
await client.query("INSERT INTO account_events (account_id, event_type, amount_cents) VALUES ($1, $2, $3)", [command.accountId, eventType, command.amountCents]);
await client.query("SELECT pg_notify($1, $2)", [ACCOUNT_CHANNEL, JSON.stringify({ ...command, eventType })]);
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
// Projector: turns each event into the denormalized read model the queries serve.
async function projectorStart(): Promise<pg.PoolClient> {
const listener = await pool.connect();
await listener.query(`LISTEN ${ACCOUNT_CHANNEL}`);
listener.on("notification", (notification) => {
const event = JSON.parse(notification.payload!) as AccountCommand & { eventType: string };
const signed = event.eventType === "MoneyDeposited" ? event.amountCents : -event.amountCents;
void redis.send("HINCRBY", [accountReadKey(event.accountId), "balanceCents", String(signed)]);
void redis.send("HINCRBY", [accountReadKey(event.accountId), "transactionCount", "1"]);
});
return listener;
}
await pool.query("TRUNCATE account_events");
await redis.del(accountReadKey("ACC-001"));
const listener = await projectorStart();
const commands: AccountCommand[] = [
{ type: "deposit", accountId: "ACC-001", amountCents: 100_000 },
{ type: "withdraw", accountId: "ACC-001", amountCents: 25_000 },
{ type: "withdraw", accountId: "ACC-001", amountCents: 900_000 },
];
for (const command of commands) {
try {
await commandHandle(command);
console.log(` [COMMAND] ${command.type} R$ ${(command.amountCents / 100).toFixed(2)} accepted`);
} catch (error) {
console.log(` [COMMAND] ${command.type} R$ ${(command.amountCents / 100).toFixed(2)} rejected: ${(error as Error).message}`);
}
}
// Eventual consistency: the read side catches up a moment later.
for (let i = 0; i < 50 && (await redis.hget(accountReadKey("ACC-001"), "transactionCount")) !== "2"; i++) await Bun.sleep(20);
const model = await redis.hgetall(accountReadKey("ACC-001"));
console.log(` [QUERY] ACC-001 balance R$ ${(Number(model.balanceCents) / 100).toFixed(2)}, ${model.transactionCount} transactions (from Redis)`);
listener.release();
redis.close();
await pool.end();
Nível
intermediário
6/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Rediscache / estrutura de dados
redis:7-alpine:6379
Banco
sql/01_schema.sql
Variáveis de ambiente
Por que se relacionam
Seu progresso
0/157 estudados
Fica salvo só neste navegador.