Notes
All notes

Databases at Scale (System Design #11)

One Postgres handles millions of rows comfortably. Then three things happen, usually at once: reads saturate the disk, writes saturate the primary, and the dataset outgrows the box. This is the wall where every growing system arrives, and it has exactly three answers — copies (replication), slices (sharding), and shortcuts (caching and tuning). This chapter is the first two; Chapter 12 is the third.

The order matters. Reach for replication before sharding, and tuning before either. Sharding is the most complex, least reversible change you can make to a database, and teams do it too early as often as too late.

Replication: copies for reads and survival

One node (the primary or leader) accepts writes; one or more replicas (followers) replay the primary’s write log and serve reads. This scales reads horizontally and provides a standby for failover.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.72cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=gray!10] (w) at (-3.6,0) {writes};
  \node[b, fill=orange!16] (p) at (-1.3,0) {primary};
  \node[b, fill=green!12] (r1) at (1.4,1.1) {replica};
  \node[b, fill=green!12] (r2) at (1.4,0) {replica};
  \node[b, fill=green!12] (r3) at (1.4,-1.1) {replica};
  \draw[a] (w) -- (p);
  \draw[a, dashed] (p) -- node[above, font=\scriptsize] {log} (r1);
  \draw[a, dashed] (p) -- (r2);
  \draw[a, dashed] (p) -- (r3);
  \node[font=\rmfamily\small, text=black!60] at (2.9,1.1) {reads};
\end{tikzpicture}

Three consequences to design around:

  1. Reads scale, writes do not. All writes still funnel through the primary. If writes are the bottleneck, replication alone will not save you.
  2. Replication lag breaks read-your-writes. A read sent to a lagging replica may miss a just-committed write. Route a user’s own reads to the primary (or pin them to a replica that has caught up) — the read-your-writes refinement from Chapter 4.
  3. Failover is a process, not an event. Promoting a replica involves election (to prevent split-brain) and usually a few seconds of failed writes. With async replication it can also lose the tail.

Quorums generalize this. With \(N\) replicas, write to \(W\) and read from \(R\) such that \(W + R > N\): any read overlaps at least one replica that saw the latest write, so it is guaranteed fresh.

def quorum_reads_latest(n, w, r):
    return w + r > n           # overlap at least one replica
print(quorum_reads_latest(3, 2, 2))   # True
print(quorum_reads_latest(3, 1, 1))   # False -> stale reads possible

\(W = N, R = 1\) is fast, read-heavy, but fragile on the write side; \(W = 1, R = N\) is fast writes; \(W = R = \text{majority}\) balances both and survives a minority of failures. This is how leaderless stores (Dynamo-style) tune consistency per operation.

Sharding: slices for size and throughput

When the data no longer fits on one box, or writes exceed one primary, split the rows across shards by a shard key.

Strategy How Strength Weakness
Range by key range (A–M, N–Z) good range scans hot spots from sequential keys
Hash hash(key) % N even spread range queries scatter; resharding moves all keys
Directory lookup table maps key → shard flexible, easy rebalance extra lookup, table is critical

The shard key decides everything. Good keys have high cardinality, spread writes evenly, and match the dominant query so a request touches one shard. Common choices: user_id, tenant_id, order_id. Anti-patterns: created_at as a range key (all writes hit “today”), or a low-cardinality key like country (a few huge shards).

Hot spots are sharding’s central risk. Even a hashed key can be skewed by a celebrity user or a viral item. Mitigations: add a random suffix to split a hot key, cache the hot entity aggressively, or route that entity to its own shard.

Resharding is why you should choose carefully. With modulo hashing, adding a shard moves almost every key. With consistent hashing (Chapter 8), only about \(1/N\) of keys move. With a directory, you update the mapping and migrate gradually.

import hashlib

def shard(key, n_shards):
    return int(hashlib.md5(key.encode()).hexdigest(), 16) % n_shards

# modulo: adding a shard remaps ~all keys. consistent hashing fixes this.
print([shard(f"user-{i}", 4) for i in range(8)])
# in production you'd take the first shard clockwise on a hash ring

Practical requirements before you shard:

Federation: partition by function

Federation (functional partitioning) splits the database by purpose rather than by row: one database for users, one for orders, one for analytics. It reduces load per database and lets each be tuned independently — an analytics store can be columnar, an order store transactional.

It is simpler than sharding because there is no shard-key math, but it does not scale a single hot table: if orders alone outgrows a box, you still need to shard it. Federation and sharding compose — federate first, then shard the biggest function.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.8cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=gray!10] (app) at (0,1.4) {application};
  \node[b, fill=blue!10] (u) at (-3.2,0) {users db};
  \node[b, fill=green!12] (o) at (-1.1,0) {orders db};
  \node[b, fill=orange!16] (a2) at (1.1,0) {analytics (columnar)};
  \node[b, fill=yellow!22] (s) at (3.2,0) {search};
  \draw[a] (app) -- (u); \draw[a] (app) -- (o); \draw[a] (app) -- (a2); \draw[a] (app) -- (s);
\end{tikzpicture}

Denormalization and tuning: shortcuts before sharding

Before adding infrastructure, make the existing database fast. These are cheap and often delay sharding by years:

The order of attack is therefore: index and tune → cache → replicate → federate → shard. Each step is more expensive and harder to reverse than the last. Do not skip ahead.

Pitfalls

QQuestionSelf-check

Why does replication scale reads but not writes? What makes a good shard key, and when should you shard?

ASolution

Every write still goes to the primary; replicas only serve reads, so writes remain a single bottleneck. A good shard key has high cardinality, spreads writes evenly, and matches the dominant query so requests hit one shard. Shard only after indexing, caching, and replication fail — it is the most complex and least reversible option.

Next: Caching (System Design #12) — the cheapest way to make all of this feel fast.