DB·61
Scaling Databases
How to grow a database past one server. Covers the scaling ladder (query and index work, vertical scaling, connection pooling, caching, read replicas, partitioning, sharding), replication lag and read-your-writes, split brain and fencing, write scaling, sharding strategies and shard-key choice, rebalancing, hot partitions, cross-shard queries and transactions (2PC versus sagas), CQRS and materialised views, and the managed and distributed-SQL options (Aurora, Citus, Vitess, CockroachDB, Spanner, YugabyteDB, TiDB).
Start here: when one database isn't enough
Climb the ladder one rung at a time
"How do we scale the database?" usually gets answered with the most dramatic option first: shard it, or switch to a distributed database. In practice, each step up the scaling ladder costs more complexity than the one before, and most systems never need the top rungs:
| Rung | What you do | Buys you | Costs |
|---|---|---|---|
| 1. Optimise | Indexes, better queries, fewer round trips (chapter 60) | Often 10–1,000× on the slow queries | Engineering time |
| 2. Bigger machine | More CPU, RAM, faster disks | Single servers reach 100+ cores and terabytes of RAM | Money; a ceiling eventually |
| 3. Connection pooling | PgBouncer or an application pool | Thousands of clients on a few hundred connections | A component to run |
| 4. Caching | Redis or in-process caches for hot reads (Volume 3 chapter 53) | Offloads repeated reads | Staleness, invalidation |
| 5. Read replicas | Send reads to copies kept current by replication | Scales read throughput | Replication lag: stale reads |
| 6. Partitioning | Split big tables into pieces on one server | Cheap retention, smaller indexes, pruning | Partition key in every query; more objects |
| 7. Functional split | Separate databases per service or domain | Independent scaling and failure | No joins or transactions across them |
| 8. Sharding | Split one table's rows across many servers by key | Scales writes and storage nearly without limit | Cross-shard queries and transactions, rebalancing, operations |
A single well-tuned PostgreSQL server handles tens of thousands of transactions per second and several terabytes; that covers the large majority of products. The lab measures what some of the higher rungs actually cost.
Replicas: copies for reading and for surviving failures
A replica receives the primary's write-ahead log and replays it (chapter 57), so it holds a nearly current copy. Replicas serve two purposes:
- Read scaling: route reporting and read-heavy endpoints to replicas. They're eventually consistent with the primary: chapter 57's lab saw a replica a fraction of a millisecond behind still return stale data for 199 of 200 immediate reads.
- High availability: if the primary fails, promote a replica to be the new primary. With asynchronous replication, commits the primary acknowledged but hadn't yet sent are lost on failover; in the lab, a one-second network stall before the primary died lost 358,000 acknowledged payments. Synchronous replication waits for a replica to confirm before acknowledging a commit: no loss, at the cost of latency on every write and of availability if the replica is unreachable. Tools like Patroni automate detection, promotion and fencing (making sure the old primary can't keep accepting writes, the "split-brain" problem).
Partitioning: many smaller tables that look like one
CREATE TABLE ev_part (id bigint, at timestamptz NOT NULL, kind text, payload text) PARTITION BY RANGE (at);
CREATE TABLE ev_2025_01 PARTITION OF ev_part FOR VALUES FROM ('2025-01-01') TO ('2025-02-01');
… one per month …
Queries see one table; PostgreSQL routes each row to its partition and prunes partitions a query can't touch (a one-month query read 1 of 12). The biggest win is data lifecycle: deleting a month of events from a plain table took 718 ms and left 669,599 dead rows for VACUUM to clean; dropping that month's partition took 85 ms and left nothing.
Sharding: many databases that act as one
Sharding spreads one logical table across several database servers, each holding the rows for a subset of keys (for example, hash(customer_id) decides which server holds a customer and all their orders). Each shard is an ordinary database, so writes scale with the number of shards. The costs are why it's the last rung:
- Queries that don't include the shard key must ask every shard and merge the answers.
- Transactions spanning shards lose ACID guarantees unless you add distributed commit protocols (Volume 5).
- Rebalancing: with the naive
hash(key) mod N, adding a fifth shard to four moves 80% of all data; consistent hashing moves only the necessary 20% (lab experiment 3). - Every operational task (backups, migrations, upgrades) multiplies by the number of shards.
Distributed SQL databases (CockroachDB, YugabyteDB, TiDB, Spanner) and extensions like Citus automate sharding, rebalancing and distributed transactions, trading some latency and operational simplicity of a single node for that.
How deep to go in scaling databases
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name the scaling ladder's rungs and what each buys |
| L2 | Use pooling, read replicas and partitioning correctly in an application |
| L3 | Explain replication modes, failover and fencing, partition pruning, sharding schemes and rebalancing |
| L4 | Diagnose replica lag, data loss risks, partition-less queries, hot shards and pool exhaustion |
| L5 | Choose and design a scaling and high-availability architecture with RPO and RTO targets |
| L6 | Operate sharded or distributed databases and their migrations at scale |
The scaling ladder
Climb in order
Each step up this ladder adds operational complexity, so take the cheapest step that solves the problem:
- Fix queries and indexes (chapter 60). Most "we need to scale the database" problems are a missing index or an N+1 pattern.
- Vertical scaling: modern servers have 100+ cores, terabytes of RAM and millions of NVMe IOPS. A single well-tuned PostgreSQL or MySQL instance handles tens of thousands of transactions per second and multi-terabyte datasets. It's the simplest scaling there is, and its limit is further away than people think.
- Connection pooling: protects the database from too many connections (chapter 57).
- Caching: removes repeated reads (Vol. 3 ch. 53).
- Read replicas: scale reads (below).
- Partitioning and archiving cold data: keep hot data small (chapter 57).
- Functional split: separate databases per domain or service (orders, catalogue, analytics). Each gets its own capacity, and cross-domain joins move to the application or to events (Vol. 5).
- Sharding / distributed SQL: scale writes and data size beyond one machine.
Scaling reads
Read replicas
Replicas receive the primary's changes (streaming WAL or binlog, chapter 57) and serve read-only queries:
writes ┌──────────┐ WAL ┌───────────┐
app ───────────────▶ │ primary │ ──▶ │ replica 1 │ ◀── reads (reports, search pages, exports)
reads (some) ──▶ └──────────┘ ──▶ │ replica 2 │ ◀── reads
└───────────┘
Routing reads to replicas:
- Application-level: two data sources ("writer" and "reader"). In Spring, an
AbstractRoutingDataSourcekeyed by@Transactional(readOnly = true)(withLazyConnectionDataSourceProxy). In Go, separate*sql.DBpools. In Rails,connects_to. In Django, database routers. In EF Core, separate contexts. - Proxy-level: ProxySQL (MySQL), Pgpool-II, AWS RDS Proxy reader endpoints, Aurora reader endpoints (load-balanced across replicas), and cloud read endpoints.
- Driver-level: the PostgreSQL JDBC
targetServerType=preferSecondaryand the libpqtarget_session_attrs=prefer-standby(multi-host connection strings).
What replicas are good for: read-heavy workloads (catalogue browsing, feeds), isolating heavy analytical queries and exports from OLTP traffic, and geographic read locality. They don't help write throughput (every replica applies every write), and they add replication lag.
Replication lag
With asynchronous replication (the default), replicas trail the primary by milliseconds normally, and by seconds or minutes under load, during long-running transactions, during big DDL or batch updates, or when a replica is too small to keep up. Lag causes visible anomalies:
Consistency guarantees to design for (Vol. 5 formalises them):
- Read-your-writes: a user sees their own updates.
- Monotonic reads: a user never sees time go backwards (stick a session to one replica, or check positions).
- Consistent prefix: causally related writes appear in order.
Monitoring lag: PostgreSQL pg_stat_replication (write_lag, flush_lag, replay_lag) on the primary, and now() - pg_last_xact_replay_timestamp() on replicas (misleading when there are no writes). MySQL SHOW REPLICA STATUS (Seconds_Behind_Source, which is famously imprecise, so use heartbeat tables such as pt-heartbeat). Alert on lag, and take lagging replicas out of rotation automatically.
High availability
Failover and split brain
When the primary fails, a replica is promoted. The hard problems:
- Detection: is the primary dead, or just slow or partitioned from the monitor? False positives cause unnecessary failovers. Use timeouts plus multiple observers.
- Data loss: with async replication, transactions committed on the old primary but not yet replicated are lost on failover (RPO > 0). Synchronous replication (quorum
ANY 1 (…)) avoids it at a latency cost. - Split brain: the old primary isn't actually dead (a network partition), keeps accepting writes, and now two primaries diverge. Merging them afterwards is painful or impossible. Prevention:
- Consensus-based leadership: Patroni stores the leader key in etcd, Consul or ZooKeeper with a TTL. A primary that can't renew its lease demotes itself. Kubernetes operators (CloudNativePG) use the API server similarly.
- Fencing: make sure the old primary can't write. STONITH ("shoot the other node in the head") powers it off or detaches its storage, and network fencing removes it from the virtual IP or load balancer.
- Quorum: only a side with a majority of voters can elect a primary (Vol. 5's Raft and Paxos).
- Client redirection: DNS or virtual IP changes, proxies (HAProxy with Patroni's REST health checks), multi-host connection strings, or managed endpoints. Clients must reconnect and retry in-flight transactions. Make writes idempotent (Vol. 3 ch. 45).
Managed services (RDS Multi-AZ, Aurora, Cloud SQL HA, Azure Flexible Server zone-redundant HA, AlloyDB) handle most of this for you, with typical failover times from about 30 seconds to a couple of minutes (Aurora is often faster). Test failover regularly: application behaviour during failover (connection storms, retries, stale DNS caches in the JVM, networkaddress.cache.ttl) is where outages happen.
Scaling writes
Write scaling
Writes are harder than reads because every write must land on the authoritative copy. Options short of sharding:
- Make writes cheaper: fewer indexes (chapter 58), HOT-friendly updates, batching and
COPYfor bulk loads, smaller rows, avoiding write amplification from triggers, and async commit where acceptable. - Absorb bursts with queues: decouple request spikes from write throughput (Vol. 3 ch. 51).
- Move data out: event or log data to append-optimised stores (Kafka, ClickHouse, object storage), and counters to Redis with periodic flushes (write-behind, with the stated risks).
- Vertical scaling: faster storage helps WAL fsync throughput and checkpoint I/O.
- Functional split: separate write-heavy domains onto separate databases.
When one primary's write capacity or storage really isn't enough, you need sharding: multiple independent primaries, each owning part of the data.
Partitioning versus sharding
| Partitioning (chapter 57) | Sharding | |
|---|---|---|
| Where | One server, one database | Many servers (each shard is a full database with its own primary and replicas) |
| Transparency | Fully transparent to SQL | Needs routing: in the app, a proxy, or a distributed database |
| Goal | Manageability, pruning, retention | Write throughput, data size, isolation (blast radius, tenant isolation) |
| Cross-partition queries and transactions | Normal SQL, ACID | Expensive or unsupported: scatter-gather queries, distributed transactions |
Sharding strategies
The shard key decides which shard owns a row. It's the most consequential decision in a sharded system:
| Strategy | Mapping | Pros | Cons |
|---|---|---|---|
| Range | Key ranges → shards (A–F, G–M…, or time ranges) |
Range scans stay on one shard; easy to split ranges | Hot spots: sequential keys (timestamps, auto-increment) send all new writes to the last shard |
| Hash | hash(key) mod N → shard |
Even distribution | Range queries scatter to all shards; changing N remaps almost every key (unless you use consistent hashing or fixed virtual shards) |
| Consistent hashing | Keys and nodes on a hash ring; a key belongs to the next node clockwise; nodes own many virtual nodes | Adding a node moves only ~1/N of keys | Uneven load without many vnodes; used by Dynamo-style stores (Cassandra, DynamoDB internally, Riak) |
| Fixed virtual shards (logical shards) | Hash into, say, 4,096 fixed logical shards, each mapped to a physical server through a lookup table | Rebalancing moves whole logical shards without rehashing keys; very common in practice (Vitess, Citus shard groups, Instagram's scheme) | Needs the mapping and a move procedure |
| Directory / lookup | A lookup service maps key → shard | Full flexibility (move single tenants, place by size or region) | The directory is a dependency (cache it) |
| Geo / tenant | By region or customer | Data residency, locality, tenant isolation | Uneven tenant sizes; "whale" tenants need their own shards |
Choosing the shard key:
- High cardinality and an even distribution of both data and load.
- Most queries should include it, so they route to one shard. That usually means the key that scopes your access patterns: tenant ID for B2B SaaS, user ID for consumer apps, order ID only if you never query across a customer's orders.
- Co-locate related data: shard child tables by the same key (orders, order lines and payments all by
tenant_id), so joins and transactions stay on one shard. Citus calls this "co-location"; Vitess calls it the same keyspace ID. - Avoid monotonic keys for range sharding (hot last shard), or hash them.
- Think about future growth and whales: the largest tenant must still fit on one shard, or need sub-sharding.
Rebalancing
Shards grow unevenly, and you add servers. Rebalancing moves data while the system keeps running:
- Copy the shard's data to the new server: a snapshot plus streaming changes (logical replication or CDC).
- Catch up until the lag is near zero.
- Cut over: briefly block writes for that shard, apply the final changes, switch routing, then unblock.
- Clean up the old copy.
Tools: Vitess MoveTables/Reshard, Citus shard rebalancer (citus_rebalance_start), CockroachDB, TiDB and YugabyteDB (automatic range splitting and rebalancing), MongoDB's balancer (moving chunks), and Cassandra's token-range streaming. Rebalancing competes with production traffic for I/O and network, so throttle it.
Hot partitions
Even with a good key, load can concentrate:
- Hot keys: a celebrity user, a viral product, a "global" counter row. Every write to one row serialises on that row's lock and that shard.
- Hot ranges: time-based keys put all new writes on the newest range.
- Whale tenants: one customer is half the traffic.
Mitigations:
- Split hot counters into N sub-counters (
likes:post42:shard{0..15}), summed on read. - Add randomness to hot keys (a salt prefix), at the cost of scatter reads.
- Isolate whales on dedicated shards.
- Cache reads of hot rows, and queue and batch writes to them.
- Use adaptive capacity features (DynamoDB redistributes throughput to hot partitions automatically, within limits).
Cross-shard queries and transactions
Once data is sharded, operations spanning shards get expensive:
- Cross-shard queries (scatter-gather): the router sends the query to every relevant shard and merges results (sorting, limits and aggregates combined at the coordinator). Latency is the slowest shard's, and load multiplies by the shard count. Keep them off hot paths, or serve them from a separate read model (a search index, analytics store or CQRS projection) built from all shards.
- Global uniqueness (a unique email across shards): a separate lookup table or service, or include the shard key in the unique constraint.
- Cross-shard transactions have two families of solutions:
- Two-phase commit (2PC): a coordinator asks every participant to prepare (durably promise to commit), then tells all to commit. It's atomic, but participants hold locks during the coordinator round trips, and a coordinator failure between phases leaves participants blocked in doubt. PostgreSQL supports it (
PREPARE TRANSACTION, used by Citus), as do XA in MySQL and Java's JTA. Use it sparingly. - Sagas: a sequence of local transactions with compensating actions on failure (Vol. 3 ch. 51, Vol. 5). There's no global atomicity, so intermediate states are visible, but there's no blocking either. This is the usual choice across services.
- Distributed SQL databases (below) implement distributed transactions internally with consensus-replicated ranges and timestamp ordering, making cross-shard ACID transparent at a latency cost.
The best design minimises cross-shard operations by choosing the shard key so that almost every transaction touches one shard.
Splitting reads from writes
CQRS and materialised views
CQRS (Command Query Responsibility Segregation) separates the write model (normalised, constraint-heavy, optimised for correctness) from one or more read models (denormalised, shaped per query, optimised for speed):
- Read models can live in the same database (summary tables, materialised views) or in specialised stores (search, cache, column store, graph).
- They're derived and rebuildable from the source of truth (replay events or re-run CDC from a snapshot).
- They're eventually consistent: design the UI for it ("your order is being processed").
- CQRS doesn't require event sourcing (Vol. 5), though they combine well.
Materialised views are CQRS inside the database:
CREATE MATERIALIZED VIEW merchant_daily_sales AS
SELECT merchant_id, date_trunc('day', created_at) AS day, count(*) AS orders, sum(total_cents) AS revenue
FROM orders WHERE status IN ('PAID', 'SHIPPED')
GROUP BY 1, 2;
CREATE UNIQUE INDEX ON merchant_daily_sales (merchant_id, day); -- required for CONCURRENTLY
REFRESH MATERIALIZED VIEW CONCURRENTLY merchant_daily_sales; -- doesn't block readers; recomputes everything
PostgreSQL materialised views are refreshed in full (there's no built-in incremental maintenance; extensions like pg_ivm add it). For large data, maintain summary tables incrementally (in the same transaction, with triggers, or from CDC) or use TimescaleDB continuous aggregates. Oracle (fast refresh with MV logs), SQL Server (indexed views, maintained synchronously) and ClickHouse (materialised views that transform inserts as they arrive) have richer incremental options.
Options in the market
Managed and distributed SQL
| System | Architecture | Notes |
|---|---|---|
| Amazon Aurora (PostgreSQL/MySQL compatible) | Compute separated from a distributed, 6-way replicated storage layer (log-structured: only WAL is shipped). Replicas share the storage, so lag is typically milliseconds | Fast failover; up to 15 replicas; still a single writer (Aurora Limitless adds sharding); Aurora DSQL is a distributed serverless option |
| Google AlloyDB / Cloud SQL, Azure Database for PostgreSQL, Neon (serverless, branching, separated storage) | Managed PostgreSQL; several separate storage from compute | Branching databases for development (Neon) is a distinctive feature |
| Citus (an extension; Azure Cosmos DB for PostgreSQL) | Coordinator + workers; distributed tables sharded by a distribution column, reference tables replicated everywhere, co-location | Real PostgreSQL with sharding; excellent for multi-tenant SaaS and real-time analytics |
| Vitess (MySQL; PlanetScale) | A proxy layer (VTGate) routing to sharded MySQL (VTTablet); online resharding | Scaled YouTube; powers PlanetScale |
| CockroachDB | Data split into ranges replicated by Raft; serializable by default; PostgreSQL wire protocol | Multi-region with locality controls; survives node, zone and region failures |
| Google Spanner | TrueTime (GPS and atomic clocks) for external consistency; Paxos-replicated splits | Strictly serialisable globally; PostgreSQL interface available |
| YugabyteDB | Reuses PostgreSQL's query layer on a Raft-based distributed storage (DocDB) | High PostgreSQL compatibility |
| TiDB | MySQL-compatible SQL layer + TiKV (Raft, RocksDB) + TiFlash columnar replicas | HTAP |
Distributed SQL trade-offs: every write goes through consensus (one or more cross-zone or cross-region round trips), so latency is higher than a single-node database (milliseconds to tens of milliseconds). Some PostgreSQL or MySQL features differ or are missing. Schema design must consider data placement (for example, avoiding sequential primary keys that create hot ranges: use UUIDs or hash-sharded indexes). They pay off when you need horizontal write scaling, multi-region writes or region survival. For most applications, a well-run single primary plus replicas goes a very long way. (Vol. 5 covers consensus, clocks and replication theory.)
Lab: partitions, shards and failover
PostgreSQL 16 on a 2-core machine; a streaming replica on the same machine (pg_basebackup -R -X stream -C -S replica1); a Python simulation for shard placement.
Experiment 1: partitioning by month
7.8 million events across 2025, in a plain table and in a table partitioned by month, both with an index on the timestamp:
load: flat 10,430 ms | partitioned by month 12,575 ms
one month's events from ev_flat: 147 ms
one month's events from ev_part: 135 ms (plan touches 1 of 12 partitions)
retire January: DELETE from flat table 718 ms (and leaves ~669,599 dead rows for VACUUM) | DETACH + DROP partition 85 ms
Partitioning cost 20% more on load (routing each row) and barely changed the indexed one-month query: an index range scan on the flat table was already reading only that month. The win was retention: dropping a partition is a metadata operation that frees the space immediately, while DELETE wrote 669,599 dead row versions that VACUUM must later clean and WAL must ship to replicas. Partition when you have a clear lifecycle key (time) and very large tables, or when per-partition maintenance (vacuum, index rebuilds) becomes too slow; don't expect it to speed up queries that indexes already serve, and remember that queries without the partition key must check every partition.
Experiment 2: a replica without a slot
The replica from chapter 57's lab was stopped while the primary kept working, then restarted:
FATAL: could not receive data from WAL stream: ERROR: requested WAL segment 000000010000000200000001 has already been removed
LOG: waiting for WAL to become available at 2/1002000
While the replica was down, the primary recycled WAL files the replica still needed (it keeps only max_wal_size / wal_keep_size worth by default), so the replica could never catch up and had to be rebuilt from a new base backup. A replication slot makes the primary retain WAL until the replica has consumed it; the replica was rebuilt with one. The opposite risk follows: a slot whose replica is gone forever retains WAL until the primary's disk fills. Monitor pg_replication_slots (active, retained bytes) and set max_slot_wal_keep_size.
Experiment 3: placing keys on shards
100,000 customers, from 4 shards to 5:
hash(key) mod N, 4 → 5 shards: 80.1% of 100,000 customers must move
consistent hashing (100 virtual nodes per shard), 4 → 5 shards: 19.9% move (ideal 20%)
load per shard with 1 virtual node(s) each: [1741, 26305, 26985, 44969]
load per shard with 100 virtual node(s) each: [23820, 24947, 25142, 26091]
With modulo placement, changing N changes almost every key's shard: adding capacity means moving most of the data. Consistent hashing places shards and keys on a ring, and each key belongs to the next shard clockwise; adding a shard takes over only its slice. With one point per shard the slices were badly uneven (one shard had 26× another's load); 100 virtual nodes per shard evened them out to within ±5%. Production systems use variants: Cassandra and DynamoDB use rings with virtual nodes; Citus, Vitess and most distributed SQL databases use many fixed small shards (or key ranges) that are moved between servers as whole units.
Experiment 4: failover and data loss
Four clients insert payments in batches of 200 into the primary, each batch committed and acknowledged. Then the network to the replica stalls for one second (its WAL receiver is paused), the primary is killed (pg_ctl stop -m immediate, like a power failure), and the replica is promoted:
first run (no stall), primary killed mid-load: 817,200 payments acknowledged; promoted replica has 817,200; acknowledged but LOST: 0; promotion took 591 ms
replica's network stalled 1 s, then primary killed: 601,200 payments acknowledged by the old primary; promoted replica has 243,200;
acknowledged but LOST: 358,000; promotion took 291 ms
On a healthy local network the replica was effectively current and nothing was lost, which is why asynchronous replication looks safe in testing. One second of replication delay at the wrong moment, a routine event on real networks, lost 358,000 payments the application had told users were successful. That window is your RPO (recovery point objective). Options: synchronous replication to at least one replica (synchronous_standby_names, synchronous_commit = on/remote_apply), which bounds the loss to zero at the cost of write latency; or accept a bounded loss for less critical data and reconcile from upstream sources (payment provider records). Promotion itself took under a second; the real downtime in production is detection, fencing and reconnecting clients, typically tens of seconds with Patroni or a managed service.
Try it yourself
- Configure
synchronous_standby_names = 'replica1'and rerun experiment 4. What happens to the primary's write throughput, and to writes while the replica is paused? - Add a
DEFAULTpartition to experiment 1's table and insert a 2026 event. Why is a default partition a trap when you later add the 2026 partitions? - Extend experiment 3 to simulate a hot key (one customer with 10% of all traffic) and measure per-shard load. How would you split it?
- Put PgBouncer in transaction-pooling mode in front of PostgreSQL and run pgbench with 500 clients against
max_connections = 100.
Revision sheet: scaling databases
Key ideas
- Ladder: optimise → scale up → pool → cache → read replicas → partition → split by function → shard; climb only on measured need.
- Replication: physical streaming (async, sync, quorum), logical replication; lag and read-your-writes; slots and WAL retention.
- High availability: RPO (how much data you can lose) and RTO (how long you can be down); automated failover (Patroni, cloud managed services), fencing, split-brain, connection routing (VIPs, proxies, DNS).
- Partitioning: range/list/hash, pruning, per-partition indexes, retention by detach/drop, partition key in unique constraints.
- Sharding: shard key choice (high cardinality, even distribution, co-location of related data), hash vs range, directory-based placement, consistent hashing and virtual nodes, hot keys, resharding, cross-shard queries and transactions.
- Systems: Citus, Vitess (MySQL), distributed SQL (CockroachDB, YugabyteDB, TiDB, Spanner), managed scale-out (Aurora, AlloyDB, Neon's separated storage).
- CQRS and read models: separate read stores fed by events or CDC when read shapes diverge from the write model.
Numbers to remember
- Lab: dropping a month partition 85 ms vs DELETE 718 ms plus 669,599 dead rows; mod-N resharding moved 80% of keys vs 20% with consistent hashing; one virtual node per shard gave 26× load imbalance; a 1-second replication stall before failover lost 358,000 acknowledged payments.
Pitfalls
- Sharding before optimising; choosing a shard key that isn't in most queries.
- Reading from replicas without lag awareness; assuming async replication loses nothing.
- Replication slots for dead replicas filling disks; replicas without slots falling irrecoverably behind.
- Failover without fencing; clients pinned to the old primary.
- Partitioning without a lifecycle need; queries missing the partition key; default partitions.
Glossary
- RPO / RTO: recovery point / time objective.
- Fencing: guaranteeing a failed primary can't accept writes.
- Partition pruning: skipping partitions a query can't need.
- Shard key: the value deciding which shard holds a row.
- Virtual node: one of many ring positions per physical shard.
- Scatter-gather: querying all shards and merging results.