Machine Room

Sharding vs Replication

Both put a database on more than one server, and they fix different problems: replication fixes reads and failures, sharding fixes writes and size. The one-page notes from the reel.

Download the PDF

One-page notes, Sharding vs Replication. Both put a database on more than one server. They fix different problems. 1, Start: one database server. users. id | name. 1 | Ana, 2 | Ben, 3 | Cara, 4 | Dan, 5 | Eva, 6 | Finn, 7 | Gia, 8 | Hugo. read. write. It holds all the data. Every read and every write goes to it. Problem 1: too many reads. And if this one server dies, the app is down. Problem 2: too many writes, or too much data for one server. 2, Replication: copies of the same data. primary. replica. users 1-8. write. read. Each copy is called a replica. Every replica holds everything. Reads can go to the replicas. Writes go to one server, the primary. Each write lands there first, then is copied to the replicas. 3, The two things replication brings. failover. primary. takes over. If the primary dies, a replica takes over. replication lag. primary. 7 | Gina. replica. 7 | Gia. A replica can be a moment behind the primary. That delay, between a write on the primary and the same write on a replica, is replication lag. Replication doesn't spread the writes: every write still goes to the primary. 4, Sharding: split the data. shard 1. 1 | Ana, 2 | Ben, 3 | Cara, 4 | Dan. shard 2. 5 | Eva, 6 | Finn, 7 | Gia, 8 | Hugo. Half the users on one server, half on another. Each user lives on only one shard. Now the writes are spread out too. That's horizontal scaling, for a database. Adding shards adds storage. 5, The shard key. user id = 6. 1-4. 5-8. shard 1. shard 2. name = Eva. ask every shard. A shard key decides which shard a user is on. Here it's the user's ID. A query without the shard key has to ask every shard. The price is complexity. 6, In practice: use both. shard 1: users 1-4. shard 2: users 5-8. primary. replica. Each shard is itself a primary with its own replicas. MongoDB: "Each shard must be deployed as a replica set.". Vitess: "A Vitess shard typically contains one MySQL primary and many MySQL replicas.". 7, Which one fixes what. replication | sharding. each server holds | everything | only its part. writes | all go to the primary | spread across shards. reads | can go to the replicas | spread across shards. the price | replication lag | complexity. fixes | reads and failures | writes and size. Replication fixes reads and failures. Sharding fixes writes and size. Real systems use both.

On a phone, press and hold the image to save it.