System Design on databases, replication and sharding
Start with a relational database
- Relational (SQL) databases such as PostgreSQL store rows in tables with a set schema.
- They give joins and ACID transactions: a group of changes all happen, or none do.
- They fit data with relationships and rules, like orders, billing and stock.
NoSQL trades query power for scale
- Key-value and document stores relax joins and transactions to spread across machines.
- Design them around the queries you know. New kinds of query are hard to add later.
- A URL shortener is one lookup by key, so a key-value store fits it well.
| Relational | Key-value | Document | |
|---|---|---|---|
| Shape | Tables and rows | Key to opaque value | JSON documents |
| Query | Joins, rich SQL | Lookup by key | By fields in a document |
| Atomic unit | Many rows | One key | One document |
| Good for | Orders, billing | Caches, sessions | Catalogs, profiles |
| Examples | PostgreSQL, MySQL | Redis, DynamoDB | MongoDB |
Replication keeps copies on other machines
- One primary takes the writes and streams them to replicas, also called standbys.
- If the primary dies, a replica is promoted to primary. That switch is failover.
- Replicas can also answer reads, which spreads the read load.
Writes
- App
- Primarythe only writer
- Replicasget every change
Reads
- App
- Any replicamay be slightly behind
Synchronous is safe, asynchronous is fast
- Synchronous: a write waits until replicas have it. Failover loses nothing. Writes slow.
- Asynchronous: the primary confirms at once. A crash can lose the last few writes.
- Async replicas lag, so users may not see their own write. Read those from the primary.
Read replicas scale reads, not writes
- Every write still goes through the one primary.
- If reads are the problem, add replicas and caching before anything harder.
Sharding splits the data across databases
- Each shard holds a slice of the rows, chosen by a shard key such as user ID.
- Hash the key for even load. Ranges allow range queries but risk one hot shard.
- Queries and transactions across shards are slow and hard. Keep requests to one shard.
- The shard key is very hard to change later. Shard only when one primary cannot cope.
Consistent hashing makes adding a shard cheap
- With hash(key) mod N, changing N moves most keys to a different shard.
- Consistent hashing places shards on a ring, so adding one moves only a small fraction.