Database Scaling — System Design

Database scaling means making a database handle a bigger load. Vertical scaling adds machine resources (CPU, RAM, disk) to one server: easy, but there is a…

Picture one ticket desk with one clerk and one big ledger. Every ticket sale goes in that ledger. People who only ask ("is seat A-12 still free?") and people who buy (the clerk writes in the ledger) queue at the same desk, and the line keeps growing. There are three ways to help:

Those three, in order, are called vertical scaling, read replicas and sharding. In this picture, the clerk is the database server and the ledger is the data. A person who asks is a read (a request to read data), and a person who buys is a write (a request to change data). They are all part of database scaling: making a database handle a bigger load, whether that's more queries a second or more data.

The example model: TicketTune's database

The numbers in this lesson and in the Lab are an example model, not a benchmark (a real measurement). On a normal day (1x traffic), the TicketTune app sends 1,300 reads (SELECT) and 130 writes (INSERT, UPDATE, DELETE) a second to PostgreSQL, its main database. One 8 vCPU server (8 virtual processor cores) takes 4,000 reads a second, or 400 writes a second. Writes cost more because they go to disk and update indexes (lists of pointers that help the database find rows quickly).

Server load = reads / 4,000 + writes / 400 = 32.5% + 32.5% = 65%. While the load is below 100%, a query waits about 4 ms / (1 - load): 11 ms at a 65% load, 40 ms at 90%. Above 100%, the server receives more work than it can finish, so its queue keeps growing. At 2x traffic the load is 130%: every second the server receives 1.3 seconds of work but finishes only 1 second of it, so the queue grows by 0.3 seconds of work. After 10 seconds a new query waits about 3 seconds, and buyers see timeouts.

Before adding servers, make sure each query is efficient. A query with no index that reads 2 million rows is not saved by any server. That is covered in the Index Strategy and Connection Pooling lessons (Database track), and caching in the Caching Strategies lesson.

Vertical scaling: a bigger server

Vertical scaling (scaling up) means adding machine resources to one server: CPU, RAM (memory) and a faster disk. In this model, a server twice as big takes about 1.8 times the load, not 2 times, but it costs twice as much. This table shows the load for each server size:

Size Capacity Cost Load at 2x traffic Load at 6x traffic
8 vCPU 1x 1x 130% 390%
16 vCPU 1.8x 2x 72% 217%
32 vCPU 3.2x 4x 41% 122%
64 vCPU 5.8x 8x 22% 67%

The upside: one click in the cloud, and the code doesn't change at all. The downsides: there is a biggest machine, the cost rises faster than the capacity, and it is still one machine. If that machine dies, everything dies with it.

Horizontal scaling: more servers

Horizontal scaling (scaling out) means adding more servers. For app servers that is easy, because every server is the same (the Load Balancing lesson). For a database it is harder, because the data has to live on those servers. There are two ways:

Read replicas: splitting reads, not writes

A read replica is a copy of the database that can only be read. One server becomes the primary, the main server, which takes every write. Every change on the primary is then copied to each replica. The app sends SELECT to a replica, and INSERT, UPDATE, DELETE to the primary. This route function picks the server from the SQL text:

function route(sql) {
  return sql.trim().toUpperCase().startsWith('SELECT') ? 'replica' : 'primary';
}

console.log(route('SELECT * FROM orders WHERE user_id = 48213')); // replica
console.log(route('INSERT INTO orders (user_id, event_id, qty) VALUES (48213, 42, 2)')); // primary

This route function is enough for the model. In a real app, three kinds of SELECT must still go to the primary:

So frameworks (the toolkits an app is built on) pick the server from what the code means, not from the first word of the SQL text. Laravel, for example, has read and write settings for a database connection. Inside a transaction and for lockForUpdate() (locking rows), Laravel uses the primary. With 'sticky' => true, a request that has written also reads from the primary.

What people forget: every replica also has to replay every write to keep its data the same as the primary's. In this model, replaying one write costs half as much as the write itself. This table shows the load at 3x traffic (3,900 reads and 390 writes a second):

Setup Primary Each replica
No replica 97.5% + 97.5% = 195% -
1 replica 390 / 400 = 97.5% 97.5% reads + 48.75% replay = 146%
2 replicas 97.5% 48.75% + 48.75% = 97.5%
4 replicas 97.5% 24.4% + 48.75% = 73%

Then traffic goes up to 4x, and the primary's load becomes 130%. If you add a fifth replica, does the primary drop below 100%? No. All 520 writes a second still go to the primary: 520 / 400 = 130%, however many replicas there are. A fifth replica only takes reads. Read replicas help a read-heavy load (mostly reads, as in most web apps), but they don't help writes.

One more thing: a replica is always a little behind the primary (replication lag), because each change takes time to copy. So data that was just written may not show on a replica yet. The full story is in the Replication & HA lesson (Database track).

Sharding: splitting the data

Sharding splits one big table across several servers. Each server, called a shard, holds some of the rows, and takes the reads and writes for those rows only. The column that decides which shard a row goes to is the shard key.

In the Lab, TicketTune has 120,000 users and 4 shards. There are three shard keys to pick from. This code writes each one as a function that returns a shard number, 0 to 3:

// hash(user_id): a random-looking but fixed number from the id
function shardByHash(userId) {
  return hash(String(userId)) % 4; // hash() = FNV-1a, in the Lab's code
}
// user_id range: ids 1-30,000 on shard 0, 30,001-60,000 on shard 1, and so on
function shardByRange(userId) {
  return Math.min(3, Math.floor((userId - 1) / 30000));
}
// event_id: every order for one event on one shard
function shardByEvent(eventId) {
  return eventId % 4;
}

console.log(shardByHash(48213), shardByRange(48213), shardByEvent(42)); // 2 1 2

Hot shards and cross-shard queries

This model has two facts. First, 7 in 10 buyers want Archipelago Concert. Second, the users who signed up last (id 90,001 and up) are three times as active, so they bring 50% of the traffic. If one server carried all the traffic at 4x, its load would be 260%, so each shard's load is its share of that 260%. This table shows the busiest shard for each shard key, at 4x traffic with 4 shards:

Shard key The busiest shard holds Its load
hash(user_id) 25.2% of traffic 66%
user_id range 50% (shard 3, the newest users) 130%
event_id 70% (shard 2, Archipelago Concert) 182%

A shard carrying far more than the others is a hot shard. Three shards idle, one overloaded, and the whole system slows down with it. Pick a shard key with many values and evenly spread traffic.

The main weakness of sharding is cross-shard queries. A query that doesn't name the shard key has to go to every shard, and the results are merged in the app. This is called scatter-gather (spread out, then collect). Its latency follows the slowest shard, and it costs 4 queries, not 1. JOINs across shards (combining tables whose rows are on different shards) are harder still. This table shows how many shards two queries ask:

Query Shard key hash(user_id) Shard key event_id
SELECT * FROM orders WHERE user_id = 48213 1 shard 4 shards
SELECT COUNT(*) FROM orders WHERE event_id = 42 4 shards 1 shard

So the shard key comes from the most frequent query. There are two other weaknesses. First, adding a shard with % N (N = the number of shards) moves almost every row. Consistent hashing reduces this, see the Load Balancing lesson. Second, ids must be unique across all shards, not only within one shard.

🎯 The order, cheapest first

  1. Fix queries and indexes. Check with EXPLAIN, a command that shows how the database runs a query. Often it ends here.
  2. Connection pooling and a cache. Connection pooling reuses database connections that are already open. Redis for data that is read often.
  3. Vertical scaling. One click, no code changes.
  4. Read replicas. For a load that is mostly reads.
  5. Split by feature (vertical partitioning): analytics tables (statistics data) in their own database, for example.
  6. Sharding. Last, because it is the hardest to run and hard to undo.

⚠️ Wrong moves when the database starts to struggle

TL;DR: Database scaling means making a database handle a bigger load. Vertical scaling adds machine resources (CPU, RAM, disk) to one server: easy, but there is a biggest machine and the cost climbs fast. Horizontal scaling adds more servers. Read replicas copy the whole database to servers that can only be read. SELECT (a read, reading data) is spread over the replicas, and every write (changing data) still goes to the primary, the main server. So replicas help reads but not writes: in this model the primary stays at a 130% load at 4x traffic (four times a normal day) however many replicas there are. Sharding splits the data across several servers (shards) by a shard key, the column that decides which shard a row goes to, so reads and writes are both split. Pick a shard key that spreads evenly and appears in the most frequent query. event_id (the concert's ID) makes a hot shard (one shard overloaded, 182%), while hash(user_id) (a hash of the user's ID) is even (66%). The main weakness of sharding is cross-shard queries, which have to ask every shard and merge the results. Fix queries, indexes (pointers that speed up finding rows) and caching first. Shard last.

⚡ Vertical or horizontal

Meaning: Vertical scaling adds machine resources to one server: CPU, RAM and a faster disk. Horizontal scaling adds more servers. Vertical is the easiest, but there is a biggest machine, the cost rises faster than the capacity, and it is still one machine: if that machine dies, everything dies with it.

⚡ Read replicas: SELECT goes to a replica

Write:

function route(sql) {
  return sql.trim().toUpperCase().startsWith('SELECT') ? 'replica' : 'primary';
}

console.log(route('SELECT * FROM orders WHERE user_id = 48213')); // replica
console.log(route('INSERT INTO orders (user_id, event_id, qty) VALUES (48213, 42, 2)')); // primary

Meaning: A read replica is a copy of the database that can only be read, and the primary is the main server, which takes every change. The route function looks at the start of the SQL text. SELECT (a read, reading data) is spread over the replicas, while INSERT, UPDATE, DELETE (writes, changing data) still go to the primary.

⚡ Replicas don't help writes

Guess first: at 4x traffic (four times a normal day), the primary gets 520 writes a second and its load is 130%. If you add a fifth replica, does the primary's load drop below 100%?

No. All 520 writes a second still go to the primary, which can only take 400, so its load stays at 130%. Every replica even has to replay all those writes.

Meaning: Read replicas suit a load that is mostly reads, not writes.

⚡ Pick a shard key that spreads evenly

Meaning: Sharding splits a table's rows over several servers, called shards, by a shard key: the column that decides which shard a row goes to. Pick a key with many values, evenly spread traffic, and a place in the most frequent query. In this model (4x traffic, 4 shards), 7 in 10 buyers want one concert. The shard key event_id (the concert's ID) piles them on one shard: a hot shard with a 182% load. hash(user_id) (a hash of the user's ID) spreads them evenly, and its busiest shard is only at 66%.

What you will learn