pattern/persistence/materialized-view
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Guarda o resultado de uma agregação cara como tabela, recalculada só no refresh. O dashboard lê pronto; o dado tem a idade do último refresh.
pattern/persistence/materialized-view
Cenário
O dashboard mostra total, quantidade e ticket médio do mês por conta; um PIX novo de R$ 10.000,00 aparece só após o refresh.
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Guarda o resultado de uma agregação cara como tabela, recalculada só no refresh
Esconde cada passo: lembre antes de tocar para revelar.
transactions é a fonte da verdade
transaction_monthly_summary agrega por conta e mês, índice único (account_id, month)
O dashboard lê só a view
REFRESH ... CONCURRENTLY não bloqueia leitores (exige o índice único)
Trade-offs
O que se ganha, o que se paga
Vantagens
Agregado pesado em milissegundos
Banco mantém, sem código de sync
Custos
Dado com a idade do refresh
Refresh cresce com o volume
Código
pattern/persistence/materialized-view
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec materialized-view-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 materialized-view-dbSaída: o dashboard mostra 500 transações, total R$ 1252500.00 e ticket médio R$ 2505.00; antes do refresh o PIX novo não aparece; depois, 501 transações, total R$ 1262500.00 e ticket médio R$ 2519.96.
Código
src/demo.ts// Demo: the dashboard reads the monthly summary precomputed by a materialized view; a new PIX shows up only after the refresh.
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.MATERIALIZED_VIEW_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/matview_db" });
const accountId = crypto.randomUUID();
// Dashboard query: reads the stored aggregate, never sums the transactions on the hit.
async function summaryPrint(label: string): Promise<void> {
const { rows: [month] } = await pool.query<{ transaction_count: number; total_cents: string; average_ticket_cents: string }>("SELECT transaction_count, total_cents, average_ticket_cents FROM transaction_monthly_summary WHERE account_id = $1 ORDER BY month DESC LIMIT 1", [accountId]);
console.log(` [${label}] ${month!.transaction_count} transactions, total R$ ${(Number(month!.total_cents) / 100).toFixed(2)}, average ticket R$ ${(Number(month!.average_ticket_cents) / 100).toFixed(2)}`);
}
// CONCURRENTLY builds the new result aside and applies only the diff: readers keep the previous numbers meanwhile.
const summaryRefresh = () => pool.query("REFRESH MATERIALIZED VIEW CONCURRENTLY transaction_monthly_summary");
await pool.query("INSERT INTO transactions (account_id, type, amount_cents) SELECT $1, 'pix', 1000 * n FROM generate_series(1, 500) AS n", [accountId]);
await summaryRefresh();
await summaryPrint("DASHBOARD");
await pool.query("INSERT INTO transactions (account_id, type, amount_cents) VALUES ($1, 'pix', 1000000)", [accountId]);
await summaryPrint("BEFORE REFRESH");
await summaryRefresh();
await summaryPrint("AFTER REFRESH");
await pool.end();
Nível
introdutório
3/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
Por que se relacionam
Vem antes
Teste rápido
Qual padrão vem antes de Materialized View?
Leitura pré-calculada. Abrir CQRS
Seu progresso
0/157 estudados
Fica salvo só neste navegador.