pattern/persistence/read-replicas
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
O primário recebe escritas e envia o WAL por streaming replication a um hot standby que atende leituras; a réplica pode estar atrás.
pattern/persistence/read-replicas
Cenário
PIX gravado no primário, extrato servido no standby; o cliente vê o PIX que acabou de fazer (*read-your-writes*).
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Primário recebe escritas e envia o WAL por *streaming replication* a um hot standby que atende leituras
Esconde cada passo: lembre antes de tocar para revelar.
pg_basebackup -R clona o primário; o standby aplica o WAL e aceita só leitura
O PIX devolve o LSN após o commit
O extrato vai ao standby quando ele reproduzir o LSN
Espera curta esgotadaLê do primário
Trade-offs
O que se ganha, o que se paga
Vantagens
Leitura escala sem tocar o primário
Standby pronto para failover
Custos
Leitura pode ser antiga
Read-your-writes exige carregar o LSN
Código
pattern/persistence/read-replicas
10 arquivos./
docker/
sql/
src/
Executar com Docker
docker compose up -d --wait# sobe PostgreSQLbun install# dependênciasbun run demo# roda o cenáriodocker compose down -vSaída: o PIX de R$ 1299.90 commita no primário com o LSN; o extrato sai do standby com 1 PIX e R$ 1299.90 (ou do primário, se o standby não alcançar o LSN a tempo); a escrita no standby é recusada como read-only transaction.
Código
src/demo.ts// Demo: the PIX is written on the primary; the statement is read from the hot standby once it has replayed the PIX's WAL position.
import pg from "pg";
const poolPrimary = new pg.Pool({ connectionString: Bun.env.READ_REPLICAS_PRIMARY_URL ?? "postgres://postgres:postgres@localhost:5432/replica_db" });
const poolStandby = new pg.Pool({ connectionString: Bun.env.READ_REPLICAS_STANDBY_URL ?? "postgres://postgres:postgres@localhost:5433/replica_db" });
const accountId = crypto.randomUUID();
const STANDBY_POLL_ATTEMPTS = 25;
const STANDBY_POLL_INTERVAL_MS = 20;
// Write on the primary and keep the WAL position after the commit: the token a later read waits for.
await poolPrimary.query("INSERT INTO transactions (account_id, type, amount_cents) VALUES ($1, 'pix', 129990)", [accountId]);
const { rows: [commit] } = await poolPrimary.query<{ lsn: string }>("SELECT pg_current_wal_lsn()::text AS lsn");
const lsn = commit!.lsn;
console.log(` [PRIMARY] PIX of R$ 1299.90 committed at LSN ${lsn}`);
// Read-your-writes: the standby serves the statement only after replaying that LSN; past a short wait, the primary answers.
async function readTargetChoose(minLsn: string): Promise<[pg.Pool, string]> {
for (let i = 0; i < STANDBY_POLL_ATTEMPTS; i++) {
const { rows: [state] } = await poolStandby.query<{ caught_up: boolean }>("SELECT pg_wal_lsn_diff(pg_last_wal_replay_lsn(), $1::pg_lsn) >= 0 AS caught_up", [minLsn]);
if (state!.caught_up) return [poolStandby, "standby"];
await Bun.sleep(STANDBY_POLL_INTERVAL_MS);
}
return [poolPrimary, "primary"];
}
const [pool, target] = await readTargetChoose(lsn);
const { rows: [statement] } = await pool.query<{ total: number; amount_cents: string }>("SELECT count(*)::int AS total, coalesce(sum(amount_cents), 0) AS amount_cents FROM transactions WHERE account_id = $1", [accountId]);
console.log(` [READ] statement from the ${target}: ${statement!.total} PIX, R$ ${(Number(statement!.amount_cents) / 100).toFixed(2)}`);
// The standby only replays the WAL: a write there is refused.
const refused = await poolStandby.query("INSERT INTO transactions (account_id, type, amount_cents) VALUES ($1, 'pix', 1)", [accountId]).catch((error: Error) => error.message);
console.log(` [STANDBY] write attempt: ${refused}`);
await Promise.all([poolPrimary.end(), poolStandby.end()]);
Nível
intermediário
5/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
PostgreSQLbanco relacional
postgres:16-alpine:5433
Banco
sql/01_schema.sql
sql/02_replication.sql
Variáveis de ambiente
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Read Replicas?
Tira a leitura quente do banco. Abrir Caching
Seu progresso
0/157 estudados
Fica salvo só neste navegador.