Foundations

Scalability

How a system grows from one server to many: scale up first, make services stateless, then scale reads and writes separately by removing one bottleneck at a time.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A small team runs a booking site on one server: a web app and a PostgreSQL database on a machine with 8 cores and 32 GB of memory. It serves 50 requests a second comfortably. Then a marketing campaign works. Traffic triples, and by Friday evening CPU sits at 95%, pages take four seconds and some requests time out.

The first fix is a bigger machine with 32 cores and 128 GB. The resize costs a few minutes of downtime and no code changes, and the problem goes away. This is vertical scaling, and it is the right first move.

Six months later traffic has tripled again, and the team notices two things a bigger machine cannot fix. There is a largest machine on the price list. And, more pressing, whenever this one server restarts for a kernel patch or a failed disk, the whole business is offline. Every deployment is a risk to everything.

What the team needs is for capacity to grow by adding machines, not by replacing one, and for the site to survive the loss of any single machine. That is horizontal scaling, and it changes how the application has to be written. A system is scalable when adding resources gives it close to proportionally more capacity. The rest of this lesson is about how to get there.

Vertical and horizontal scaling

Vertical (scale up) Horizontal (scale out)
How A bigger machine More machines
Code changes None Stateless services, replicated or partitioned data
Ceiling The largest machine available No hard ceiling, but coordination costs grow
Failure One machine is one point of failure Survives the loss of a machine
Operations Simple Load balancing, fleet deployments, distributed-systems problems

When to scale up. First, and for as long as it is cheap. A single modern server can have a hundred or more cores and hundreds of gigabytes of memory, and a well-indexed relational database on that hardware can serve many thousands of queries a second. Stack Overflow, by its engineers’ own published accounts, served a very large site for years from a small number of web servers and a scaled-up SQL Server.

When to scale out. When you must survive a machine failure, when the load exceeds the largest sensible machine, or when demand swings enough that adding and removing machines saves money.

When not to scale out. When the thing in question is a database that fits on one machine. Distributing it adds failure modes and removes none of your load problems.

In practice you do both. The app tier scales out early, because it can be made stateless cheaply. The database scales up for as long as possible, because distributing data is hard.

Stateless services

A load balancer can send a request to any server only if every server can handle it. That fails when one server holds something between requests that the others lack. The usual culprits, and where each should go:

  • Sessions in server memory. Move them to a shared store such as Redis, or into a signed token that the client sends with each request. See authentication and authorisation.
  • Uploaded files on local disk. Move them to object storage.
  • In-process caches. Fine as an optimisation. If correctness depends on the cache, use a shared one.
  • Scheduled jobs. A cron entry on every server runs the job once per server. Use one scheduler, or a lock.
  • Long-lived connections. A WebSocket is state by nature, so it needs a routing layer that knows which server holds which user. See real-time communication.

The state does not disappear. You push it into a few services built to hold it: a database, a cache, an object store, a queue. The app tier then becomes disposable. Servers can be added, removed and replaced at will, which is what makes autoscaling and rolling deployments possible.

Load balancer

Open full screen

Round robin

Each server in turn, whatever it is already doing.

  • S10
  • S20
  • S30
  • S40
Peak on one server
0
Gap, busiest to idlest
0
Completed
0

Least connections

Whichever server has the fewest requests in flight.

  • S10
  • S20
  • S30
  • S40
Peak on one server
0
Gap, busiest to idlest
0
Completed
0

Both pools receive the same 500 requests. Blue blocks are quick; red ones take 12 times longer. With no slow requests the two behave alike. Add slow ones and round robin keeps stacking new work on servers that are already stuck. Sent 0 of 500.

Send a mix of fast and slow requests through the simulator and compare the two algorithms: round robin keeps handing work to a server that is already stuck on slow requests, and least connections does not. Load balancing goes further.

Scaling reads and scaling writes

Once the app tier scales out, the database becomes the constraint. Reads and writes need different treatment.

Reads are the easier half, because a copy can answer them:

  • Read replicas apply the primary’s changes and serve queries. They lag slightly, so a read may be stale. See replication and consistency models.
  • Caches answer repeated reads from memory. See caching patterns.
  • CDNs serve static and cacheable content from locations near the user.

All three trade freshness for capacity.

Writes are harder. Every write must reach the authoritative copy, and replicas do not help, since each replica has to apply every write too. The options, cheapest first:

  1. A bigger primary, and tuning. Batch small writes, drop unused indexes, use faster disks.
  2. A queue to absorb bursts. This smooths peaks but does not raise the sustained rate. See backpressure.
  3. Split by function. Move a write-heavy feature, such as event logging, to its own database.
  4. Shard. Split one dataset across many primaries by a key. You pay for it with cross-shard queries, harder transactions, rebalancing and hot keys. See sharding.

Think in bottlenecks

A system’s throughput is set by its most constrained resource, and adding capacity anywhere else changes nothing. So measure before you change anything. For each tier, look at CPU, memory, disk I/O and network, and at limits such as connection counts and lock contention. Fix whichever saturates first, then expect the bottleneck to move.

A common example: 20 app servers each hold a pool of 30 database connections, 600 in all. To handle more traffic, the team doubles the app tier, and 1,200 connections now arrive at one PostgreSQL primary. PostgreSQL gives every connection its own process, so each one costs memory and scheduling work, and its default limit is just 100. The database gets slower, not faster. The fix is a connection pooler such as PgBouncer, or the read scaling described above. Adding capacity upstream of a bottleneck makes it worse.

Scaling out is also rarely linear. Servers share things, such as the database, a lock or a network link, so the tenth server adds less than the second did.

The typical evolution

From one server to a scaled-out system9 components: Users, Load balancer, App server 1, App server 2, Shared cache, Primary database, Read replica, Job queue, Workers. Connections: Users to Load balancer; Load balancer to App server 1; Load balancer to App server 2; App server 1 to Shared cache; App server 2 to Shared cache; App server 1 to Primary database (writes); App server 2 to Read replica (reads); Primary database to Read replica (replication); App server 2 to Job queue (slow jobs); Job queue to Workers; Workers to Primary database.UsersLoad balancerApp server 1app + databaseApp server 2Shared cacheRedisPrimarydatabaseRead replicaJob queueWorkerswritesreadsreplicationslow jobs

Step 1 of 8

Everything starts on one machine. The web app and its database share a single server. It is cheap, simple and easy to reason about, and it is the right design until something measurable runs out.

Read the steps as text
  1. Everything starts on one machine. The web app and its database share a single server. It is cheap, simple and easy to reason about, and it is the right design until something measurable runs out.
  2. The first moves are to buy a bigger machine and then to give the database a server of its own. The app and the database stop competing for CPU, memory and disk, and each can be sized separately.
  3. One app server is still a single point of failure, and it has a ceiling. Add a second server behind a load balancer. This only works if the servers are stateless, so sessions move out of server memory into a shared store.
  4. Now the database is the bottleneck, and most of its work is reads. Add a read replica that copies every change from the primary. Writes still go to the primary. Reads that can tolerate slightly stale data go to the replica.
  5. Many reads ask for the same few things. Keep those in the cache, so a popular profile or product page is answered from memory and never reaches the database at all.
  6. Some requests trigger slow work, such as sending email or resizing images. Hand that work to a queue and reply to the user straight away. Workers drain the queue at their own pace, which also smooths out traffic spikes.
  7. Eventually writes outgrow one primary. Replicas and caches cannot help, because they only serve reads. Split the data across several primaries by a key such as user ID. This is sharding. It is the most expensive step, so it comes last.
  8. Each step removed the bottleneck that existed at the time, and each added something you now have to operate. In an interview, name the bottleneck first, then the smallest change that removes it.
From one server to a scaled-out system
  1. One server runs everything.
  2. The database moves to its own machine, and both scale up.
  3. Several stateless app servers sit behind a load balancer.
  4. Read replicas and then a cache take over most reads.
  5. Queues and workers take slow or bursty work off the request path.
  6. Sharding arrives when writes or data size exceed one primary.

In the interview

Bring this up when your estimates show that one machine is not enough, or when the interviewer asks “how does this scale to ten times the load?”.

A strong answer names the bottleneck first: “At 35,000 reads a second the primary runs out long before the app tier does.” Then it proposes the smallest change that removes it, says what that costs (staleness, complexity, money), and says what breaks next. State that the app tier is stateless and say where sessions live. Treat reads and writes separately.

Do not open with sharding. Say when you would need it: “One primary handles 400 writes a second for years. I would shard when the write rate or the data size approaches what one machine can hold, and I would choose a shard key now so that the move stays possible.”

Key takeaways

  • Scale up while it is cheap and safe, then scale out. A bigger machine needs no code changes. More machines need a design that tolerates them.
  • The app tier can only scale out when servers are stateless. Sessions, files and scheduled jobs must move to shared services.
  • Reads scale with replicas, caches and CDNs, at the price of some staleness. Writes are harder and end in partitioning the data.
  • Find the bottleneck by measuring, fix that one thing, and expect the bottleneck to move somewhere else.
  • The usual order is: separate the database, add app servers behind a load balancer, add replicas and a cache, move slow work to queues, and shard last.
  • Every step adds operational cost. Do not take a step the numbers do not yet require.

Try it

Check yourself

1. A web tier keeps user sessions in each server's memory. What happens when a second server is added behind a round-robin load balancer?
2. A database primary is at 85% CPU, and monitoring shows that 95% of its queries are reads. Which change gives the most relief for the least risk?
3. Why does putting a queue in front of a database not raise its sustained write capacity?
4. A team doubles its app servers from 20 to 40, and the site gets slower. Each server keeps a pool of 30 connections to one PostgreSQL primary. What is the most likely cause?
5. When is vertical scaling the right choice?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Vertical and horizontal scaling

Vertical: a bigger machine. Simple, with no code changes, but it has a ceiling and is a single point of failure. Horizontal: more machines. No hard ceiling and it survives failures, but it needs load balancing and stateless or partitioned design.

What makes a service stateless?

Any server can handle any request, because nothing needed between requests lives in one server's memory or on its local disk. State goes to a database, a cache, object storage or a token held by the client.

Three ways to scale reads

Read replicas, caches and CDNs. Each serves a copy, so each accepts some staleness.

Ways to scale writes, cheapest first

A bigger primary and tuning, a queue to absorb bursts, splitting data by function into separate databases, and finally sharding by key.

Why are sticky sessions only a stop-gap?

They pin each user to one server, so load is uneven, a server that dies takes its users' sessions with it, and scaling in or deploying drops sessions. A shared session store or signed token removes the problem.

What is the bottleneck rule?

Throughput is set by the most constrained resource. Improving anything else changes nothing, and once you fix the bottleneck it moves somewhere else.

Review the deck