Choosing a Database · Lesson 69 of 112

Database Scaling, Replication and Sharding

What you will learn

  • What scaling up and scaling out mean
  • What replication does and what replica lag is
  • What sharding does and its costs
  • Why you should try simpler fixes first

1. Scaling up and out

When a database becomes too slow or too busy, there are two directions:

  • Scale up (vertical): a bigger machine with more memory, faster disks, more CPU. Simple, no change to your design, but it has a limit and a cost.
  • Scale out (horizontal): use several machines. This can go further but brings new problems. The two main tools are replication and sharding.

Before either, check the cheaper fixes: the right indexes and better queries (chapter 7), a cache (lesson 9.3), and removing needless work.

2. Replication

Replication keeps copies of the data on other servers. One server, the primary, accepts writes; replicas copy its changes. Benefits: spread reads across replicas, and have a spare if the primary fails.

The catch is replica lag: a copy is a little behind the primary. SQLite's backup function lets us copy a database in code, enough to show the lag:

import sqlite3

primary = sqlite3.connect(":memory:")
primary.execute("CREATE TABLE t (x INTEGER)")
primary.execute("INSERT INTO t VALUES (1)")
primary.commit()

replica = sqlite3.connect(":memory:")
primary.backup(replica)

primary.execute("INSERT INTO t VALUES (2)")
primary.commit()
print("primary", primary.execute("SELECT COUNT(*) FROM t").fetchone()[0],
      "replica", replica.execute("SELECT COUNT(*) FROM t").fetchone()[0])
primary.backup(replica)
print("after sync, replica", replica.execute("SELECT COUNT(*) FROM t").fetchone()[0])
primary 2 replica 1
after sync, replica 2

For a moment the replica said 1 row while the primary had 2. A user who saves something and then reads from a lagging replica may not see their own change. Real systems copy changes continuously and quickly, but some delay is normal, so decide which reads can accept slightly old data. Some systems can instead wait until a replica confirms each write (synchronous replication), which avoids lag but makes every write slower; copying without waiting is asynchronous. Chapter 14 returns to these choices.

3. Sharding

Sharding splits one big table across several servers (shards), each holding part of the rows. A shard key (for example the user id) decides which shard owns a row. A common way is to hash the key and take the remainder:

import sqlite3, zlib

shards = [sqlite3.connect(":memory:") for _ in range(3)]
for s in shards:
    s.execute("CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT)")

def shard_for(key):
    return zlib.crc32(key.encode()) % len(shards)

names = ["rina", "sam", "lee", "amy", "joe", "mia", "tom", "eva"]
for n in names:
    shards[shard_for(n)].execute("INSERT INTO users VALUES (?, ?)", (n, n.title()))
for i, s in enumerate(shards):
    print("shard", i, [r[0] for r in s.execute("SELECT id FROM users ORDER BY id")])
print(shards[shard_for("lee")].execute("SELECT name FROM users WHERE id = 'lee'").fetchone())
shard 0 ['sam']
shard 1 ['mia']
shard 2 ['amy', 'eva', 'joe', 'lee', 'rina', 'tom']
('Lee',)

Looking up lee goes straight to the right shard. But notice the split is uneven: with only eight keys, one shard got six. Hashing balances well only with many keys and a good key.

Costs of sharding:

  • A question across all users must ask every shard and combine the answers.
  • A join or transaction across shards is hard or impossible.
  • Adding a shard changes the remainder for most keys, so data must move (real systems use smarter schemes).
  • It is much harder to operate. Choose it only when one primary plus replicas cannot cope.

Worked example: pick the next step

A shop's site is slow at sale time. The order of things to try:

  1. Check slow queries and indexes.
  2. Cache the product pages.
  3. Move reports to a replica.
  4. Move to a bigger server.
  5. Only then think about sharding.

The shop is made up.

Common mistakes

  • Sharding too early, buying heavy complexity for a problem an index would fix.
  • Reading from a replica right after writing and being surprised by old data.
  • Picking a poor shard key, so one shard does most of the work.

Key takeaways

  • Scale up with a bigger machine; scale out with more machines.
  • Replication copies data for read capacity and safety, but replicas lag.
  • Sharding splits data across servers by a key, at a high price in complexity.
  • Try indexes, queries, caching and replicas before sharding.

Practice

1. What is the difference between scaling up and scaling out?

Show answer

Up: a bigger single machine. Out: more machines sharing the work.

2. What is replica lag?

Show answer

The delay before a replica has the latest changes of the primary.

3. In the sharding demo, why did lee always go to shard 2?

Show answer

The same key always hashes to the same number, so the remainder, and therefore the shard, is always the same.

4. Why is the split in the demo uneven?

Show answer

Only eight keys were hashed, which is too few to spread evenly.

5. Give two costs of sharding.

Show answer

For example: questions across all shards are harder, joins and transactions across shards are hard, and moving data when shards are added.

6. Name two fixes to try before sharding.

Show answer

For example indexes and better queries, caching, or moving reports to a replica.