Database Replication & Sharding
- Scale reads with replicas while guaranteeing read-your-writes for flows like "pay, then view payment status"
- Choose between vertical, functional and horizontal partitioning, and recognise when sharding is actually required
- Pick a shard key and a sharding strategy (range, hash, directory) for orders, accounts and multi-tenant data, and plan resharding
- Handle hotspots, cross-shard queries, cross-shard transactions and global secondary indexes
TL;DR
- Replicas scale reads, not writes. They lag; any flow that reads right after writing must go to the primary or wait for the replica to catch up (LSN/GTID tokens).
- Partition in increasing order of pain: table partitioning inside one DB → functional split (DB per domain) → sharding. Many systems never need the last step.
- A good shard key has high cardinality, spreads load evenly, matches the dominant access path so most queries hit one shard, never changes, and keeps entities that are updated together on the same shard.
- Range sharding keeps ranges scannable but hotspots on monotonic keys; hash spreads evenly but scatters range queries; directory is most flexible but adds a lookup dependency.
- Use many logical shards mapped onto few physical ones so resharding moves whole buckets instead of rehashing rows.
- Cross-shard queries become scatter-gather or move to a read model; cross-shard transactions become sagas. Global secondary indexes are a second write and usually eventually consistent.
Why it matters
- E-commerce: the orders table grows by millions of rows a day during sales; customer order history, merchant dashboards and order-status polling all hit it. Read replicas absorb browsing, but write growth and data size eventually push you to shard orders by customer, which immediately raises "how does the merchant see their orders?".
- Banking: after a transfer, the customer's next screen must show it — reading a lagging replica produces "transaction not found" and a second transfer attempt. Sharding a ledger by account means a transfer between two accounts may span shards, which turns a local ACID transaction into a distributed one. The shard key is a business-level decision.
- Interviews: "the database is the bottleneck, what now?" is a staple. Interviewers listen for whether you exhaust simpler options first, choose the shard key from access patterns, and know what you give up.
Core concepts
Read replicas and replication lag
- Asynchronous replication: the primary commits without waiting; replicas apply later. Lag is usually milliseconds but can grow to seconds or minutes under write bursts, long-running queries on the replica, network issues, or large transactions. On failover, unreplicated commits are lost (RPO above zero).
- Synchronous / semi-synchronous: the commit waits until at least one standby has received (or applied) the change. No loss on failover, at the cost of commit latency and availability coupling to the standby.
- Monitor lag continuously (
pg_stat_replicationreplay lag in PostgreSQL,Seconds_Behind_Sourceor GTID gaps in MySQL) and remove replicas from read rotation when lag exceeds a threshold.
Deeper treatment of replication topologies and failover is in Replication.
Read-your-writes and friends
Lag produces three classic anomalies:
| Guarantee | Anomaly without it | Typical fix |
|---|---|---|
| Read-your-writes | Customer pays, then the status page says "not found" | Route that user's reads to primary for a short window, or wait for an LSN/GTID token |
| Monotonic reads | Order shows "shipped", refresh shows "paid" (different replica, older) | Pin a session to one replica, or carry a minimum-version token |
| Consistent prefix | A reply appears before the message it answers | Keep causally related writes in one partition, or read from a consistent snapshot |
The most precise technique is a position token:
MySQL offers the same idea with GTIDs (WAIT_FOR_EXECUTED_GTID_SET). Simpler alternatives: "read from primary for 5 seconds after this user writes" (a flag in the session), or "always read payment status and balances from the primary" — often the right call in banking, because these reads are a small fraction of load.
Ways to partition
- Table partitioning inside one database (for example PostgreSQL declarative partitioning by month): smaller indexes, cheap retention by dropping old partitions, partition pruning. Not sharding — one server still does all the work — but often enough. See Partitioning & Sharding in Practice.
- Vertical partitioning: split a wide table by columns. Product
price,stockandstatus(hot, small, frequently updated) live apart fromdescription,specsand image metadata (large, rarely changing). Hot rows fit in memory; updates touch less data. - Functional partitioning: a database per domain — catalog, orders, payments, customers, ledger. Each scales and fails independently and aligns with service ownership (see Microservices Patterns). Cross-domain joins move into the application or into events.
- Horizontal partitioning (sharding): the same schema on many primaries, rows distributed by a shard key. The only option that scales writes and data size beyond one node.
Choosing a shard key
Ask, in this order:
- What are the dominant queries and transactions? The key should let them hit one shard.
- Is the cardinality high and the distribution even?
countryis a bad key (one shard gets 90%);customer_idis usually good. - Does it change? Moving a row between shards on update is painful; choose an immutable key.
- What must be atomic together? Entities in the same transaction should share a key.
- Is there a known heavy hitter? A marketplace's largest seller, a bank's payroll-processing corporate customer, a tenant with 40% of traffic.
| System | Candidate key | Good because | Watch out for |
|---|---|---|---|
| E-commerce orders | customer_id | Order history and checkout touch one shard | Merchant queries scatter; needs a merchant index |
| Marketplace merchant data | merchant_id | Merchant dashboard, payouts on one shard | Mega-sellers create hot shards |
| Bank accounts and ledger | customer_id | A customer's accounts and internal transfers stay local | Corporate customers with thousands of accounts |
| Bank ledger (alternative) | account_id | Even spread | Every transfer is cross-shard |
| Multi-tenant SaaS | tenant_id | Isolation, per-tenant moves | Big tenants need dedicated shards |
| Event / time series | (entity_id, time bucket) | Spreads writes, keeps per-entity scans local | Querying "all entities at time T" scatters |
Range, hash and directory sharding
| Strategy | Strengths | Weaknesses | Used by |
|---|---|---|---|
| Range | Efficient range scans, ranges can split and move dynamically | Sequential keys (time, auto-increment) hit the last range | Bigtable/HBase, CockroachDB, TiDB, MongoDB ranged sharding |
| Hash | Even distribution, no coordinator for routing | Range queries hit all shards; naive mod N remaps almost everything when N changes | Cassandra, DynamoDB partition keys, Citus hash distribution |
| Directory | Any placement policy, move individual tenants, isolate heavy hitters | Lookup on every request (cache it), directory must be highly available | Multi-tenant platforms, Vitess with lookup vindexes |
Logical shards. Instead of hash(key) mod physical_shards, hash into a fixed, large number of buckets (say 1,024 or 4,096), and keep a small map of bucket → physical cluster. Adding capacity moves whole buckets; the key → bucket function never changes. Redis Cluster's 16,384 hash slots and Vitess's keyspace-id ranges follow this idea. Consistent Hashing is another way to get minimal movement.
Resharding
Moving data while serving traffic is the hardest operational part of sharding:
- Tools such as Vitess (
Reshard,MoveTables) and distributed SQL databases automate this; with hand-rolled sharding you build the copy-stream-verify-cutover pipeline yourself. - Keep the write pause to seconds by catching up the stream first; make clients retry safely during it (idempotency keys).
- Rehearse it before you need it. The first resharding during a sales peak is how outages happen.
Hotspots
Even a perfect hash cannot spread load from a single key:
- Hot merchant / hot account: a top seller during a live-stream sale, or a bank's settlement or fee-income account touched by every transaction. Fixes: split the hot account into N sub-accounts (sub-ledgers) that are summed for reporting; batch postings to it asynchronously; or give the entity a dedicated shard via a directory.
- Monotonic keys on range shards: time-ordered ids all land in the newest range. Fixes: hash-prefix the key, or use hash sharding for write-heavy tables.
- Hot tenant: isolate onto its own shard; enforce per-tenant quotas (see Rate Limiting).
Cross-shard queries and joins
- Scatter-gather: query all shards in parallel and merge. Latency is the slowest shard's latency, and load multiplies by shard count. Acceptable for rare admin queries, not for hot paths.
- Denormalise: store
merchant_nameandproduct_titlein the order row so order history needs no join. - Reference tables: replicate small, slowly-changing tables (currencies, countries, fee schedules) to every shard.
- Co-location: shard related tables by the same key (orders, order_items and payments all by
customer_id) so joins stay local. - Read models: build reporting and cross-entity views in a separate store (warehouse, search index, CQRS projection) fed by CDC. See Event-Driven Architecture, CQRS & Event Sourcing.
- Cross-shard transactions: avoid by design; otherwise use a saga or a carefully scoped two-phase commit (see Distributed Transactions: 2PC, TCC, Saga). For a bank transfer across shards, a common pattern is to record the transfer and debit on the source shard, then post the credit asynchronously and idempotently, with reconciliation.
Global secondary indexes
If orders are sharded by customer_id, "orders for merchant M" has no local answer.
- Local secondary index: each shard indexes its own rows by
merchant_id. Writes stay local and consistent; the query must scatter to all shards. - Global secondary index: a separate table, itself sharded by
merchant_id, mappingmerchant_id → (order_id, customer_id). The query hits one index shard, then fetches orders by primary key. Each write now updates two shards, so the index is usually maintained asynchronously (via CDC or the outbox) and is eventually consistent — DynamoDB's GSIs, for example, are eventually consistent.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Async replicas | Cheap read scaling, no commit penalty | Lag, stale reads, RPO above zero on failover | Read-heavy, lag-tolerant reads |
| Sync / semi-sync standby | No data loss on failover | Commit latency, standby outage can stall writes | Ledgers, payments, orders |
| Read-from-primary for critical reads | Simple, correct | Primary load | Payment status, balances, post-write screens |
| LSN / GTID tokens | Precise read-your-writes on replicas | Plumbing through clients, replica checks | High read volume needing freshness |
| Functional split | Clear ownership, independent scaling | Cross-domain joins move to app/events | Before sharding |
| Hash sharding with logical buckets | Even load, painless rebalancing | Range queries scatter | Most OLTP sharding |
| Range sharding | Range scans, auto-splitting | Hotspots on monotonic keys | Time-ordered reads, distributed SQL |
| Directory sharding | Flexible placement, tenant isolation | Lookup dependency | Multi-tenant, heavy hitters |
| Global secondary index | Single-shard queries by secondary key | Extra writes, eventual consistency | Frequent queries on a non-shard key |
| Distributed SQL (CockroachDB, TiDB, YugabyteDB, Spanner) | Automatic sharding, distributed ACID | Higher write latency, new operational model, cost | Need horizontal writes and SQL transactions |
In practice
- Exhaust the cheap options first: indexes and query fixes, connection pooling, bigger instance, table partitioning, replicas, caching, functional split. A well-tuned PostgreSQL primary on modern hardware handles thousands of write TPS (rough).
- Pick sharding tech deliberately: Citus (PostgreSQL extension), Vitess (MySQL), application-level sharding with a router library, or distributed SQL. Application-level sharding gives full control and full responsibility.
- A router with logical shards in Go stays small:
package shard
import (
"context"
"database/sql"
"hash/fnv"
"math/rand/v2"
)
const LogicalShards = 1024 // fixed forever; only the placement map changes
type Cluster struct {
Primary *sql.DB
Replicas []*sql.DB
}
type Router struct {
placement [LogicalShards]int // logical shard -> index in clusters; loaded from config
clusters []*Cluster
}
func LogicalShard(customerID string) int {
h := fnv.New32a()
h.Write([]byte(customerID))
return int(h.Sum32() % LogicalShards)
}
func (r *Router) ForCustomer(customerID string) *Cluster {
return r.clusters[r.placement[LogicalShard(customerID)]]
}
// ReadDB returns a replica that has replayed at least minLSN, or the primary.
// In production, cache each replica's replay LSN for a few ms instead of
// querying it on every read.
func (c *Cluster) ReadDB(ctx context.Context, minLSN string) *sql.DB {
if len(c.Replicas) == 0 {
return c.Primary
}
if minLSN == "" {
return c.Replicas[rand.IntN(len(c.Replicas))]
}
for _, rep := range c.Replicas {
var caughtUp bool
err := rep.QueryRowContext(ctx,
"SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn", minLSN).Scan(&caughtUp)
if err == nil && caughtUp {
return rep
}
}
return c.Primary
}
- Shard-aware ids: embedding the logical shard in the id (as Instagram's and some Snowflake variants do) lets you route by id alone. See Unique ID Generation.
- Plan the merchant (or back-office) view on day one: if you shard orders by customer, decide immediately whether merchants are served by a GSI, a search index or a warehouse.
Common pitfalls
- Reading your own write from a replica. Symptom: "payment not found" right after success; duplicate submissions.
- Replicas silently lagging minutes behind. Symptom: stale order statuses during peak, because analytics queries on the replica block replay. Fix: lag-aware routing and separate analytics replicas.
hash mod Nwith physical shard count. Symptom: adding one shard requires moving almost every row.- Shard key from the wrong access path. Symptom: the main screen is a scatter-gather across 32 shards; p99 latency is the slowest shard's p99.
- Ignoring heavy hitters. Symptom: one shard at 95% CPU, the rest at 20%, during a big seller's live sale.
- Cross-shard transactions without a saga. Symptom: debits without credits after partial failures; reconciliation breaks.
- Auto-increment ids per shard. Symptom: id collisions when data is merged or moved. Use globally unique ids.
- Unrehearsed resharding. Symptom: a multi-hour write freeze or data mismatch the first time you do it.
Interview angle
- Where it appears: every design with growing data; explicitly in "design an order system", "design a ledger", "design Twitter", "design a multi-tenant SaaS".
- Strong answer covers: estimated write load and data size that justify (or not) sharding; replicas with a read-your-writes plan; shard key chosen from access patterns with heavy hitters considered; strategy (usually hash with logical buckets); how secondary access paths are served; how cross-shard transactions are avoided or handled; how resharding works.
- Follow-ups: "A customer just paid — which DB serves the next screen?", "How do merchants query their orders?", "What happens when one seller is 30% of traffic?", "How do you add shards without downtime?", "Transfer between two accounts on different shards?"
- Red flags: sharding before replicas and caching, choosing a shard key without discussing queries, unaware of replication lag,
mod Nwithout a rebalancing story, assuming cross-shard joins are free.
Self-check
1. Name three ways to guarantee read-your-writes with async replicas and their costs.
- Read from the primary for critical reads or for a window after a user writes — simple, adds primary load.
- Pass an LSN/GTID token from the write and read from a replica only once it has replayed past it — precise, requires plumbing and replica position checks.
- Pin a session to the primary (or to one replica for monotonic reads) — easy, reduces load spreading.
2. You must shard a bank's ledger. Compare customer_id and account_id as shard keys.
customer_id co-locates all of a customer's accounts, so their statements and transfers between their own accounts are single-shard and ACID; but corporate customers with huge volumes create hot shards, and transfers to other customers still cross shards. account_id spreads load more evenly but makes nearly every transfer cross-shard, requiring sagas or async credit posting. Most designs prefer customer_id (or a customer-group key) with heavy hitters isolated via a directory.
3. Why use 1,024 logical shards on 8 physical clusters instead of hashing directly onto 8?
The key → logical shard mapping never changes, so rows are never rehashed. To add capacity you move whole logical shards between clusters and update a small placement map. With direct mod 8, going to 9 clusters would remap almost every key.
4. Orders are sharded by customer_id. How do you serve a merchant dashboard listing their recent orders?
Maintain a global secondary index sharded by merchant_id, fed asynchronously by CDC or the outbox, then fetch order details by id from the order shards — accepting a small staleness window. Alternatives: a search index or an analytics store for the dashboard. Scatter-gather across all shards works only for low traffic.
5. What causes replication lag spikes, and how do you protect users from them?
Write bursts larger than replay throughput, long-running queries on replicas conflicting with replay, large transactions, replica resource saturation, and network issues. Protect users with lag monitoring that removes lagging replicas from rotation, read-your-writes routing for post-write flows, separate replicas for analytics, and always-primary reads for money-critical screens.
6. Scenario: one marketplace seller generates 30% of order writes during a live-stream sale. Hash sharding by merchant_id puts them on one shard. Options?
Give that merchant a dedicated shard via a directory entry; or sub-shard the merchant by (merchant_id, hash(order_id) mod k) so their writes spread across k shards, with the merchant view assembled from k shards; or shard orders by customer_id instead (buyers are many) and serve merchant views from a GSI. Also queue and batch secondary writes (stats, counters) for that merchant.
Exercise
- Run PostgreSQL with one primary and one streaming replica (Docker Compose). Insert a row on the primary and immediately read it from the replica in a tight loop; measure how often it is missing under a write load generated by
pgbench. - Implement the LSN-token read path from the Go snippet and show that it never returns "not found" after a successful write.
- On paper, shard an e-commerce order platform for 50 M orders/month: choose the key, the number of logical shards, the merchant-view strategy, and write the resharding runbook in seven steps.
Done looks like: a measured miss rate before/after, and a one-page sharding design with a justification for each choice.
Further reading
- Designing Data-Intensive Applications (Martin Kleppmann), Ch. 5 "Replication" and Ch. 6 "Partitioning".
- Database Internals (Alex Petrov), Part II on distributed systems and replication.
- PostgreSQL documentation: "High Availability, Load Balancing, and Replication" and the
pg_lsnfunctions. - Vitess documentation: sharding, vindexes, resharding workflows (vitess.io).
- Instagram Engineering, "Sharding & IDs at Instagram" (2012).
- Corbett et al., "Spanner: Google's Globally-Distributed Database" (OSDI 2012).
Related
- Replication — topologies, failover and quorum details.
- Partitioning & Sharding in Practice — hands-on PostgreSQL partitioning and sharding tools.
- Consistent Hashing — minimal-movement key placement.
- Distributed Transactions: 2PC, TCC, Saga — when a transaction must span shards.
- Consistency Models — read-your-writes, monotonic reads, and stronger guarantees.
- Double-Entry Ledger Design — shard keys and hot accounts in a ledger.
- E-commerce Order Platform — sharding orders end to end.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).