Pular para o conteúdo

CQRS com PostgreSQL e Redis

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.

passos
4
arquivos
7
testes
0
tecnologias
7

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

Fluxo
5/5
ComandoCommand side: validaPostgreSQL: account_eventsProjectorRedis: account:readQuery sideINSERT + NOTIFYLISTENHINCRBY
5

5 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

  1. 1

    O command side calcula o saldo pelo log de eventos e valida

  2. 2

    Evento e pg_notify na mesma transação; o aviso só sai no COMMIT

  3. 3

    O projector escuta o canal e atualiza o Redis

  4. 4

    A consulta lê só o Redis (consistência eventual)

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec cqrs-postgres-redis-db sh -c 'pg_isready -h 127.0.0.1 -U postgres' >/dev/null 2>&1; do sleep 1; done
  3. until docker exec cqrs-postgres-redis-cache redis-cli ping >/dev/null 2>&1; do sleep 1; done
  4. bun install# dependências
  5. bun run demo# roda o cenário
  6. docker rm -f cqrs-postgres-redis-db cqrs-postgres-redis-cache

Saí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.

Requisitos
BunDocker
Sobe junto
PostgreSQLRedis

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

Linhas de TypeScript
65
Tipo
B — dois ou mais serviços (docker compose)

Domínio financeiro

  • Saldo

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Banco

sql/01_schema.sql

  • account_events

Variáveis de ambiente

CQRS_POSTGRES_REDIS_DATABASE_URL
postgresql://postgres:postgres@localhost:5432/cqrs_db
Write side: PostgreSQL event log.
CQRS_POSTGRES_REDIS_REDIS_URL
redis://localhost:6379
Read side: Redis read models, rebuilt from the event log at any time.
Esc

↑ ↓ navegarEnter abrir239 resultados