Notes and Talks/UJEP/NSQL/02

Sharding and Replication

Questions to answer:

Why is one machine not enough

Recall the two ways to scale:

Sharding vs. Replication

Sharding Replication different records on different nodes copies of the same record A node 1 B node 2 C node 3 A node 1 A node 2 A node 3 Sharding stores different records on different nodes. Replication stores copies of the same record on several nodes.

Sharding (partitioning): where does a record (piece of data) live?

How to map key ⇒ node

Range sharding a … m node 1 n … s node 2 t … z node 3 a growing key piles new writes onto the last node neighbours stay together; range scans are cheap Hash sharding user:7 user:8 user:9 hash(key) mod 3 node 0 node 1 node 2 0 1 2 consecutive keys scatter; writes spread evenly, but a range scan must ask every node
Consistent hashing A B C D key k walk clockwise → Why it is useful • A key belongs to the next node on the ring. • Add a node → only the keys on one arc move (about 1/n of all keys). • Remove a node → only its arc's keys move. • Virtual nodes: one machine owns many points on the ring, so load stays even. Redis Cluster uses the same idea with a fixed ring of 16 384 hash slots and a map that moves a few slots at a time.

The cost of sharding

How Redis, MongoDB and Neo4j shard

app mongos router config servers replica set — chunk map reads the chunk map chunk 1–100 primary writes secondary secondary Shard A (replica set) chunk 101–200 primary writes secondary secondary Shard B (replica set) chunk 201–300 primary writes secondary secondary Shard C (replica set) route by shard key mongos reads the chunk map from the config servers. A query that contains the shard key goes to one shard; without it, mongos scatters the query across all shards and merges the results.

Replication

The cost: replication lag — a read from a lagging secondary returns an older value (inconsistency window}

Redis, MongoDB and Neo4j

They use primary–secondary replication.

  1. One node, the primary, accepts writes.

  2. The primary keeps a sequential log of writes.

  3. Secondaries read the log and apply the writes as they happen.

client write primary value 2 secondary A value 1 (lagging) secondary B value 2 log log client read sees value 1 — stale The primary appends each write to its log; secondaries apply the log in order. Reading a lagging secondary returns an older value — the inconsistency window from lecture 1.

A problem: a client that writes and then reads from a secondary can miss its own write. (There are ways to fix it, but they have a cost.)

What if the primary dies?

The secondaries notice and elect a new primary.

A split brain

A network partition that leaves two groups → two primaries that accept writes and create conflicting histories. Must be prevented.

Shard, replicate, or both?

Three examples:

The decisions: