AlgoViz

Horizontal scaling

easy 25 min

Horizontal scaling, or scaling out, means adding machines and sharing the load between them.

Video lesson · Chapter 1 of 5

A checkout machine vanishes

0:00 / 3:13

Horizontal scaling

1:08Reel

Theory

Read or listen first. About 2 min.

What it is

Horizontal scaling means running the same program on several machines at once and splitting the work between them. When there is more work, you add machines. When there is less, you remove some.

From the outside it still looks like one system. People use one address, and something in front decides which machine answers each request. Each machine is ordinary and can be replaced. The group is what has to stay up.

Why it exists

One machine has a largest size, stops when it fails, and must be paid for at its busiest size all day. Many smaller machines remove all three limits: you can keep adding them, one can fail while the others work, and the number can follow the traffic.

The price is coordination. Several machines have to agree on who is logged in, which version of the data is right and who does what. Most of the work in scaling out is making the program not care which machine it runs on.

A short history

  1. 1994

    Engineers at NCSA describe a scalable web server: several identical machines behind one name, with DNS handing out their addresses in turn.

  2. 1997

    Fox and colleagues at Berkeley publish Cluster-Based Scalable Network Services, showing Internet services built from many ordinary workstations.

  3. 2003

    Google describes its search cluster in IEEE Micro: thousands of commodity PCs, with reliability provided by software instead of expensive servers.

  4. 2009

    Amazon launches Elastic Load Balancing, Auto Scaling and CloudWatch. Adding machines can follow a metric.

  5. 2015

    Kubernetes 1.0 is released. Copies of a program become a number you declare, and the platform keeps that many running.

Words to know

Instance
One running copy of the program, on its own machine or container.
Replica
Another word for a copy. In databases, a copy of the data.
Load balancer
The part that receives every request and picks an instance for it.
Stateless
Keeps nothing between requests that another instance would need.
Scale out and scale in
Add instances and remove instances.
Cooldown
A pause after a change, so the next decision uses fresh measurements.
Draining
Letting an instance finish its current requests before it stops.

How it works

Step through the idea, or press Play.

Step 1 of 3

Make servers interchangeable. Move sessions, files and data out of the server, so any copy can answer any request

Understand it

Start here

Friends with backpacks

In vertical scaling one pupil bought bigger and bigger backpacks, until the shop had nothing bigger. Now imagine the pupil asks friends to help. Together they carry far more, and one friend can be ill without every book staying behind.

One backpack becomes many
1 bag: 40 books

The bags stay ordinary. What changed is their number, the person who shares the books out, and the shared list.

The idea

What it is, and what it is not

Horizontal scaling is

  • Adding more server instances
  • Distributing load across machines
  • Using a load balancer
  • Running several replicas of the same program
  • Scaling with demand (auto-scaling)

Horizontal scaling is not

  • Making one server bigger
  • Adding CPU or RAM to it
  • Upgrading its hardware
  • Running one powerful machine
  • Keeping a single point of failure

Growing a fleet

StageServersCapacityRunning at 70%
Start1100 req/s70 req/s
Growing3300 req/s210 req/s
Scaled6600 req/s420 req/s
Assumes 100 requests a second for each server, measured by a load test, and a shared part that is not yet the limit.

Architecture

The whole picture

The old picture for this is a busy pizza shop. When orders pile up, the shop does not ask one chef to cook faster. It hires more chefs, and a manager gives each one orders. When it is quiet, some chefs go home.

One address, many interchangeable servers

Users send requests to a load balancer inside our system. It spreads them over three separate machines, each its own box running the same service. All three use the same shared parts: Redis for sessions and cache, PostgreSQL for data and S3 for files.
Each thick box is one machine. Nothing a user needs lives in only one of them.
  1. 1

    Load balancer

    The traffic officer. It picks a server with a rule such as round robin or least connections, checks the servers' health continuously, and is often where TLS ends. Examples: NGINX, HAProxy, AWS ALB. See load balancing.

  2. 2

    Auto-scaling

    Watches CPU, memory or requests per server. Scales out above the target and in when traffic is low. A cooldown or stabilization window prevents constant adding and removing.

  3. 3

    Stateless design

    No session in local memory and no files on the local disk. Every request carries or looks up what it needs, so any server can handle it and servers are easy to add and remove.

  4. 4

    Shared storage

    A database for durable data, Redis for sessions and cache, and object storage such as S3 for files. Every server reads the same data.

Two requests, two servers, one user

Server B has never seen this user. It does not need to have.

Auto-scaling

How the number of servers is chosen

The simplest rule uses two thresholds: add a server above 80% CPU, remove one below 30%. Target tracking is usually better: name the level you want and let the formula say how many servers reach it.

Target tracking, as the Kubernetes autoscaler does it

desired=⌈current×metric nowmetric wanted⌉⌈4×9060⌉=6\text{desired} = \left\lceil \text{current} \times \frac{\text{metric now}}{\text{metric wanted}} \right\rceil \qquad \left\lceil 4 \times \tfrac{90}{60} \right\rceil = 6
Four servers at 90% CPU with a target of 60% become six. Kubernetes skips the change when the ratio is within 10% of 1, and by default waits for a 300-second window before it scales in.

Scale out, scale in, or wait

Scale out fast and in slowly. A server added too early costs a little; one missing at the peak costs users.

Auto-scaling is a control loop

A control loop: three machines in a fleet send CPU and request metrics to Prometheus, the autoscaler reads them and sets the number of machines in the fleet, which the load balancer then uses.
It reacts after the fact. The delay is metric interval, plus decision, plus boot time, plus warm-up.

Which metric to follow

MetricGood whenCareful
CPUWork is computationUseless if servers wait on a database
MemoryMemory really follows loadMany programs never give memory back, so it blocks scaling in
Requests per serverRequests cost about the sameNeeds a load-tested limit
Queue length or ageBackground workersUse backlog per worker, not the total
ScheduleKnown peaks, such as 9:00Combine with a reactive rule

Capacity

How many servers do you need?

Servers for a peak, with one to spare

n=⌈peaklimit per server×target use⌉+spare⌈600100×0.7⌉+1=9+1=10n = \left\lceil \frac{\text{peak}}{\text{limit per server} \times \text{target use}} \right\rceil + \text{spare} \qquad \left\lceil \tfrac{600}{100 \times 0.7} \right\rceil + 1 = 9 + 1 = 10
600 requests a second at peak, 100 per server at its limit, run at 70%. If the ten run in two zones, check that five can carry the peak: 600 / 5 = 120 each, so no. Surviving a zone needs more.

From users to servers: a worked example

  1. 1

    Requests a day

    Assume 1 million people make 17 requests a day each: 17 million. Divided by 86,400 that is about 197 a second on average; dividing by 100,000 in your head gives 170.

  2. 2

    Peak

    Three times the average: about 590, say 600 a second.

  3. 3

    Servers

    At 70 useful requests a second each, 9 servers. Add one so that losing a server is not an incident: 10.

  4. 4

    Cost

    With an assumed 0.05anhoureach,tenserverscost0.05 an hour each, ten servers cost 0.50 an hour, or $365 for a 730-hour month. At night, 3 servers may be enough.

Why ten times the servers is not ten times the work

C(N)=N1+α(N−1)+βN(N−1)α=0.05, β=0.001:;C(10)≈6.5, C(31)≈9.0, C(60)≈8.0C(N) = \frac{N}{1 + \alpha (N-1) + \beta N (N-1)} \qquad \alpha = 0.05,\ \beta = 0.001:; C(10) \approx 6.5,\ C(31) \approx 9.0,\ C(60) \approx 8.0
The Universal Scalability Law. Alpha is waiting for something shared, beta is the cost of keeping copies in agreement. With any beta above zero there is a point where more machines make the system slower, here around 31. The two values are an example; you fit them to your own load test.

Patterns

Ways to split the work

Think of a team in a video game. With stateless players nobody carries items; everything is in a shared chest. With sharding the map is split, and each player guards one zone. With read replicas several players can look at the map, but one draws it.

  • Stateless services

    Any server handles any request. Easy to add servers, no sticky sessions, and a server's death loses no state.

  • Shared nothing

    Each node owns its own CPU, memory and data. No shared bottleneck and little coordination, as long as a request needs one node.

  • Sharding

    Split the rows, for example by user_id % 3. Spreads writes and data. Queries across shards get hard. See sharding.

  • Microservices

    Scale only what is busy: auth x2, orders x5, payments x3. Deploy separately and choose technology per service. Calls that were local now cross a network.

Read replicas

Good when most traffic is reads. Replicas help with reads only: every replica still applies every write, and it may be a moment behind.

Worked example: 10,000 queries a second of which 90% are reads. The primary keeps 1,000 writes. Three replicas share 9,000 reads, so 3,000 each, plus the 1,000 writes every one of them replays.

Challenges

What gets harder

Remember a group project at school. One person always knows which version is the latest. Five people need a rule for it. More helpers means more coordination.

ChallengeWhat goes wrongWhat to do
StateRequest 1 logs in on server A. Request 2 lands on B: "Who are you?"Sessions in Redis or Memcached, or a signed token
ConsistencyTwo servers read the same value and both writeTransactions, conditional updates, one owner per key
NetworkClient, balancer, app, cache, database: every hop adds time and can failConnection pools, caching, async work, timeouts
OperationsMore parts: metrics, logs, traces, alerts, perhaps a mesh and an orchestratorManaged services first, then Kubernetes, Prometheus, Grafana as needed. See operability

The race two servers can lose

Server B's write erased server A's. This is a lost update.
SQL
-- The database decides in one step. If no row changes, there was not enough money.UPDATE accounts   SET balance = balance - 50 WHERE id = 7 AND balance >= 50;
A conditional update is enough here. Transactions with row locks, or an append-only record of events, solve bigger versions. A distributed lock is the last choice, because it can expire while you still think you hold it.

Where the session lives

StrategyHowGoodBad
Sticky sessionsThe balancer sends a user to the same server each timeNo code changeUneven load, and the server's death logs people out
Central storeAll servers share Redis or MemcachedAny server works. The usual choiceOne more part, which must be available
Signed token (JWT)The client carries its own stateNo lookupHard to revoke before it expires, sent with every request, keep secrets out

Availability

More servers, fewer outages?

Independent copies, then the parts in series

1−(1−0.999)2=0.9999990.999999×0.9999×0.9995≈0.99941 - (1 - 0.999)^2 = 0.999999 \qquad 0.999999 \times 0.9999 \times 0.9995 \approx 0.9994
Two servers at 99.9% would give 99.9999% if their failures were independent. Behind one balancer at 99.99% and one database at 99.95% the user gets about 99.94%. The weakest part decides. All inputs are assumptions.

Copies in one rack, running one bad release, are not independent. Spread them over zones, release to a few first, and give the balancer and the database a spare too. Details: high availability and resilience.

What happens when a server dies

  1. 1

    Detect

    Health checks fail, for example 3 times, 5 seconds apart: up to about 15 seconds.

  2. 2

    Stop sending

    The balancer removes the server. Requests already there fail and must be retried safely.

  3. 3

    Absorb

    With n servers, each survivor gets n / (n - 1) of its old load. From 4 servers at 60% to 3 at 80%.

  4. 4

    Replace

    The auto-scaler starts a new one. Traffic returns when it is ready, not when it has booted.

Compare

Out or up?

AspectVertical (up)Horizontal (out)
ScalabilityLimited by the largest machineVery high, limited by shared parts and coordination
Downtime to growRestart, or a switchoverNone if servers drain properly
ComplexityOne nodeDistributed
Cost at scaleSpecial large machinesOrdinary machines, plus the cost of running many
Fault toleranceSingle point of failureRedundancy, if every layer has it
Code changesNoneStateless, safe to retry
Data consistencySimple, one copyNeeds a design
MaintenanceOne serverAutomation, because nobody patches 50 by hand
Bold marks the stronger side.

Scale out when

  • You need high availability, such as 99.99%
  • Traffic is variable or spiky
  • You are outgrowing the biggest sensible machine
  • Users are in several regions
  • The services are already stateless

Stay vertical when

  • You are starting out with an MVP
  • Load is steady and predictable
  • The work is database-heavy with one writer
  • A simple architecture matters more
  • You need a quick win this week

Decision

Most systems use both: the web tier out, the database up until its limit is in sight.

Checklist

Ready to scale out?

  1. 1

    Nothing personal on the server

    Sessions, uploads, scheduled jobs and in-memory counters have a shared home.

  2. 2

    Start fast, stop politely

    A readiness check before traffic, draining before a stop, and no work that must not be lost.

  3. 3

    Retries are safe

    The same request twice has the same effect as once.

  4. 4

    The shared parts have room

    Multiply database connections by the maximum number of servers: 40 servers with pools of 20 is 800 connections.

  5. 5

    Limits both ways

    A minimum that survives a failure, a maximum that protects the database and the bill.

Summary

The whole topic in one minute.

Horizontal scaling adds machines instead of making one bigger. A load balancer spreads requests, health checks take broken machines out, and an auto-scaler changes the number as traffic changes.

It works when servers are stateless and the shared data can keep up. The database, sessions and coordination become the new limits, so most systems scale the web tier out and the database up until the numbers say otherwise.

  • Scaling out adds machines behind a load balancer.
  • Stateless servers make it possible; shared sessions, files and data make it correct.
  • Desired servers = ceil(current x metric now / metric wanted). Out fast, in slowly.
  • Size for the peak plus a failure, then check the database and its connections.
  • Growth ends at coordination: there is a point where one more machine does not help.

Sources