Pular para o conteúdo

Read Replicas

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.

passos
4
arquivos
10
testes
0
tecnologias
5

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ência
6/6
alt[standby alcançou][ainda não]INSERT PIX e COMMIT1LSN do commit2WAL por streaming replication3já reproduziu esse LSN?4SELECT extrato5SELECT extrato6ClientePrimárioStandby
6

6 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.

  1. 1

    pg_basebackup -R clona o primário; o standby aplica o WAL e aceita só leitura

  2. 2

    O PIX devolve o LSN após o commit

  3. 3

    O extrato vai ao standby quando ele reproduzir o LSN

  4. 4

    Espera curta esgotadaLê do primário

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker-compose.ymlinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

docker/

  • primary_hba.shinfra
  • standby_start.shinfra

sql/

  • 01_schema.sqlschema
  • 02_replication.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. docker compose up -d --wait# sobe PostgreSQL
  2. bun install# dependências
  3. bun run demo# roda o cenário
  4. docker compose down -v

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

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • PIX
  • Extrato

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

  • transactions

sql/02_replication.sql

    Variáveis de ambiente

    READ_REPLICAS_PRIMARY_URL
    postgres://postgres:postgres@localhost:5432/replica_db
    Primary: every write.
    READ_REPLICAS_STANDBY_URL
    postgres://postgres:postgres@localhost:5433/replica_db
    Hot standby: the reads.

    Por que se relacionam

    Teste rápido

    Qual é o próximo passo depois de Read Replicas?

    Próximo projeto, Dados & PersistênciaSearch Index
    Esc

    ↑ ↓ navegarEnter abrir239 resultados