Skip to content
Engineering Bible
System Design

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.
RelationalKey-valueDocument
ShapeTables and rowsKey to opaque valueJSON documents
QueryJoins, rich SQLLookup by keyBy fields in a document
Atomic unitMany rowsOne keyOne document
Good forOrders, billingCaches, sessionsCatalogs, profiles
ExamplesPostgreSQL, MySQLRedis, DynamoDBMongoDB
Typical traits. Many products blur these lines.

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

  1. App
  2. Primarythe only writer
  3. Replicasget every change

Reads

  1. App
  2. 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.
System Design in seven pages4 / 7