pattern/persistence/sharding
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- node:crypto
- Docker
Sharding divide os dados entre servidores pela chave; particionamento divide a tabela dentro do servidor. Aqui, contas em três PostgreSQL por consistent hashing e transações particionadas por mês. Particione antes de shardear.
pattern/persistence/sharding
Cenário
Bilhões de transações com chave de shard = conta; o extrato de outubro lê um shard e uma partição.
Planta
Fluxo7 passos — reproduza para seguir o fluxo
Como funciona
4passos
Contas em três PostgreSQL por consistent hashing e transações particionadas por mês
Esconde cada passo: lembre antes de tocar para revelar.
Anel com 160 nós virtuais sha256 por shard; conta vai ao próximo ponto no sentido horário
Tudo de uma conta no mesmo shard
PARTITION BY RANGE (booked_at) por mês
Novo shard move ~1/N das contas; a demo compara com hash mod N, que move a maioria
Trade-offs
O que se ganha, o que se paga
Vantagens
Escrita escala com shards
Resharding move só ~1/N
Custos
Transação entre shards exige saga
Consulta entre contas lê todos os shards
Código
pattern/persistence/sharding
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec sharding-shard-a pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; doneuntil docker exec sharding-shard-b pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; doneuntil docker exec sharding-shard-c 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 sharding-shard-a sharding-shard-b sharding-shard-cSaída: 600 transações em shard-a=190, shard-b=218 e shard-c=192; o extrato de outubro de CC-00042 lê só shard-c e transactions_2026_10; um quarto shard moveria 71/300 contas no anel contra 228/300 com hash mod N.
Código
src/demo.ts// Demo: transactions of 300 accounts sharded by account over three PostgreSQL servers, partitioned by month inside each.
import { createHash } from "node:crypto";
import pg from "pg";
const pools: Record<string, pg.Pool> = {
"shard-a": new pg.Pool({ connectionString: Bun.env.SHARDING_SHARD_A_URL ?? "postgres://postgres:postgres@localhost:5432/shard_a_db" }),
"shard-b": new pg.Pool({ connectionString: Bun.env.SHARDING_SHARD_B_URL ?? "postgres://postgres:postgres@localhost:5433/shard_b_db" }),
"shard-c": new pg.Pool({ connectionString: Bun.env.SHARDING_SHARD_C_URL ?? "postgres://postgres:postgres@localhost:5434/shard_c_db" }),
};
const SHARD_VIRTUAL_NODES = 160;
// Consistent hashing: each shard owns SHARD_VIRTUAL_NODES points on a ring of 2^32 positions; an account belongs to the first point
// clockwise from its own hash. Adding a shard moves only ~1/N of the accounts.
type RingPoint = { position: number; shard: string };
const hash32 = (value: string) => createHash("sha256").update(value).digest().readUInt32BE(0);
const ringBuild = (shards: string[]): RingPoint[] =>
shards.flatMap((shard) => Array.from({ length: SHARD_VIRTUAL_NODES }, (_, index) => ({ position: hash32(`${shard}#${index}`), shard }))).toSorted((left, right) => left.position - right.position);
const ring = ringBuild(Object.keys(pools));
const shardResolve = (accountId: string, points: RingPoint[] = ring) => (points.find((point) => point.position >= hash32(accountId)) ?? points[0])?.shard ?? "";
// Everything about one account goes to one shard: its writes, its statement, its locks.
const poolResolve = (accountId: string) => pools[shardResolve(accountId)] as pg.Pool;
await Promise.all(Object.values(pools).map((pool) => pool.query("TRUNCATE transactions")));
const accounts = Array.from({ length: 300 }, (_, index) => `CC-${String(index).padStart(5, "0")}`);
for (const [index, accountId] of accounts.entries()) {
await poolResolve(accountId).query("INSERT INTO transactions (account_id, description, amount_cents, booked_at) VALUES ($1, 'Salário', 500000, '2026-09-05T08:00:00Z'), ($1, 'PIX enviado', $2, '2026-10-02T12:00:00Z')", [accountId, -(1_000 + index)]);
}
const sizes = await Promise.all(Object.entries(pools).map(async ([shard, pool]) => `${shard}=${(await pool.query<{ n: number }>("SELECT count(*)::int AS n FROM transactions")).rows[0]!.n}`));
console.log(` [SHARDS] 600 transactions: ${sizes.join(" ")}`);
// The October statement of one account: one shard, and inside it one monthly partition (pruned by booked_at).
const statementSql = "SELECT description, amount_cents FROM transactions WHERE account_id = $1 AND booked_at >= '2026-10-01' AND booked_at < '2026-11-01'";
const { rows } = await poolResolve("CC-00042").query<{ description: string; amount_cents: string }>(statementSql, ["CC-00042"]);
const plan = (await poolResolve("CC-00042").query<{ "QUERY PLAN": string }>(`EXPLAIN ${statementSql.replace("$1", "'CC-00042'")}`)).rows.map((row) => row["QUERY PLAN"]);
console.log(` [STATEMENT] CC-00042 on ${shardResolve("CC-00042")}: ${JSON.stringify(rows)}; partitions scanned: ${plan.flatMap((line) => /on (transactions_\w+)/.exec(line)?.[1] ?? []).join(", ")}`);
// Contrast: a fourth shard on the ring moves ~1/4 of the accounts; hash mod N would move ~3/4 of them.
const ringGrown = ringBuild([...Object.keys(pools), "shard-d"]);
const movedRing = accounts.filter((accountId) => shardResolve(accountId) !== shardResolve(accountId, ringGrown)).length;
const movedModulo = accounts.filter((accountId) => hash32(accountId) % 3 !== hash32(accountId) % 4).length;
console.log(` [RESHARD] adding shard-d moves ${movedRing}/300 accounts on the ring, ${movedModulo}/300 with hash mod N`);
await Promise.all(Object.values(pools).map((pool) => pool.end()));
Nível
avançado
10/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine
PostgreSQLbanco relacional
postgres:16-alpine
PostgreSQLbanco relacional
postgres:16-alpine
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 7 de 7
Escala e deploy
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Sharding e Particionamento?
Busca textual fora do banco. Abrir Search Index
Seu progresso
0/157 estudados
Fica salvo só neste navegador.