Skip to main content

Partitioning & Sharding in Practice

Learning objectives
  • Create range, list and hash partitioned tables in Postgres and verify partition pruning in plans
  • Design time-based partitioning for a transactions or ledger table, including retention and archiving
  • Explain how Citus and Vitess distribute tables, route queries and reshard
  • Choose a shard key (customer, account, merchant, tenant) from access patterns, transaction boundaries and skew
  • Handle cross-shard transactions and plan rebalancing without downtime

TL;DR​

  • Partitioning splits one table into child tables inside one database; sharding spreads data across many database servers. Partition first; shard when one primary can no longer handle the writes or the dataset.
  • Postgres declarative partitioning supports range, list and hash. Primary keys and unique constraints must include the partition key; indexes are local per partition.
  • Pruning only works when the query filters on the partition key directly. A ledger partitioned by created_at but queried by id alone scans every partition.
  • Time partitions make retention cheap: detach and archive a month instead of deleting a billion rows.
  • A good shard key is present in almost every query, keeps transactions on one shard, has high cardinality and spreads load evenly. For banks, customer_id usually beats account_id; for marketplaces, buyer and merchant views often need different keys plus a CDC-fed read model.
  • Cross-shard transactions are expensive (2PC) or eventually consistent (sagas). Co-locate data that changes together.
  • Use many logical shards mapped to fewer physical nodes, so rebalancing moves whole logical shards instead of rehashing every row.

Why it matters​

Transaction tables in banks and e-commerce grow without bound: a mid-size payment processor can add hundreds of millions of rows per month, and regulations often require keeping years of history. At some point a single unpartitioned table hurts everything: vacuum takes days, index rebuilds take hours, deleting old data generates more WAL than the business traffic, and the working set no longer fits in memory. Later, the write rate or total size outgrows one primary, and you must shard. Both decisions are hard to reverse, and the shard key shapes every service built on top. Interviewers know this and push on it.

Core concepts​

Partitioning versus sharding​

PartitioningSharding
ScopeOne database instanceMany instances
SolvesMaintenance (vacuum, indexes, retention), pruning large scans, smaller working setWrite throughput, total size, failure isolation (blast radius)
TransactionsNormal ACID across partitionsSingle-shard ACID; cross-shard needs 2PC or sagas
TransparencyFully transparent to SQLNeeds a router (Citus, Vitess, application logic)

Postgres declarative partitioning​

-- Range: the workhorse for time-series and transactions
CREATE TABLE ledger_entry (
id bigint NOT NULL,
account_id bigint NOT NULL,
journal_id bigint NOT NULL,
amount_minor bigint NOT NULL,
currency char(3) NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (id, created_at) -- must include the partition key
) PARTITION BY RANGE (created_at);

CREATE TABLE ledger_entry_2025_11 PARTITION OF ledger_entry
FOR VALUES FROM ('2025-11-01') TO ('2025-12-01');
CREATE TABLE ledger_entry_2025_12 PARTITION OF ledger_entry
FOR VALUES FROM ('2025-12-01') TO ('2026-01-01');

-- Index on the parent is created on every partition (local indexes)
CREATE INDEX ON ledger_entry (account_id, created_at);

-- List: by region or tenant tier
CREATE TABLE customer_event (
region text NOT NULL,
id bigint NOT NULL,
payload jsonb,
PRIMARY KEY (region, id)
) PARTITION BY LIST (region);
CREATE TABLE customer_event_vn PARTITION OF customer_event FOR VALUES IN ('VN');
CREATE TABLE customer_event_sg PARTITION OF customer_event FOR VALUES IN ('SG');
CREATE TABLE customer_event_other PARTITION OF customer_event DEFAULT;

-- Hash: spread a hot table evenly when there is no natural range
CREATE TABLE session_token (
token_hash bytea NOT NULL,
customer_id bigint NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY (token_hash)
) PARTITION BY HASH (token_hash);
CREATE TABLE session_token_p0 PARTITION OF session_token FOR VALUES WITH (MODULUS 4, REMAINDER 0);
-- ... p1, p2, p3

Rules and version notes (Postgres):

  • Hash partitioning and default partitions arrived in 11; foreign keys referencing partitioned tables in 12; DETACH PARTITION … CONCURRENTLY in 14.
  • Unique constraints must include all partition key columns, because each partition enforces uniqueness only locally. There are no global indexes. If you need global uniqueness of id alone, generate ids that are unique by construction (sequence, UUIDv7, Snowflake) and accept that the database enforces (id, created_at).
  • Updating the partition key moves the row to another partition (11+), which is a delete plus insert under the hood.
  • Sub-partitioning is allowed (for example range by month, then hash by account) but multiplies the partition count.
  • Partition counts in the hundreds are routine; many thousands increase planning time and lock overhead when queries cannot be pruned at plan time (rough; improved in recent versions).

MySQL also supports RANGE, LIST, HASH and KEY partitioning with similar pruning; every unique key (including the PK) must include all partitioning columns, and partitioned InnoDB tables cannot have foreign keys.

Partition pruning​

The planner (and, since Postgres 11, the executor for parameters and subqueries) skips partitions whose bounds cannot match:

EXPLAIN (COSTS OFF)
SELECT sum(amount_minor) FROM ledger_entry
WHERE account_id = 42
AND created_at >= '2025-11-01' AND created_at < '2025-12-01';
-- Aggregate
-- -> Index Scan using ledger_entry_2025_11_account_id_created_at_idx on ledger_entry_2025_11

Pruning fails, and every partition is scanned, when:

  • The filter is on another column only (WHERE id = 123). Fix by including the time in lookups (UUIDv7 or Snowflake ids embed a timestamp you can turn into a range), or by keeping a small lookup table from id to created_at.
  • The partition key is wrapped in an expression (WHERE date(created_at) = …).
  • Types differ in ways that prevent comparison with partition bounds.

With prepared statements running a generic plan, pruning happens at execution time and shows up as Subplans Removed: N in EXPLAIN ANALYZE.

Time-based partitions for transactions and retention​

A payments or ledger table partitioned by month (or by day at very high volume) gives you:

  • Hot/cold separation: the current month's partition and its indexes stay in memory; old partitions are rarely touched.
  • Per-partition maintenance: vacuum, REINDEX CONCURRENTLY and ANALYZE run on manageable pieces; old partitions become effectively read-only and all-visible (good for index-only scans).
  • Cheap retention: removing a month is a metadata operation.
-- Create partitions ahead of time (a job, or the pg_partman extension)
CREATE TABLE ledger_entry_2026_01 PARTITION OF ledger_entry
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');

-- Retire an old month without blocking writers
ALTER TABLE ledger_entry DETACH PARTITION ledger_entry_2018_11 CONCURRENTLY;
-- export ledger_entry_2018_11 to object storage (e.g. Parquet), verify row counts and checksums, then
DROP TABLE ledger_entry_2018_11;

Compare with DELETE FROM ledger_entry WHERE created_at < '2018-12-01': hours of work, WAL for every row, replica lag, bloat left behind. Retention periods for financial records are set by regulation and vary by jurisdiction and record type (often several years); involve compliance before deciding (see Compliance).

Tips:

  • Always pre-create future partitions with monitoring; an insert with no matching partition fails (or lands in the default partition, which then blocks creating the proper partition until you move the rows out).
  • Avoid a default partition on time-range tables; it makes ATTACH scan the default and prevents DETACH … CONCURRENTLY.
  • To attach a bulk-loaded table without a long scan, first add a CHECK constraint matching the partition bounds, then ATTACH PARTITION; Postgres skips validation when the constraint proves the bounds.
  • Pair time partitions with BRIN indexes on created_at for audit range scans (see Indexing).

Sharding with Citus and Vitess​

Citus (Postgres extension). A coordinator node holds metadata and routes queries; worker nodes hold shards (ordinary Postgres tables).

SELECT create_distributed_table('customer', 'customer_id');
SELECT create_distributed_table('account', 'customer_id', colocate_with => 'customer');
SELECT create_distributed_table('ledger_entry', 'customer_id', colocate_with => 'customer');
SELECT create_reference_table('currency'); -- small table replicated to every node
  • Tables distributed on the same column with the same shard count are co-located: rows with the same customer_id live on the same worker, so joins and transactions within a customer are local.
  • Reference tables (currencies, countries, fee schedules) are copied everywhere so joins with them are local.
  • Queries filtering on the distribution column route to one shard; others fan out in parallel to all shards. Multi-shard writes use two-phase commit internally.
  • Shards can be moved and rebalanced online; recent versions also support schema-based sharding for multi-tenant apps. Check the version-specific docs.

Vitess (MySQL). VTGate is a stateless proxy that speaks the MySQL protocol and routes queries; VTTablet runs beside each MySQL instance; a topology service stores the shard map.

  • A keyspace is a logical database, split into shards by ranges of a keyspace ID.
  • The VSchema declares, per table, a primary vindex: a function from a column (for example customer_id via a hash vindex) to the keyspace ID. Lookup vindexes map secondary columns (order_id, email) to keyspace IDs through a backing table, so lookups by them still route to one shard.
  • Resharding uses VReplication: new shards are filled from a snapshot plus the binlog stream, verified, then traffic is switched over per tablet type. MoveTables does the same for vertical splits.
  • Vitess originated at YouTube and runs at several very large MySQL users.

Application-level sharding (a directory service mapping tenant or customer to a database) is also common, especially for database-per-tenant designs (see Schema Patterns). You own routing, resharding and cross-shard queries yourself.

Choosing the shard key​

Criteria, roughly in priority order:

  1. Query locality: the key appears in nearly every hot query, so they hit one shard.
  2. Transaction locality: data that must change atomically shares the key.
  3. Cardinality and evenness: many distinct values with no dominant one.
  4. Hotspot resistance: no single value receives a large share of traffic at peak.
  5. Stability: the key value never changes for a row (moving rows between shards is expensive).

Comparing candidates for a combined bank-and-marketplace platform:

Shard keyLocal operationsCross-shard operationsSkew riskTypical fit
customer_idCustomer's accounts, cards, statements, orders, own-account transfersP2P transfers to other customers; merchant viewsCorporate customers with thousands of accountsRetail banking, buyer-side e-commerce, wallets
account_idSingle-account postings and statementsEvery transfer (two accounts); customer overviewLow, except very busy accountsRarely ideal alone; works if accounts of one customer are co-located via a customer-derived prefix
merchant_idMerchant dashboard, settlement, payouts, refundsBuyer's order history across merchantsHigh: a few merchants dominate volume, sale events concentrate on themAcquiring and merchant-side services, often with big merchants split further
tenant_idEverything inside a tenantCross-tenant analyticsLarge tenantsB2B SaaS, banking-as-a-service
TimeRecent-data queriesEverything by entityExtreme: all writes hit the newest shardNever as the sole shard key for OLTP (fine for partitioning within a shard)

A pattern that works for marketplaces: shard the order service by buyer customer_id (checkout and order history are buyer-centric), publish order events, and build a merchant-side read model sharded by merchant_id via CDC (see Transactional Outbox & CDC and E-commerce Order Platform). For payments acquiring, shard by merchant_id and split the top merchants by sub-key (merchant_id, terminal_id or a bucket).

Cross-shard transactions​

A P2P transfer from customer A (shard 1) to customer B (shard 7) cannot be one local transaction. Options:

ApproachGuaranteesCostsUse for
Co-locationLocal ACIDConstrains the shard keyEverything you can arrange to be local
Two-phase commit (Citus, XA)Atomic across shardsExtra round trips, locks held during prepare, blocking if the coordinator fails mid-protocol; needs recovery of prepared transactionsRare administrative or low-volume operations
Saga with ledger in-transit accountEventually consistent; money always accounted for in a clearing/suspense accountIntermediate states visible; compensation logic; idempotency everywhereP2P transfers, cross-shard payments

Details in Distributed Transactions: 2PC, TCC, Saga and Bank Transfer System.

Cross-shard reads: scatter-gather with a strict limit and timeout, or maintain global secondary indexes (a lookup table from order_id or email to shard), or embed the shard in the identifier (Instagram's well-known scheme puts a logical shard id inside each 64-bit id, see Unique ID Generation).

Rebalancing​

Never map rows directly with hash(key) % number_of_servers: adding a server remaps almost every row. Instead:

  1. Hash keys into a fixed, large number of logical shards (for example 4,096 buckets), chosen once.
  2. Keep a mapping table from logical shard to physical database. Initially many logical shards live on each server.
  3. To rebalance or split a hot server, move logical shards:
    • copy a snapshot of the bucket to the target,
    • stream ongoing changes (logical replication, VReplication, CDC),
    • verify counts and checksums,
    • briefly block writes for that bucket, let replication catch up, switch the mapping, unblock,
    • clean up the source copy after a safety period.

This is the same idea as virtual nodes in Consistent Hashing. Citus and Vitess automate versions of it; with application-level sharding you build it yourself, so design the mapping table and the move procedure before you need them.

Trade-offs​

OptionStrengthsWeaknessesChoose when
No partitioningSimplest; global indexes and constraintsMaintenance and retention pain at scaleTables under roughly hundreds of GB with no retention needs
Range partitioning by timeRetention by detach, hot/cold separation, pruning for time queriesLookups without time scan all partitions; partition management jobsTransactions, ledgers, events, logs
Hash partitioningEven spread of I/O and vacuumNo range pruning; partition count fixed unless you re-partitionHot tables without a natural range
List partitioningIsolate regions or tiersUneven sizesData residency, tenant tiers
CitusPostgres compatibility, co-location, reference tables, online rebalancingCoordinator design, extension version coupling, some SQL limitations on distributed queriesMulti-tenant SaaS, customer-sharded OLTP on Postgres
VitessProven at very large MySQL scale, online reshardingOperational complexity, MySQL-only, some query restrictionsLarge MySQL estates
App-level shardingFull control, any databaseYou build routing, resharding, cross-shard toolingDatabase per tenant, special requirements
Distributed SQL (CockroachDB, YugabyteDB, TiDB, Spanner)Automatic sharding and distributed transactionsHigher per-transaction latency, cost, different operational modelGlobal consistency needs, teams wanting less manual sharding

In practice​

A logical-shard router in Go:

package shard

import (
"encoding/binary"
"fmt"
"hash/fnv"
"sync/atomic"

"github.com/jackc/pgx/v5/pgxpool"
)

const LogicalShards = 4096 // fixed forever; physical placement can change

// Map assigns each logical shard to a physical database pool.
type Map struct {
placement [LogicalShards]int // logical shard -> index into pools
pools []*pgxpool.Pool
}

// Router holds the current map; swap atomically when a shard moves.
type Router struct {
current atomic.Pointer[Map]
}

func LogicalShard(customerID int64) int {
var b [8]byte
binary.BigEndian.PutUint64(b[:], uint64(customerID))
h := fnv.New64a()
h.Write(b[:])
return int(h.Sum64() % LogicalShards)
}

func (r *Router) PoolFor(customerID int64) (*pgxpool.Pool, error) {
m := r.current.Load()
if m == nil {
return nil, fmt.Errorf("shard map not loaded")
}
return m.pools[m.placement[LogicalShard(customerID)]], nil
}

func (r *Router) Swap(m *Map) { r.current.Store(m) }

Store the logical shard number on each row (or derive it from an id that embeds it) so moves and audits do not depend on recomputing hashes in many codebases.

Checklist before sharding:

  • Have you exhausted vertical scaling, read replicas for reads, caching, partitioning and query fixes? (See Database Replication & Sharding.)
  • Is the shard key in every hot query and transaction? List the exceptions and how each is handled.
  • What are the top 10 values by volume, and what happens at 10× peak for the largest one?
  • How will you reshard, back up and restore one shard, and run schema migrations across all shards?

Common pitfalls​

  • Partitioning a table and still querying it by non-partition columns only. Symptom: queries got slower after partitioning because they now probe dozens of indexes.
  • Forgetting to create next month's partition. Symptom: inserts fail at midnight on the first of the month, or everything lands in the default partition.
  • Expecting global uniqueness from a partitioned unique index without the partition key. Postgres rejects it; teams then drop the constraint and get duplicates.
  • Retention via giant DELETE. Symptom: WAL spikes, replica lag, bloat, and hours-long jobs that collide with business peaks.
  • Shard key with skew. Sharding by merchant_id and discovering one merchant is 25% of volume. Symptom: one shard at 90% CPU, others idle.
  • hash % N placement. Symptom: adding a node requires moving nearly all data.
  • Cross-shard joins in request paths. Symptom: latency equal to the slowest shard, timeouts when any shard is degraded.
  • Changing shard key values (customer merges, merchant re-onboarding). Symptom: orphaned rows on old shards; design a move procedure.

Interview angle​

  • Prompts: "Your transactions table has 5 billion rows, what do you do?", "How would you shard a wallet system?", "What's your shard key for orders?", "How do you transfer money between users on different shards?"
  • A strong answer separates partitioning (maintenance, retention, pruning) from sharding (write scale), picks a key from access patterns and transaction boundaries, quantifies skew, and explains cross-shard transfers with a saga and a clearing account.
  • Mention operational reality: pre-creating partitions, retention mandated by regulation, resharding with logical shards, backups per shard, migrations across shards.
  • Follow-ups: "How do you look up an order by id if you shard by customer?" (embed shard in id, or lookup table), "What happens during a Black Friday spike on one merchant?" (sub-sharding, queueing, read model).
  • Red flags: "shard by created_at", sharding before partitioning and indexing, assuming cross-shard transactions are free, no plan for rebalancing.

Self-check​

1. Why must a Postgres partitioned table's primary key include the partition key?

Each partition has its own local index, and Postgres has no global index spanning partitions. Uniqueness can therefore only be enforced if any two rows with the same key are guaranteed to be in the same partition, which holds only when the key includes the partition columns.

2. A ledger_entry table partitioned by month is queried by WHERE id = $1. What happens and how do you fix it?

Without a filter on created_at, the planner cannot prune and probes the primary-key index of every partition, which grows slower as partitions accumulate. Fix by using ids that encode the timestamp (UUIDv7 or Snowflake) and deriving a time range for the query, adding created_at to the API that looks entries up, or keeping a lookup table from id to month.

3. Describe how to retire seven-year-old transaction data with minimal impact.

With monthly partitions, detach the oldest partition (DETACH PARTITION … CONCURRENTLY on Postgres 14+), export it to cheaper storage in an open format, verify counts and checksums, record the archive location for auditors, and then drop the table. This avoids the WAL, bloat and replica lag of a large DELETE. Confirm retention periods with compliance first.

4. Compare customer_id and account_id as shard keys for a retail bank.

customer_id co-locates all of a customer's accounts, so the customer overview, statements and own-account transfers are single-shard; P2P transfers to other customers are cross-shard. account_id distributes evenly but makes every transfer and every customer overview cross-shard unless accounts are co-located by customer anyway. Most designs choose customer (or a customer-derived prefix) and handle P2P transfers with sagas.

5. What does co-location mean in Citus, and why does it matter?

Tables distributed by the same column with the same shard count place rows with the same distribution value in the same shard on the same worker. Joins and transactions that filter by that value are then executed locally on one node, with no network hops or two-phase commit. Reference tables extend this by replicating small lookup tables to every node.

6. Why use 4,096 logical shards on 8 servers instead of 8 shards?

Rebalancing then means moving some logical shards to new servers and updating a mapping table, without changing the hash function or touching most data. With 8 shards hashed by modulo, adding a ninth server would remap most keys. Logical shards also let you isolate a hot shard on its own server.

7. Scenario: a payment from a customer on shard 3 to a merchant on shard 9 must never lose or create money. Design it.

On shard 3, in one transaction: debit the customer, credit an in-transit (clearing) account, and write an outbox event with a transfer id. A relay publishes the event; shard 9 consumes it and, in one transaction deduplicated by transfer id, debits the in-transit account mirror and credits the merchant. If shard 9 rejects permanently, a compensating transaction on shard 3 reverses the debit. Reconciliation verifies the in-transit account nets to zero over time.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Partition a ledger, prove pruning, and retire a month.

docker run --name pg-part -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-part psql -U postgres
  1. Create ledger_entry partitioned by month as above, with partitions for 12 months of 2025.
  2. Load 12 million rows spread across the year:
INSERT INTO ledger_entry (id, account_id, journal_id, amount_minor, currency, created_at)
SELECT g, (random() * 200000)::bigint, g / 2, (random() * 1000000)::bigint - 500000, 'VND',
timestamptz '2025-01-01' + (g::double precision / 12000000) * interval '364 days'
FROM generate_series(1, 12000000) g;
ANALYZE ledger_entry;
  1. Run EXPLAIN (ANALYZE, BUFFERS) for an account's November statement with and without the created_at range, and for WHERE id = 6000000. Count partitions scanned in each.
  2. Prepare the statement with the created_at bounds as parameters, run SET plan_cache_mode = force_generic_plan;, and find Subplans Removed in EXPLAIN ANALYZE EXECUTE …. Then reset the setting and see that Postgres prefers custom plans here.
  3. Detach January concurrently, export it with \copy … TO '/tmp/2025_01.csv' CSV, verify the row count, and drop it. Time the operation, then compare with DELETE of February's rows from a copy of the table, including WAL generated (pg_current_wal_lsn() before and after).
  4. Optional: start the citusdata/citus image, distribute customer, account and ledger_entry by customer_id with co-location, and compare EXPLAIN of a single-customer query with a query lacking customer_id.

Done when you can show pruning working and failing, and quantify the retention difference between detach and delete.

Further reading​

  • PostgreSQL documentation, "Table Partitioning": postgresql.org/docs/current/ddl-partitioning.html.
  • Citus documentation, "Choosing Distribution Column" and "Table Co-Location" (docs.citusdata.com).
  • Vitess documentation, "VSchema", "Vindexes" and "Resharding" (vitess.io).
  • Instagram Engineering, "Sharding & IDs at Instagram".
  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 6 "Partitioning".
  • Alex Xu, System Design Interview Vol. 1, chapters on consistent hashing and scaling.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).