Vertical vs horizontal scaling
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite got popular and its one server hits 100% CPU every evening. You can buy a bigger machine or add more of the same one, and the right choice comes from numbers.
Your turn: 100 times the users
The expected sale peak is 4,000 requests per second (RPS), and a load test says one ShopLite server handles 500 RPS. Write your answers down first, then compare them with the sections below.
- How many servers would you run, and why not exactly 8?
- Would you buy one huge machine or many small ones? Give one reason for each.
- A seller uploads a product photo and the next customer gets a 404 for it. What did you forget about having several servers?
Scale up vs scale out
Vertical scaling (scale up) is moving the app to a bigger machine with more CPU, memory or faster disks. It needs no code change, but there is always a largest machine.
Example 1 compares one machine growing in size with several small machines, using simplified prices.
Example 1 · Cost and limits of scaling up vs scaling out
public class ScaleUpVsOutDemo { record Machine(String size, int vcpus, int rps, int rupeesPerMonth) { }
public static void main(String[] args) { // Made-up but realistic shape: bigger machines cost more per unit of power, and there is a largest size Machine[] sizes = { new Machine("small", 2, 500, 6_000), new Machine("medium", 4, 1_000, 12_500), new Machine("large", 8, 1_900, 27_000), new Machine("xlarge", 16, 3_500, 60_000), new Machine("2xlarge", 32, 6_000, 1_30_000)}; // the biggest size on offer
System.out.println("Scale up (one bigger machine):"); for (Machine m : sizes) { System.out.printf(" %-8s %2d vCPU %5d rps Rs %7d/month Rs %5.1f per rps%n", m.size(), m.vcpus(), m.rps(), m.rupeesPerMonth(), (double) m.rupeesPerMonth() / m.rps()); }
System.out.println("Scale out (more small machines):"); Machine small = sizes[0]; for (int count : new int[] {2, 4, 8, 16}) { System.out.printf(" %2d x small %5d rps Rs %7d/month Rs %5.1f per rps%n", count, count * small.rps(), count * small.rupeesPerMonth(), (double) small.rupeesPerMonth() / small.rps()); } System.out.println("Need 8,000 rps: no single machine is big enough; 16 small servers are."); }}Scale up (one bigger machine): small 2 vCPU 500 rps Rs 6000/month Rs 12.0 per rps medium 4 vCPU 1000 rps Rs 12500/month Rs 12.5 per rps large 8 vCPU 1900 rps Rs 27000/month Rs 14.2 per rps xlarge 16 vCPU 3500 rps Rs 60000/month Rs 17.1 per rps 2xlarge 32 vCPU 6000 rps Rs 130000/month Rs 21.7 per rps Scale out (more small machines): 2 x small 1000 rps Rs 12000/month Rs 12.0 per rps 4 x small 2000 rps Rs 24000/month Rs 12.0 per rps 8 x small 4000 rps Rs 48000/month Rs 12.0 per rps 16 x small 8000 rps Rs 96000/month Rs 12.0 per rps Need 8,000 rps: no single machine is big enough; 16 small servers are.
What this code does
- Each step up in size costs more per request per second: Rs 12 for the small machine, Rs 21.7 for the largest. And 6,000 RPS is the ceiling.
- Small machines keep the same cost per RPS and can go past any single machine: 16 of them reach 8,000 RPS.
Scaling up is the easy first step, but prices grow faster than power at the top end, one machine is still one point of failure, and resizing it usually means a restart.
Horizontal scaling (scale out) means running several copies of the app on ordinary machines, with a load balancer spreading requests between them. Capacity grows in small, cheap steps, there is no hard ceiling, and losing one machine removes only part of the capacity. The cost is that the app must be built so any copy can handle any request.
What must be true to scale out
Stateless server is a server that keeps nothing a later request needs in its own memory or disk, so any copy can answer any request and copies can be added or removed freely.
Example 2 saves a seller's image on one server's disk and then asks a second server for it.
Example 2 · A file on one server's disk is missing on the other
import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;
class AppServer { final String name; final Set<String> localDisk = new HashSet<>(); // files saved on this machine only final Map<String, String> sharedStorage; // stands in for object storage (S3-like)
AppServer(String name, Map<String, String> sharedStorage) { this.name = name; this.sharedStorage = sharedStorage; }
void uploadToLocalDisk(String file) { localDisk.add(file); }
String readFromLocalDisk(String file) { return localDisk.contains(file) ? "200 OK" : "404 Not Found"; }
void uploadToSharedStorage(String file) { sharedStorage.put(file, "bytes"); }
String readFromSharedStorage(String file) { return sharedStorage.containsKey(file) ? "200 OK" : "404 Not Found"; }}
public class LocalDiskUploadDemo { public static void main(String[] args) { Map<String, String> objectStorage = new HashMap<>(); List<AppServer> servers = List.of(new AppServer("server-1", objectStorage), new AppServer("server-2", objectStorage)); String image = "products/kurta-blue.jpg";
System.out.println("Seller uploads the image, the request lands on server-1"); servers.get(0).uploadToLocalDisk(image); for (AppServer s : servers) { System.out.println(" local disk: GET via " + s.name + " -> " + s.readFromLocalDisk(image)); }
servers.get(0).uploadToSharedStorage(image); for (AppServer s : servers) { System.out.println(" shared storage: GET via " + s.name + " -> " + s.readFromSharedStorage(image)); } }}Seller uploads the image, the request lands on server-1 local disk: GET via server-1 -> 200 OK local disk: GET via server-2 -> 404 Not Found shared storage: GET via server-1 -> 200 OK shared storage: GET via server-2 -> 200 OK
What this code does
- The seller's upload lands on server-1, so only server-1's local disk has the image; a customer routed to server-2 gets 404.
- Saved in shared object storage (an S3-like service, a
Maphere), the image is found through every server, so servers can be added or removed freely.
Login state lives in a JWT or a shared session store, carts in Redis or the database, uploaded files in object storage, and every server talks to the same database and cache.
The Backend Architecture module showed sessions kept in server memory. Files are the other common trap: an image saved on server-1's disk returns 404 when the next request lands on server-2.
Find the bug
Find the state that blocks scaling
Each snippet keeps state on one server. Tap the wrong line, then read the fix.
After a second server is added, customers see empty carts at random.
Round 1 of 2Auto-scaling in plain words
Auto-scaling is adding or removing servers automatically based on a metric, usually average CPU or requests per second per server.
Example 3 replays an 8 pm flash sale minute by minute and shows when the scaler adds servers.
Example 3 · An auto-scaler during an 8 pm flash sale
public class AutoScalerDemo { static final int RPS_PER_SERVER = 500; // one server is "100% busy" at 500 rps static final int MIN = 2; static final int MAX = 10;
public static void main(String[] args) { // Requests per second each minute around ShopLite's 8 pm flash sale int[] traffic = {600, 700, 900, 1800, 2600, 3000, 3100, 3000, 2400, 1200, 800, 700, 650, 600, 600, 600}; int servers = 2; int highMinutes = 0; int lowMinutes = 0;
System.out.println("min rps servers cpu% action"); for (int minute = 0; minute < traffic.length; minute++) { int running = servers; int cpu = Math.min(100, traffic[minute] * 100 / (servers * RPS_PER_SERVER)); String action = ""; highMinutes = cpu > 70 ? highMinutes + 1 : 0; lowMinutes = cpu < 30 ? lowMinutes + 1 : 0; if (highMinutes >= 2 && servers < MAX) { // busy for 2 minutes: add servers int wanted = (int) Math.ceil(traffic[minute] / (RPS_PER_SERVER * 0.6)); int newCount = Math.min(MAX, Math.max(servers + 1, wanted)); action = "scale out " + servers + " -> " + newCount; servers = newCount; highMinutes = 0; } else if (lowMinutes >= 3 && servers > MIN) { action = "scale in " + servers + " -> " + (servers - 1); servers--; lowMinutes = 0; } System.out.printf("%3d %4d %7d %4d %s%n", minute, traffic[minute], running, cpu, action); } }}min rps servers cpu% action 0 600 2 60 1 700 2 70 2 900 2 90 3 1800 2 100 scale out 2 -> 6 4 2600 6 86 5 3000 6 100 scale out 6 -> 10 6 3100 10 62 7 3000 10 60 8 2400 10 48 9 1200 10 24 10 800 10 16 11 700 10 14 scale in 10 -> 9 12 650 9 14 13 600 9 13 14 600 9 13 scale in 9 -> 8 15 600 8 15
What this code does
- CPU is traffic ÷ capacity. After two minutes above 70% the scaler jumps to the count that would run at 60%; it scales in one server at a time after three quiet minutes.
- At minutes 3 and 5 the servers are at 100% (overloaded) before new ones are added: auto-scaling reacts late, which is why planned sales are scaled out in advance.
A typical rule: aim for 60% CPU; if it stays above 70% for two minutes, add servers; if it stays below 30% for a while, remove one. A minimum keeps a spare running, and a maximum caps the bill (and the database connections).
Auto-scaling reacts after the load has arrived, and new servers need minutes to boot and warm up. For a planned event like an 8 pm flash sale, scale out ahead of time, and let auto-scaling handle the surprises. Kubernetes' Horizontal Pod Autoscaler uses the rule desired = ⌈current × current metric ÷ target⌉.
Worked numbers: servers for 4,000 RPS
Headroom is the spare capacity kept free at peak, for example running servers at 70% instead of 100%, so a spike or a slow minute does not cause errors.
A load test shows one ShopLite server handles 500 RPS, and the expected peak is 4,000 RPS. Work it out in three steps, then check it in Example 4.
servers = ceil(peak / (perServer x maxUse)) + spares = ceil(4000 / (500 x 0.7)) + 1 = ceil(11.43) + 1 = 13Example 4 · Server count with headroom and one spare
public class ServerCountDemo { static int serversNeeded(int peakRps, int rpsPerServer, double maxUtilisation, int spares) { double usablePerServer = rpsPerServer * maxUtilisation; // headroom: never plan for 100% int forTraffic = (int) Math.ceil(peakRps / usablePerServer); return forTraffic + spares; // N + 1: survive one server failing }
public static void main(String[] args) { int peak = 4_000; int perServer = 500; System.out.println("No headroom, no spare: " + (int) Math.ceil(peak / (double) perServer) + " servers (each at 100%)"); System.out.println("70% headroom: " + serversNeeded(peak, perServer, 0.7, 0) + " servers"); System.out.println("70% headroom + 1 spare: " + serversNeeded(peak, perServer, 0.7, 1) + " servers"); System.out.printf("Check: with one down, 12 servers x 500 x 0.7 = %d rps >= %d%n", (int) (12 * perServer * 0.7), peak); }}No headroom, no spare: 8 servers (each at 100%) 70% headroom: 12 servers 70% headroom + 1 spare: 13 servers Check: with one down, 12 servers x 500 x 0.7 = 4200 rps >= 4000
What this code does
- Without headroom, 8 servers handle exactly 4,000 RPS at 100%: any spike or failure means errors.
- At 70% use each server counts for 350 RPS, giving 12; one spare makes 13, and with one server down the other 12 still cover the peak.
Step 1, the raw count: 4,000 ÷ 500 = 8 servers, but each would run at 100%, with no room for a spike or a slow minute.
Step 2, headroom: keep each server at about 70% at peak, so each counts for 350 RPS, and 4,000 ÷ 350 = 11.4, rounded up to 12. Step 3, a spare (N+1): add one more, so that losing any one server still leaves 12, for 13 in total. Always round up; rounding down plans for less than the peak.
Predict the output
Make your own estimate
Work it out on paper first, then pick what the code prints.
Round 1 of 2
Peak 2,600 RPS, 500 RPS per server, 70% headroom, one spare.
Which ShopLite parts scale out easily
Horizontal scaling (scale out) is running more copies of a part on ordinary machines behind a load balancer. It works well for parts that keep no data of their own and badly for parts that must stay in step.
Not every part of ShopLite scales out the same way. Example 5 rates each part from easy to hard.
Example 5 · How easily each ShopLite part scales out
import java.util.List;
public class ShopLitePartsDemo { record Part(String name, String scaleOut, String why) { }
public static void main(String[] args) { List<Part> parts = List.of( new Part("REST API servers", "easy", "stateless: JWT auth, carts in Redis, files in object storage"), new Part("Product images", "easy", "served by a CDN, not by our servers"), new Part("Redis cache", "medium", "add replicas, or a Redis Cluster that splits keys"), new Part("MySQL reads", "medium", "add read replicas; mind replication lag"), new Part("MySQL writes", "hard", "one primary takes every write; sharding is a big project"), new Part("Nightly report job", "hard", "must run once: needs a lock or a single worker")); for (Part p : parts) { System.out.printf("%-18s %-6s %s%n", p.name(), p.scaleOut(), p.why()); } }}REST API servers easy stateless: JWT auth, carts in Redis, files in object storage Product images easy served by a CDN, not by our servers Redis cache medium add replicas, or a Redis Cluster that splits keys MySQL reads medium add read replicas; mind replication lag MySQL writes hard one primary takes every write; sharding is a big project Nightly report job hard must run once: needs a lock or a single worker
What this code does
- The API servers are easy because they are stateless; images are easiest of all because the CDN serves them.
- MySQL writes are hard because one primary takes every write, and the nightly report must not run once per server.
Stateless API servers and static files scale out easily. Shared stores are harder, because data must stay correct when it lives in several places.
Jobs that must run once need a lock or a single worker, or every copy will run them.
Next step
Check your understanding
11 quick questions