SD/Lesson 4 of 8/6 min read
Databases at Scale
SQL vs NoSQL choice, replication (leader-follower, multi-leader, leaderless), replication lag, sharding strategies, consistent hashing, hotspots, federation and object storage.
On this page
Choosing a database
| Need | Lean towards |
|---|---|
| Transactions, joins, strict schema, integrity | Relational (Postgres, MySQL) |
| Flexible documents, nested data | Document store (MongoDB) |
| Very high write throughput, wide rows, time series | Column-family (Cassandra, ScyllaDB) |
| Simple lookups by key at huge scale | Key-value (DynamoDB, Redis) |
| Relationship-heavy queries | Graph (Neo4j) |
| Full-text search | Search engine (Elasticsearch, OpenSearch) |
Start with a relational database unless a requirement rules it out. A single well-indexed Postgres instance handles far more than most products need. See NoSQL for the data models.
Replication
Replication keeps copies of the same data on multiple nodes for availability, durability and read scaling.
Leader-Follower Replication
One leader (primary) accepts writes and streams changes (its WAL or binlog) to followers (replicas).
writes ──▶ leader ──▶ follower 1 ◀── reads
──▶ follower 2 ◀── reads- Synchronous: the leader waits for a follower to confirm. No data loss on failover, but a slow follower stalls writes.
- Asynchronous: the leader confirms immediately. Fast, but the newest writes are lost if the leader dies.
- Semi-synchronous: one follower is synchronous, the rest asynchronous. A common compromise.
Failover: detect the dead leader, promote the most up-to-date follower, repoint clients. Danger: split brain, two nodes both believing they are leader. Prevent with fencing tokens or a consensus-based coordinator.
Read Replica
A read replica is a follower used to serve reads. Great for read-heavy workloads (10:1 or more), but it serves slightly stale data.
Replication Lag
Asynchronous followers trail the leader by milliseconds to minutes. Problems and fixes:
| Anomaly | Example | Fix |
|---|---|---|
| Read-your-writes | User edits profile, refresh shows old value | Read own data from leader for a short window |
| Monotonic reads | Refreshing shows new then old data | Pin each user to one replica |
| Consistent prefix | Answer appears before question | Keep causally related writes on one partition |
Multi-Leader Replication
Several leaders accept writes (typically one per datacenter) and replicate to each other.
- Low write latency in every region, survives a datacenter outage.
- Write conflicts: two leaders change the same row. Resolve with last-write-wins (loses data), merge functions, or CRDTs.
Leaderless Replication
Any replica accepts reads and writes (Dynamo, Cassandra). With N replicas, a write goes to W nodes and a read queries R nodes.
- If W + R > N, read and write sets overlap, so reads see the latest write (a quorum). Common: N=3, W=2, R=2.
- Repair stale replicas with read repair and background anti-entropy (Merkle trees).
- Sloppy quorum and hinted handoff keep accepting writes during partitions.
Sharding
Sharding (horizontal partitioning) splits a dataset across multiple databases so each holds a subset of the rows. Needed when data or write throughput outgrows one machine.
Shard Key
The shard key decides which shard a row lives on. A good key:
- Spreads data and traffic evenly (high cardinality, no celebrity values).
- Keeps data that is queried together on one shard (all of a user's orders on the user's shard).
Strategies
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Range | user_id 1-1M on shard 1, ... | Range scans are efficient | Hotspots on recent or popular ranges |
| Hash | hash(key) mod N | Even distribution | Range queries hit all shards; resizing remaps almost everything |
| Consistent hash | Hash ring | Resizing moves ~1/N of keys | More complex |
| Directory | Lookup table maps key to shard | Fully flexible | Lookup service is a dependency and SPOF |
| Geo | By region | Data locality, compliance | Uneven regional sizes |
Problems sharding introduces
- Cross-shard joins become application-level fan-out queries. Denormalize to avoid them.
- Cross-shard transactions need two-phase commit or sagas. Design to avoid them.
- Resharding is painful; plan for it with consistent hashing or many logical shards mapped onto fewer physical nodes.
- Hotspots: a single viral key can overload one shard. Add a random suffix to spread its writes.
- Global unique IDs: auto-increment no longer works. Use UUIDs or Snowflake-style IDs (timestamp + machine ID + sequence).
Consistent Hashing
Map both servers and keys onto a ring of hash values (0 to 2³² - 1). Each key belongs to the first server clockwise from it.
0
┌───────┐
S3 ● ● S1 key k → next server clockwise
│ ring │
S2 ● ● k
└───────┘- Adding a server takes over only the keys between it and its predecessor: about 1/N of keys move, versus nearly all with
mod N. - Removing a server hands its keys to the next server only.
Virtual Nodes
With few servers the ring is lumpy. Give each physical server many positions (virtual nodes, say 100 to 200 each) so load evens out, and so a failed server's load spreads across many survivors instead of one neighbour. Stronger servers can get more virtual nodes.
Used by DynamoDB, Cassandra, Riak, CDNs and distributed caches.
Other scaling techniques
- Vertical partitioning: split a wide table, moving rarely used or large columns elsewhere.
- Federation: split by function into separate databases (users DB, orders DB, products DB). Smaller, independent databases; cross-database joins disappear.
- Denormalization: duplicate data to avoid joins, at the cost of write complexity. See denormalization.
- CQRS: separate write models from read-optimized views that are updated asynchronously.
- Connection pooling: databases handle few connections well; put PgBouncer or a pool in front.
Object Storage
Object storage (S3, GCS, Azure Blob) stores immutable blobs addressed by key in a flat namespace, with effectively unlimited capacity and very high durability (eleven nines).
- Use for images, video, backups, logs, data lake files.
- Store the blob in object storage and only its key and metadata in the database.
- Serve through a CDN; let clients upload directly with pre-signed URLs so large files never pass through your servers.
Quick revision
- Start relational; choose NoSQL for a specific need (scale, data model).
- Leader-follower replication scales reads; asynchronous replicas lag, so handle read-your-writes.
- Multi-leader and leaderless replication trade conflict handling for availability; quorum needs W + R > N.
- Sharding scales writes and storage; the shard key determines balance and query locality.
- Consistent hashing moves only ~1/N of keys on resize; virtual nodes smooth the load.
- Put blobs in object storage, metadata in the database.