Skip to lesson

Single server to many servers: how systems grow

ShopLite got popular: ten times more visitors than last month, and every page feels slower. You cannot rebuild it, so you grow it one step at a time, fixing whatever broke first.

Your turn: what breaks first?

ShopLite runs on one server, with MySQL on the same machine. Fest week brings ten times the visitors. Before you read on, think it through with a pen:

  • Which resource runs out first: app CPU, the database, the disk or the network? How would you find out?
  • What is the cheapest fix for that resource, and what new problem could the fix bring?
  • What happens to every customer if this one server restarts during the sale?

Stage 1 to 3: one server, a database server, many app servers

Load balancer is a server that receives every request and passes each one to one of several identical app servers, skipping any server that is down.

Every system starts small. Stage 1 runs the app and MySQL on one machine. Stage 2 gives MySQL its own server. Stage 3 runs several app servers behind a load balancer.

Text
Stage 1  [Phone / browser] --HTTPS--> [ one server: ShopLite app + MySQL ]Stage 2  [Clients] --> [App server] --> [MySQL server]Stage 3  [Clients] --> [Load balancer] --> [App 1 | App 2 | App 3] --> [MySQL server]

Stage 1 is cheap and fine for the first thousand users, but app and database share one CPU and disk, and one restart stops everything. Stage 2 removes the sharing. In stage 3 the app servers must keep no user data in their own memory, so any of them can answer any request.

Example 1 · Stage 1: how much one shared server can take

OneBoxCapacity.javaJava
public class OneBoxCapacity {    public static void main(String[] args) {        int cores = 4;        double appMsPerRequest = 8.0;   // CPU time spent in the Java app (JSON, rules)        double dbMsPerRequest = 2.0;    // CPU time spent inside MySQL        double cpuMsPerSecond = cores * 1000.0;
        double capacity = cpuMsPerSecond / (appMsPerRequest + dbMsPerRequest);
        System.out.println("Stage 1: app and MySQL share one 4-core server");        System.out.printf("CPU per request: %.0f ms (app %.0f + database %.0f)%n",                appMsPerRequest + dbMsPerRequest, appMsPerRequest, dbMsPerRequest);        System.out.printf("Most it can do:  %.0f requests/second%n", capacity);        System.out.printf("Safe at 70%% CPU: %.0f requests/second%n", capacity * 0.7);    }}
Output
Stage 1: app and MySQL share one 4-core server
CPU per request: 10 ms (app 8 + database 2)
Most it can do:  400 requests/second
Safe at 70% CPU: 280 requests/second

What this code does

  • Each request costs 10 ms of CPU in total, and 4 cores give 4,000 ms of CPU per second, so the box tops out at 400 requests a second.
  • Teams plan for about 70% busy, not 100%, so the safe figure is 280. Past that, response times climb quickly because requests start to queue.

Example 2 · Stage 2 and 3: adding app servers until the database limits

GrowthCapacityDemo.javaJava
public class GrowthCapacityDemo {    static final double APP_MS = 8.0;   // CPU ms per request in the app    static final double DB_MS = 2.0;    // CPU ms per request in MySQL
    static double capacity(int cores, double msPerRequest) {        return cores * 1000.0 / msPerRequest;    }
    static void stage(String name, int appServers) {        double app = appServers * capacity(4, APP_MS);        double db = capacity(4, DB_MS);        double system = Math.min(app, db);        String limit = app <= db ? "app servers" : "database";        System.out.printf("%-34s app %5.0f | db %5.0f | system %5.0f RPS (limit: %s)%n",                name, app, db, system, limit);    }
    public static void main(String[] args) {        stage("Stage 2: own DB server, 1 app", 1);        stage("Stage 3: load balancer + 3 apps", 3);        stage("Stage 3: load balancer + 5 apps", 5);    }}
Output
Stage 2: own DB server, 1 app      app   500 | db  2000 | system   500 RPS (limit: app servers)
Stage 3: load balancer + 3 apps    app  1500 | db  2000 | system  1500 RPS (limit: app servers)
Stage 3: load balancer + 5 apps    app  2500 | db  2000 | system  2000 RPS (limit: database)

What this code does

  • With its own server the database can do 2,000 requests a second, so one app server (500) is now the limit. Three app servers lift the system to 1,500.
  • Five app servers could do 2,500, but the system still stops at 2,000 because the database is now the bottleneck. More app servers stop helping; stage 4 is next.

Example 3 · A load balancer spreading requests and skipping a crashed server

LoadBalancerTrace.javaJava
import java.util.ArrayList;import java.util.List;
public class LoadBalancerTrace {    static List<String> healthy = new ArrayList<>(List.of("app-1", "app-2", "app-3"));    static int next = 0;
    // The load balancer hands each request to the next healthy server in turn.    static String pick() {        String server = healthy.get(next % healthy.size());        next++;        return server;    }
    public static void main(String[] args) {        for (int i = 1; i <= 6; i++) {            System.out.println("request " + i + " -> " + pick() + " -> MySQL");        }
        System.out.println("app-2 crashes; the balancer stops sending to it");        healthy.remove("app-2");        next = 0;
        for (int i = 7; i <= 10; i++) {            System.out.println("request " + i + " -> " + pick() + " -> MySQL");        }    }}
Output
request 1 -> app-1 -> MySQL
request 2 -> app-2 -> MySQL
request 3 -> app-3 -> MySQL
request 4 -> app-1 -> MySQL
request 5 -> app-2 -> MySQL
request 6 -> app-3 -> MySQL
app-2 crashes; the balancer stops sending to it
request 7 -> app-1 -> MySQL
request 8 -> app-3 -> MySQL
request 9 -> app-1 -> MySQL
request 10 -> app-3 -> MySQL

What this code does

  • The balancer hands requests to app-1, app-2 and app-3 in turn, so each server gets a third of the traffic.
  • When app-2 crashes it is removed from the healthy list and requests 7 to 10 go to app-1 and app-3. Users see no error, which is the point of having several app servers.

Common mistake: believing more app servers always means more speed. Read the database number next to the app number: whichever is smaller is the limit.

Predict the output

What limits the system?

Read the code and pick what it prints.

Round 1 of 2

ShopLite has four app servers and one database server. What is the most it can serve?

app servers: 4 x 500 requests/second = 2000
database: 1 x 1500 requests/second
The CPU numbers in the examples are a simplified model ("each request costs 8 ms of app CPU"), used to show which part runs out first. Real numbers come from measuring your own app.

Stage 4 and 5: cache, replicas, CDN, queue and worker

Cache is fast memory that keeps copies of popular data, such as product details, so repeated reads skip the database. If the cache is lost, the data is still safe in MySQL.

Stage 4 takes work away from the busy database. Stage 5 takes slow work out of the request. Here is the whole design on one page.

Text
Stage 4 + 5  [Clients] --> [CDN] (images, CSS, JS)  [Clients] --> [Load balancer] --> [App x3] --> [Cache]                                         |--> [(MySQL primary)] (writes) ..copies..> [(Read replicas)] (reads)                                         ..> [[Queue]] --> [Worker] --> email / SMS / invoice

Read replicas are copies of the database that serve read queries while the primary takes all writes. A CDN (content delivery network) is a set of servers close to users that serve images, CSS and JavaScript, so those requests never reach your app.

At checkout, ShopLite saves the order and puts a job such as "send the confirmation email" in a queue. A separate worker program takes jobs from the queue and does them in the background, so the customer gets the answer at once.

ShopLite after stage 5. A phone gets files from a CDN and other requests from a load balancer, which spreads them over three app servers. The app reads hot data from a cache, writes to the MySQL primary, which copies to read replicas, and queues slow jobs for a worker.
One good design: every box answers a bottleneck from the stages before.

Example 4 · Stage 4 and 5: the path of each request

RequestPathTrace.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class RequestPathTrace {    static Map<Integer, String> cache = new HashMap<>();    static List<String> emailQueue = new ArrayList<>();
    static String productPage(int productId) {        String name = cache.get(productId);        if (name != null) {            return "LB -> app -> cache HIT (" + name + ")";        }        name = "Product-" + productId;          // pretend this came from a read replica        cache.put(productId, name);        return "LB -> app -> cache MISS -> read replica -> saved in cache";    }
    static String checkout(int orderId) {        emailQueue.add("email for order " + orderId);        return "LB -> app -> primary DB (write) -> queue +1 job -> 201 Created";    }
    public static void main(String[] args) {        System.out.println("GET  /logo.png        CDN edge HIT (never reaches the app)");        System.out.println("GET  /products/1      " + productPage(1));        System.out.println("GET  /products/1      " + productPage(1));        System.out.println("GET  /products/2      " + productPage(2));        System.out.println("POST /orders          " + checkout(501));        System.out.println("POST /orders          " + checkout(502));
        System.out.println("Worker (background):");        for (String job : emailQueue) {            System.out.println("  sent " + job);        }    }}
Output
GET  /logo.png        CDN edge HIT (never reaches the app)
GET  /products/1      LB -> app -> cache MISS -> read replica -> saved in cache
GET  /products/1      LB -> app -> cache HIT (Product-1)
GET  /products/2      LB -> app -> cache MISS -> read replica -> saved in cache
POST /orders          LB -> app -> primary DB (write) -> queue +1 job -> 201 Created
POST /orders          LB -> app -> primary DB (write) -> queue +1 job -> 201 Created
Worker (background):
  sent email for order 501
  sent email for order 502

What this code does

  • The logo is served by the CDN and never reaches the app. The first read of product 1 misses the cache and goes to a read replica; the second read is a cache hit.
  • Checkout writes to the primary database, adds a job to the queue and answers at once. The worker sends the emails afterwards, outside the customer's request.

The price of this design is old data: a cache and a replica can lag behind the primary by a moment, so a just-placed order may not show up for a second. Reads that must be fresh go to the primary.

Order of execution

Order a product page request

A product page is not in the cache yet. Put the hops in order.

Which bottleneck triggers each step

Bottleneck is the one resource that runs out first and limits the whole system. You find it by measuring, then add only the step that relieves it, usually before the resource passes 70% busy.

Growing is not guessing. Measure app CPU, database load, disk and network, find the busiest, and fix only that one. The example does this for five ShopLite snapshots.

Example 5 · Matching the busiest resource to the next step

BottleneckFinder.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
record Snapshot(String when, int appCpu, int dbConnections, int dbDisk, int network) {}
public class BottleneckFinder {    static final int LIMIT = 70;   // act before a resource passes 70% busy
    static String advice(Snapshot s) {        Map<String, Integer> usage = new LinkedHashMap<>();        usage.put("app CPU", s.appCpu());        usage.put("DB connections", s.dbConnections());        usage.put("DB disk", s.dbDisk());        usage.put("network", s.network());
        String worst = null;        int worstValue = 0;        for (Map.Entry<String, Integer> e : usage.entrySet()) {            if (e.getValue() > worstValue) {                worst = e.getKey();                worstValue = e.getValue();            }        }        if (worstValue <= LIMIT) {            return "all below " + LIMIT + "%: no change needed";        }        String fix = switch (worst) {            case "app CPU" -> "add app servers behind a load balancer";            case "DB connections" -> "cache hot reads, shorten queries";            case "DB disk" -> "add indexes, read replicas for reads";            default -> "serve images and files from a CDN";        };        return worst + " at " + worstValue + "% -> " + fix;    }
    public static void main(String[] args) {        List<Snapshot> snapshots = List.of(                new Snapshot("Launch week", 35, 20, 15, 10),                new Snapshot("College fest sale", 92, 40, 30, 25),                new Snapshot("After 4 app servers", 45, 88, 50, 30),                new Snapshot("Big catalogue", 40, 45, 85, 35),                new Snapshot("Photo-heavy pages", 40, 35, 40, 90));
        for (Snapshot s : snapshots) {            System.out.printf("%-20s %s%n", s.when(), advice(s));        }    }}
Output
Launch week          all below 70%: no change needed
College fest sale    app CPU at 92% -> add app servers behind a load balancer
After 4 app servers  DB connections at 88% -> cache hot reads, shorten queries
Big catalogue        DB disk at 85% -> add indexes, read replicas for reads
Photo-heavy pages    network at 90% -> serve images and files from a CDN

What this code does

  • advice finds the busiest resource in each snapshot. If it is above 70%, the switch names the growth step that relieves that resource.
  • The order of the snapshots is a typical story: first app CPU, then database connections after more app servers arrive, then disk reads, then network for images.

One line per bottleneck:

  • App CPU high: add app servers behind a load balancer.
  • Database connections or CPU high: cache hot reads, tune queries.
  • Database disk busy with reads: indexes first, then read replicas.
  • Network full of files: a CDN. Slow work inside requests: queue and worker.

Single points of failure at every stage

SPOF (single point of failure) is a critical part with only one copy: if it fails, the whole system stops. You remove it with a second copy that can take over.

A chain breaks at its weakest link. Look at ShopLite's design and ask of every box: if it dies, does everything stop? The example marks each part for two stages.

Example 6 · Finding single points of failure in two stages

SpofFinder.javaJava
import java.util.List;
// critical = if every copy of it is down, ShopLite stops workingrecord Component(String name, int copies, boolean critical) {}
public class SpofFinder {    static void report(String stage, List<Component> parts) {        System.out.println(stage);        for (Component c : parts) {            String status;            if (c.critical() && c.copies() == 1) {                status = "SINGLE POINT OF FAILURE";            } else if (!c.critical()) {                status = "failure only slows things down";            } else {                status = "ok (" + c.copies() + " copies)";            }            System.out.printf("  %-16s %s%n", c.name(), status);        }    }
    public static void main(String[] args) {        report("Stage 3", List.of(                new Component("load balancer", 1, true),                new Component("app server", 3, true),                new Component("MySQL", 1, true)));
        report("Stage 4, hardened", List.of(                new Component("load balancer", 2, true),                new Component("app server", 3, true),                new Component("cache", 1, false),                new Component("MySQL + standby", 2, true)));    }}
Output
Stage 3
  load balancer    SINGLE POINT OF FAILURE
  app server       ok (3 copies)
  MySQL            SINGLE POINT OF FAILURE
Stage 4, hardened
  load balancer    ok (2 copies)
  app server       ok (3 copies)
  cache            failure only slows things down
  MySQL + standby  ok (2 copies)

What this code does

  • A part is a SPOF when it is critical and has only one copy. In stage 3 both the load balancer and MySQL are SPOFs, even though there are three app servers.
  • The hardened stage adds a second load balancer and a standby database. The cache stays a single copy, which is acceptable because losing it only slows pages down.

In stage 3 the app servers are safe, but the load balancer and the database usually still are SPOFs. Fixes are a second load balancer and a standby database that is promoted when the primary dies. Some parts are not critical: if the cache fails, pages get slower because reads go to MySQL, but nothing stops.

Find the bug

Find the single point of failure

Select the line that is wrong.

ShopLite's request path. Tap the box that can stop every order.

Round 1 of 2

Next step

Check your understanding

11 quick questions