Load balancing and scaling practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
After the four lessons you should be able to trace a balancer by hand, spot the bug in one, size a fleet from traffic and decide what never reaches your servers. This page checks those four skills.
Tracing round robin and least connections
Write one token per request, such as A2 for "server A, now 2 open". Example 1 traces the same 10 requests through both rules.
Example 1 · The same 10 requests through both algorithms
import java.util.ArrayList;import java.util.List;
public class TraceTwoAlgorithmsDemo { // Request i arrives at time i (seconds) and runs DURATION[i] seconds static final int[] DURATION = {5, 1, 1, 5, 1, 1, 1, 1, 1, 1}; static final String[] NAMES = {"A", "B", "C"};
static void trace(boolean leastConnections) { List<int[]> running = new ArrayList<>(); // {server, endTime} int[] open = new int[3]; int rr = 0; StringBuilder line = new StringBuilder(); for (int t = 0; t < DURATION.length; t++) { final int now = t; running.removeIf(r -> { if (r[1] <= now) { open[r[0]]--; return true; } return false; }); int s; if (leastConnections) { s = 0; for (int i = 1; i < 3; i++) { if (open[i] < open[s]) { s = i; } } } else { s = rr++ % 3; } open[s]++; running.add(new int[] {s, t + DURATION[t]}); line.append(NAMES[s]).append(open[s]).append(' '); // server and its open count after this request } System.out.printf("%-17s %s%n", leastConnections ? "least connections" : "round robin", line.toString().trim()); }
public static void main(String[] args) { System.out.println("request durations: 5 1 1 5 1 1 1 1 1 1 (one request per second)"); trace(false); trace(true); }}request durations: 5 1 1 5 1 1 1 1 1 1 (one request per second) round robin A1 B1 C1 A2 B1 C1 A2 B1 C1 A1 least connections A1 B1 B1 B1 C1 A1 A1 A1 A1 A1
What this code does
- Requests 1 and 4 run 5 seconds. Round robin still sends request 4 and request 7 to A, so A has 2 open requests twice.
- Least connections sends requests 2 to 4 to B, which keeps finishing its short work, and never lets any server go above 1 open request.
To trace round robin, write the server list and count: request i goes to server i mod n, whatever is happening on the servers. To trace least connections, keep a running count of open requests per server: add one when a request is sent, subtract one when it finishes, and send each new request to the smallest count (ties to the first server).
The difference shows up when some requests are long: round robin keeps sending to a server stuck with a long request, least connections steers around it.
Fixing a balancer that is not thread-safe
servers.get(next % n); next++; has two bugs. Example 2 shows the second one at the moment the counter wraps.
Example 2 · The overflow bug in next % n
import java.util.List;
public class OverflowBugDemo { static final List<String> SERVERS = List.of("app-1", "app-2", "app-3");
public static void main(String[] args) { int next = Integer.MAX_VALUE - 1; // what the counter looks like after months of traffic for (int i = 0; i < 3; i++) { int counter = next++; String withMod; try { withMod = SERVERS.get(counter % SERVERS.size()); } catch (IndexOutOfBoundsException e) { withMod = "CRASH (" + e.getMessage() + ")"; } String withFloorMod = SERVERS.get(Math.floorMod(counter, SERVERS.size())); System.out.printf("counter=%11d %% -> %-48s floorMod -> %s%n", counter, withMod, withFloorMod); } }}counter= 2147483646 % -> app-1 floorMod -> app-1 counter= 2147483647 % -> app-2 floorMod -> app-2 counter=-2147483648 % -> CRASH (Index -2 out of bounds for length 3) floorMod -> app-2
What this code does
- After
Integer.MAX_VALUEthe counter wraps to −2,147,483,648, and%gives −2:List.get(-2)throws. Math.floorModalways returns a value from 0 to n − 1, so the balancer keeps working after the wrap.
First, next++ on a plain int is not atomic: two threads can read the same value, so picks repeat, counts drift and on some JVMs updates are lost. Second, after about two billion requests the int wraps to a negative number, % returns a negative index and the balancer throws.
The fix is two small changes: an AtomicInteger with getAndIncrement(), and Math.floorMod(counter, n) for the index. Also make the server list immutable (List.copyOf) so another thread cannot change it mid-pick.
Servers for traffic and failure tolerance
Start with ⌈peak ÷ (per-server RPS × target use)⌉, then add what you must survive. Example 3 plans for 6,000 RPS.
Example 3 · Sizing for 6,000 RPS: spares, zones and the database
public class FleetSizingDemo { static int perZone(int peakRps, int rpsPerServer, double maxUse, int zones) { // After losing one zone, the others carry the whole peak return (int) Math.ceil(peakRps / (double) (zones - 1) / (rpsPerServer * maxUse)); }
public static void main(String[] args) { int peak = 6_000; int perServer = 500; double maxUse = 0.7;
int simple = (int) Math.ceil(peak / (perServer * maxUse)) + 1; System.out.println("One zone, N+1: " + simple + " servers"); for (int zones : new int[] {2, 3}) { int n = perZone(peak, perServer, maxUse, zones); System.out.println(zones + " zones, survive a zone loss: " + n + " per zone, " + n * zones + " total"); } int dbLimit = 300 - 20; // max_connections minus reserve int pool = 10; System.out.println("Most servers the database allows with pools of " + pool + ": " + dbLimit / pool); }}One zone, N+1: 19 servers 2 zones, survive a zone loss: 18 per zone, 36 total 3 zones, survive a zone loss: 9 per zone, 27 total Most servers the database allows with pools of 10: 28
What this code does
- N+1 in one zone needs 19 servers. Surviving a zone loss needs 36 servers in 2 zones but only 27 in 3 zones.
- With pools of 10 and 280 usable connections the database allows 28 servers, so the 2-zone plan does not fit unless pools shrink.
One spare (N+1) covers a single server failure. Surviving the loss of a whole zone means the remaining zones must carry the full peak, so with 2 zones each must be sized for the whole peak; with 3 zones, each for half.
Finally check the limits around the fleet: the auto-scaling maximum, and the database's connection budget (servers × pool size). A plan that needs 36 servers is not real if the database allows 28.
CDN or app server?
Ask two questions about each resource: is it the same for every user, and does its content change under the same name? Example 4 sorts eight resources.
Example 4 · Eight resources: CDN or app server
public class CdnOrAppDemo { static String where(String resource) { boolean personal = resource.contains("/me/") || resource.contains("/auth/"); boolean staticFile = resource.matches(".*\\.(js|css|jpg|png|webp|svg|woff2)$"); if (personal) { return "app server, no-store"; } if (staticFile) { return "CDN, long max-age (versioned name)"; } if (resource.endsWith(".html")) { return "CDN, no-cache (revalidate)"; } return "app server (CDN only with a short max-age)"; }
public static void main(String[] args) { String[] resources = {"/assets/app.3f2a9c1b.js", "/assets/app.77c0e512.css", "/images/kurta-blue.v3.webp", "/fonts/inter.v1.woff2", "/index.html", "/api/v1/products?categoryId=2", "/api/v1/me/orders", "/api/v1/auth/login"}; for (String r : resources) { System.out.printf("%-32s -> %s%n", r, where(r)); } }}/assets/app.3f2a9c1b.js -> CDN, long max-age (versioned name) /assets/app.77c0e512.css -> CDN, long max-age (versioned name) /images/kurta-blue.v3.webp -> CDN, long max-age (versioned name) /fonts/inter.v1.woff2 -> CDN, long max-age (versioned name) /index.html -> CDN, no-cache (revalidate) /api/v1/products?categoryId=2 -> app server (CDN only with a short max-age) /api/v1/me/orders -> app server, no-store /api/v1/auth/login -> app server, no-store
What this code does
- Versioned scripts, styles, images and fonts go to the CDN with a long cache time; the HTML goes there with
no-cache. - Personal and login responses stay on the app servers with
no-store; the product list goes to the app, with a CDN only for short caching.
Same for everyone and versioned by name: CDN with a long cache time. HTML that lists versioned files: CDN with no-cache.
Anything personal or secret (/me/..., login): app server, no-store. Public API data: app server, or a CDN with a short max-age when the freshness rules allow.
Finish up
Mark complete & continue
Next: Project: ShopLite load balancer simulation