02. Scaling: cheatsheets

5 lessons, one page each when printed.

System Design · 02. Scaling · 8 min · Beginner

Vertical vs Horizontal

Make one machine bigger, or run many machines side by side.

In short

Scale up (vertical): a bigger machine. Simple, no code change, but it has a ceiling (32,000 users here), costs more per core at the top, and is one thing to lose.

Scale out (horizontal): more machines. It needs a load balancer, shared state and redundancy for the parts that exist once, but it has no ceiling. Here 20 small servers carry 30,000 users at 75% CPU.

Key ideas

  • Vertical scaling is fast and simple, but it has a hard upper limit, a rising price and one big machine to lose. (step 4)
  • Scaling out adds a new part to the system: the thing that spreads the work. (step 6)
  • Count the parts that exist only once. Each one is a risk, and each one needs a spare. (step 8)

Good to know

  • For a small app, a bigger machine is often the best first step. Keep it simple while you can. (step 3)
  • Large web systems scale out: cheap standard machines, added as needed. (step 5)

Watch out

  • Do not wait for 100%. Plan to add capacity when you pass about 70% at the peak. (step 2)
  • Anything an app server remembers in its own memory or disk is lost to the other servers. (step 7)
UsersLoad balancerApp serverApp serverLoad balancer 2App serverDatabaseShared session store

Key numbers

CPU load
75%
Max users
40,000
Cost a month
$3,000

Terms

Vertical scaling (scale up)
Adding capacity by moving to a bigger machine with more CPU, memory or disk.
Horizontal scaling (scale out)
Adding capacity by running more machines side by side.
Scaling ceiling
The largest machine you can get; vertical scaling cannot go past it.
Load balancer
A server that receives requests and spreads them across many app servers.
Shared state
Data such as sessions that every server must be able to reach, so it cannot live in one server's memory.
Single point of failure (SPOF)
A part that exists only once, so its failure stops the whole system.
Redundancy
Keeping a spare copy of a part so the system survives its failure.
Capacity headroom
Unused capacity kept in reserve, because queues grow fast near full load.

System Design · 02. Scaling · 10 min · Beginner

Load Balancing

One address for the users, many servers behind it.

In short

Users reach one address; the balancer spreads requests over the servers. Round robin takes turns, least connections picks the least busy, and weights favour bigger machines.

Health checks remove a dead server within seconds. Keep servers stateless so any of them can answer any request.

Key ideas

  • Users see one address. Behind it you can add, remove or replace servers without telling anyone. (step 2)
  • Round robin looks at the order. Least connections looks at the servers. (step 5)
  • Keep enough spare capacity: two servers must now carry the load of three. (step 8)

Good to know

  • Round robin is a fine default when every request costs about the same. (step 3)
  • Weights also help a careful roll-out: give a new server weight 1 of 10 first, and raise it if all is well. (step 6)
  • Many sites use both: an L4 balancer spreads connections over a few L7 balancers, which route by URL. (step 10)

Watch out

  • Adding servers does nothing until something spreads the requests over them. (step 1)
  • One slow request can cost as much as a hundred fast ones. (step 4)
  • A good health check tests what the server needs (its database connection), but stays cheap: it runs every few seconds. (step 7)
  • Sticky sessions make the load uneven, and when that server dies its users lose their session. The better fix is the next lesson: stateless servers. (step 9)
UsersLoad balancerS1S2S3

Key numbers

Busiest server
33%
Healthy servers
3/3
Failed requests
0

Terms

Load balancer
A server in front of the others that takes the public address and passes each request on to one of them.
Round robin
Send requests to the servers in turn: S1, S2, S3, then S1 again.
Least connections
Send each new request to the server with the fewest requests in progress.
Weighted balancing
Give bigger servers a higher weight so they receive a bigger share of the requests.
Health check
A small request the balancer sends every few seconds to see whether a server is alive.
Failover
Taking a failed server out and sending its traffic to the healthy ones.
Sticky sessions
Sending each user back to the same server, usually with a cookie.
L4 vs L7 load balancer
Layer 4 balances TCP connections; layer 7 reads the HTTP request and can route by path.

System Design · 02. Scaling · 8 min · Beginner

Stateless Services

Keep no user data on the server, so any server can answer any request.

In short

A stateful server pins users to itself, so a restart logs them out and scaling is awkward. A stateless server keeps its state in a shared store or in the user's token.

Then any server can serve any request. Deploys, crashes and autoscaling cost no one a login, and 1,000 users on each of three servers can become 600 on each of five.

Key ideas

  • State is anything the server must remember between two requests. A server that remembers it is called stateful. (step 1)
  • Stateless does not mean the system has no state. It means the app servers do not hold it. (step 4)

Good to know

  • Rolling deploys, crashes and replacements all become routine, because no single server is special. (step 7)

Watch out

  • Sticky sessions hide the problem. The load gets uneven, and the sessions are still stuck on one machine. (step 2)
  • You cannot deploy, scale in or lose a machine without hurting real users. That is the cost of state in memory. (step 3)
  • The store is now a shared part. If it dies, everyone is logged out, so run it with a replica and failover. (step 5)
  • Store: easy to log someone out, one extra lookup per request. Token: no lookup, but hard to revoke early. (step 6)
  • Check for hidden state too: files saved on the local disk, in-process caches that must agree, and open WebSocket connections. (step 8)
UsersServer 4Load balancerServer 1Server 2Server 3Session store (Redis)Server 5

Key numbers

Logged-out users
0
Servers up
5 of 5

Terms

Session
A small server-side record of who is logged in, found by an id that the browser sends in a cookie.
Stateful server
A server that remembers data about users between requests.
Sticky session
The load balancer always sends a user to the same server, so that server's memory can hold the session.
Stateless service
A server that keeps nothing about users between requests, so any server can answer any request.
Session store
A shared fast store, such as Redis, where every server reads and writes sessions.
Signed token (JWT)
A user-carried record signed with a secret key, so the server can trust it without a lookup.
Token revocation
Cancelling a token before it expires, which is hard because the server keeps no record of it.
Autoscaling
Starting and stopping servers automatically as load changes, which is safe when they are stateless.

System Design · 02. Scaling · 12 min · Intermediate

Caching

Keep the answers you read often in fast memory.

In short

A cache keeps copies of hot data in memory. At a 90% hit rate the average read drops from 20 ms to 3.0 ms and the database does a tenth of the work.

Cache-aside fills it on a miss; TTLs and deletes keep it fresh; LRU makes room; locks and negative caching protect the database from stampedes and penetration.

Key ideas

  • The cache holds copies. The database stays the source of truth. (step 2)
  • Fixes: let only one request reload the key while the others wait or get the old copy (a lock, or single flight), refresh popular keys before they expire, and add a little randomness to TTLs. (step 9)

Good to know

  • Popular data is small: a few percent of the keys often answer most of the reads. (step 3)
  • Redis can also evict by least frequently used (LFU) or only among keys that have a TTL. (step 8)
  • Static files (images, scripts) belong in the browser and the CDN; per-user data usually in Redis. (step 11)

Watch out

  • Reads usually outnumber writes 10 to 1 or more, so repeated reads are the first thing to remove. (step 1)
  • A short TTL means fresher data and more misses; a long TTL means fewer misses and older data. Choose per kind of data. (step 5)
  • Write-back suits counters and view numbers, where losing a few seconds is acceptable. Never use it for payments. (step 6)
  • Delete after the database write is committed, and keep a TTL as a safety net for a delete that gets lost. (step 7)
  • Keep negative TTLs short, or a product created a minute ago will still look missing. (step 10)
UsersApp serverCache (Redis)Database

Key numbers

Hit rate
90%
Database reads
500/s
Average read
3.0 ms

Terms

Cache hit
The value was in the cache, so the read is answered from memory in about a millisecond.
Cache miss
The value was not in the cache, so the read goes on to the database.
Hit rate
The share of reads answered by the cache; it decides the average read time and the database load.
Cache-aside
The app reads the cache first and, on a miss, loads the database and fills the cache itself.
TTL (time to live)
How long a cached copy may be used before it expires.
Write-through
Every write goes to the cache and the database together.
Write-back
Writes go to the cache first and reach the database later, in batches.
Cache invalidation
Deleting a cached copy when the data changes, so the next read loads the new value.
LRU eviction
When memory is full, remove the value that was used least recently.
Cache stampede
Many requests miss the same expired key at once and all hit the database.
Cache penetration
Requests for keys that do not exist always miss and reach the database.
Negative caching
Caching "not found" for a short time so repeated misses stop at the cache.

System Design · 02. Scaling · 9 min · Beginner

Content Delivery

Put copies of your files in cities near the users.

In short

Distance costs time: 600 ms to load from Sydney when the origin is in Virginia. A CDN keeps copies in edge servers near the users, so a hit costs 30 ms.

Static files are cached according to their headers, dynamic requests still go to the origin, and a purge or a new file name replaces old copies. The origin does far less work.

Key ideas

  • You cannot make light faster, so move the data closer to the user. (step 2)
  • The edge is a cache that lives near the user. The origin is still the source of truth. (step 3)
  • Long max-age plus versioned file names gives the best of both: speed and instant updates. (step 7)

Good to know

  • Users get faster pages, and the origin does a small part of the work. Both come from the same copies. (step 5)
  • A CDN also soaks up traffic spikes and some attacks, because the edges answer most requests themselves. (step 6)

Watch out

  • Faster servers do not help here. The time is spent on the road, not in the CPU. (step 1)
  • Someone always pays for the first request. A CDN can warm popular files in advance. (step 4)
  • Prefer versioned names so you rarely need to purge. Keep purge for emergencies. (step 8)
Users in SydneyEdge: SydneyEdge: VirginiaOrigin (Virginia)240/sUsers in Virginia

Key numbers

Sydney user
30 / 230 ms
Virginia user
30 / 35 ms
Origin load
240/s

Terms

Origin server
The real server that holds your site; a CDN copies from it.
Round trip time (RTT)
The time for a message to reach a server and for the reply to come back.
Speed of light limit
Signals in fibre travel about 200,000 km a second, which sets a minimum delay over long distances.
CDN (content delivery network)
Many servers in many cities that keep copies of your files near your users.
Edge server
A CDN server in a city near users, which answers requests from its copies.
Anycast
One address announced from many places, so each user's traffic reaches the nearest one.
Edge cache miss
The edge has no copy, so it fetches the file from the origin and keeps it.
Edge cache hit
The edge already has a copy and answers right away.
Static vs dynamic content
Static files are the same for everyone and can be cached; dynamic responses differ per user.
Cache-Control header
A response header that says who may cache a response and for how long.
Versioned file names
Putting a hash in a file name so a changed file gets a new name and old copies never go stale.
Purge
Telling the CDN to delete a cached URL from all its edges at once.