Home›Design›System design, from one server
Course · ScaleLesson 13 of 330 read

System design, from one server

What is system design, and how do you decide what to add?

Start here before the 25 ideas. One picture of an app growing, the trade-offs behind every choice, and a guide that starts from your problem.

Most system design advice starts with patterns. This page starts with one app on one database, and adds each piece only when something runs out.

What system design means

System design is deciding how the parts of an application fit together so it keeps working as more people use it. It is not a list of patterns to add. Every product starts as one app and one database, and that is the right design for longer than most people think. The work is knowing which part will run out first, and adding the smallest thing that fixes it.

Every design, small or huge, answers the same four questions:

1

Where does a request go?

From the user to a server, to the database, and back. Every box on that path adds time and can fail.

2

Where does the data live?

One database, copies of it, or pieces of it on many servers. This decides what a write costs.

3

What happens when a part dies?

A server, a disk, a whole region. Something either takes over, or people wait.

4

What happens at 10 times the traffic?

Which part runs out first, and what you add then.

The database sits under all four. App servers hold no data, so you can add ten of them in minutes. The database holds the one copy of the truth, so every answer above gets hard there first. That is why this site follows each idea down to it.

The six things you trade

Every choice in system design buys more of one of these and pays with another. Nothing on this list comes free, and a design review is mostly asking what each box costs.

Latency

How long one request waits.

One row in a million: an index reads 4 pages, the same query without it reads 19,231. Notebook 3 →

Throughput

How many requests a second the system finishes.

One connection committing durably tops out near 4,200 commits a second, set by a 0.236 ms disk flush. Napkin math →

Availability

Whether people can use it right now.

GitLab was down 18 hours in 2017 while they rebuilt from a staging copy. GitLab →

Consistency

Whether every reader sees the latest write.

Two deposits at the same moment: one was lost at READ COMMITTED. Notebook 4 →

Durability

Whether "saved" means saved, even after a crash.

A Redis failover lost 2,217 writes that clients had been told were saved. Notebook 9 →

Cost

Money, and the people who run it.

Dropbox could not grow one shard, so expanding meant doubling the whole fleet for a little more data. Dropbox →

Press a choice to see what it buys and what it costs.

One app grows

The same application, from its first thousand users to a million. At each step one part runs out, and you add one thing. It stops twice to ask you what comes next. The numbers of users are only an example: the order is what matters.

Read the order again: app servers, then a cache, then replicas, then shards. Each step is harder to undo than the one before. That is why the decision guide below always tries the cheap fixes first.

Why it matters: four real failures

None of these teams were careless. Each one hit a decision that looked fine until traffic or bad luck tested it. Every one is written up on this site with its numbers and sources.

GitLab, 2017

Backups nobody restored

300 GB of production data deleted in seconds. Five backup methods, none of them worked. 18 hours down and 6 hours of writes lost for good.

The decision behind it: backups that were taken but never restored and checked.

GitHub

A failover that waited for a human

When the MySQL master died, someone had to wake up and fail over by hand. They automated it, with a target of 30 seconds, and a guard that blocks a second automatic failover for 30 minutes.

The decision behind it: automate the failover, and put a limit on the automation.

Slack

A shard key that made a hot spot

Sharding by workspace put each big customer on one shard. That shard ran hot while the rest sat idle. They resharded by channel ID, live, with every row written to both copies and compared before cutting over.

The decision behind it: the shard key, picked from who owns the data instead of how it is accessed.

Fortnite, 2018

Timeouts that made it worse

A release changed how often the game called the account database. Queries slowed, a 200 ms client timeout opened new connections instead of waiting, and the account service was down for almost 18 hours.

The decision behind it: retry and timeout settings that turned a slow database into an unreachable one.

What to choose

Start from the problem you can measure, not from the name of a pattern. Pick what hurts:

Reads are slow

Try these in order. Stop when the problem is gone.

  1. Check the query plan first. A missing index is the most common cause. One row in a million: 4 pages with an index, 19,231 without. EXPLAIN reader →
  2. Cache the reads that repeat. Product pages, settings, anything read far more than it changes. Caching →
  3. Add read replicas. Send a user's own reads to the primary for a few seconds after they write. Replication →

Not yet: Do not shard for read load. Replicas and caches are much cheaper to add and to remove.

Measure first:

SELECT query, calls, mean_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC LIMIT 10;

Writes are slow, or the primary is at its limit

Try these in order. Stop when the problem is gone.

  1. Write less per change. Batch rows per commit, and drop indexes nobody uses. At Uber one UPDATE became four physical writes. Uber story →
  2. Move slow work out of the request. Emails, thumbnails and reports go on a queue. Message queues →
  3. Buy a bigger primary. It is boring and it works. For most products, the largest machine lasts years. Vertical scaling →
  4. Partition the biggest tables. By time or by tenant, so VACUUM and indexes work on smaller pieces. Partitioning →
  5. Shard, last. Pick the key from how the data is accessed. Sharding →

Not yet: Do not add replicas for write load. Every write still goes to the one primary.

Measure first:

SELECT relname, n_tup_ins + n_tup_upd + n_tup_del AS writes
FROM pg_stat_user_tables
ORDER BY writes DESC LIMIT 10;

Too many connections

Try these in order. Stop when the problem is gone.

  1. Put a pooler in front. PgBouncer or ProxySQL: thousands of app connections share a few dozen real ones. Connection pooling →
  2. Set timeouts and limits in the app. A pool per app server, a statement timeout below the gateway timeout. Rate limiting →

Not yet: Do not raise max_connections into the thousands. Each PostgreSQL connection is a process with its own memory.

Measure first:

SELECT state, count(*) FROM pg_stat_activity GROUP BY state;

We cannot afford downtime

Try these in order. Stop when the problem is gone.

  1. Restore a backup, on a schedule. Time it. That number is your real recovery time. Disaster recovery →
  2. Automatic failover, with a guard. Patroni, Orchestrator or a managed service, with a limit on repeated failovers. High availability →
  3. Change the schema without locking. Add, backfill, switch, then drop. Zero-downtime deploys →

Not yet: Do not count backups you have never restored. GitLab had five.

Measure first:

SELECT now() - pg_last_xact_replay_timestamp() AS replica_lag;

Run this on the replica. On a primary it returns NULL.

Users are far away

Try these in order. Stop when the problem is gone.

  1. Serve static files and pages from a CDN. Most of the bytes never reach your servers. CDN →
  2. Read replicas in other regions. Reads get close to users. Writes still travel to the primary. Replication →
  3. Writes in several regions, last. Every option either waits a round trip or can lose writes in flight. Multi-region →

Not yet: Do not go multi-region for writes until you can say what happens to a write when a region is lost.

The data is too big for one server

Try these in order. Stop when the problem is gone.

  1. Delete or archive what nobody reads. Old events and logs are often most of the bytes. Partitioning →
  2. Move reporting to a column store. ClickHouse read 870,400 of 10 million rows for a monthly report. Notebook 7 →
  3. Then shard. With the key chosen from the access pattern. Sharding →

Not yet: Do not shard to fix analytics queries. Move them out of the live database instead.

Measure first:

SELECT relname, pg_size_pretty(pg_total_relation_size(relid))
FROM pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC LIMIT 10;

Many services, one database

Try these in order. Stop when the problem is gone.

  1. Publish changes with an outbox. The row and the event commit together, so nothing is lost between them. Sagas and the outbox →
  2. Split by domain, not by shard key. Instacart split customers from fulfillment instead of sharding. Instacart story →

Not yet: Do not split the database first and work out the transactions later. Every join across the split becomes an API call.

My rule: if you cannot point at the graph that shows the problem, you do not have it yet. Every box in the animation above was added because one number crossed a line.

Where to go from here

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. The database is at 90 percent CPU from reads. Which fix is the hardest to undo?

2. Adding read replicas helps which kind of load?

3. Turning off synchronous_commit buys throughput. What does it cost?

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.