Pular para o conteúdo

Sharding e Particionamento

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.

passos
4
arquivos
7
testes
0
tecnologias
6

Cenário

Bilhões de transações com chave de shard = conta; o extrato de outubro lê um shard e uma partição.

Planta

Fluxo
7/7
Transação da conta CC-00042Anel de consistenthashing160 pontos por shardshard-ashard-bshard-ctransactions_2026_09transactions_2026_10transactions_defaultaccountIdaccountIdaccountId
7

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

  1. 1

    Anel com 160 nós virtuais sha256 por shard; conta vai ao próximo ponto no sentido horário

  2. 2

    Tudo de uma conta no mesmo shard

  3. 3

    PARTITION BY RANGE (booked_at) por mês

  4. 4

    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

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 sharding-shard-a pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. until docker exec sharding-shard-b pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  4. until docker exec sharding-shard-c pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  5. bun install# dependências
  6. bun run demo# roda o cenário
  7. docker rm -f sharding-shard-a sharding-shard-b sharding-shard-c

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

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • PIX
  • Conta corrente
  • Extrato

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

  • transactions
  • transactions_2026_09
  • transactions_2026_10
  • transactions_default

Variáveis de ambiente

SHARDING_SHARD_A_URL
postgres://postgres:postgres@localhost:5432/shard_a_db
SHARDING_SHARD_B_URL
postgres://postgres:postgres@localhost:5433/shard_b_db
SHARDING_SHARD_C_URL
postgres://postgres:postgres@localhost:5434/shard_c_db

Trilhapasso 7 de 7

Escala e deploy

  1. 1Load Balancing
  2. 2Caching
  3. 3Queue-Based Load Leveling
  4. 4Auto-Scaling
  5. 5Canary Deployment
  6. 6Blue-Green Deployment
  7. 7Sharding e Particionamento

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Sharding e Particionamento?

Próximo projeto, Dados & PersistênciaShared Database (anti-padrão)
Esc

↑ ↓ navegarEnter abrir239 resultados