Sticky sessions and CDNs for static content
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shopper adds a phone to the cart on app-1, and the next click lands on app-2 with an empty cart. Where a request goes, and what answers it, decides if ShopLite survives 100 times the users.
Your turn: the cart that vanished
On sale day ShopLite has three servers behind a balancer. A shopper's cart is empty after a click, and every product page also loads 2 MB of photos, scripts and styles from your servers. Sketch your fixes first, then compare them with the sections below.
- Where could the cart live so that any server can answer the next request?
- You could pin each user to one server instead. What goes wrong when that server crashes or one user is very busy?
- Which files are the same for every user, and could something closer to the user serve them?
Sticky sessions and their problems
Sticky session (session affinity) is a load balancer setting that sends every request from one user to the same server, usually with a cookie. It exists for apps that keep the login or cart in a server's memory.
ShopLite's balancer sets a cookie such as SERVERID=app-2 on the first response and obeys it from then on. Example 1 shows what that costs.
Example 1 · Sticky sessions: one heavy user and one crash
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class StickySessionDemo { static final List<String> SERVERS = List.of("app-1", "app-2", "app-3"); static final Map<String, String> stickyCookie = new LinkedHashMap<>(); // user -> SERVERID cookie value static final Map<String, Map<String, String>> sessionsOnServer = new HashMap<>(); static int next = 0;
static String route(String user) { return stickyCookie.computeIfAbsent(user, u -> SERVERS.get(next++ % SERVERS.size())); }
public static void main(String[] args) { for (String s : SERVERS) { sessionsOnServer.put(s, new HashMap<>()); } // Requests per user in one hour: one reseller is far busier than everyone else Map<String, Integer> requests = new LinkedHashMap<>(); requests.put("Asha", 40); requests.put("Ravi", 35); requests.put("bulk-reseller", 900); requests.put("Meena", 30); requests.put("Kabir", 45); requests.put("Priya", 38);
Map<String, Integer> load = new LinkedHashMap<>(); requests.forEach((user, count) -> { String server = route(user); sessionsOnServer.get(server).put(user, "cart + login"); load.merge(server, count, Integer::sum); }); System.out.println("Sticky routing: " + stickyCookie); System.out.println("Requests per server: " + load);
System.out.println("app-3 crashes: lost sessions " + sessionsOnServer.get("app-3").keySet() + " (logged out, carts emptied)"); }}Sticky routing: {Asha=app-1, Ravi=app-2, bulk-reseller=app-3, Meena=app-1, Kabir=app-2, Priya=app-3}
Requests per server: {app-1=70, app-2=80, app-3=938}
app-3 crashes: lost sessions [Priya, bulk-reseller] (logged out, carts emptied)What this code does
- The cookie pins each user to the server picked on their first visit. The bulk reseller's 900 requests all land on app-3, which gets 938 requests while the others get 70 and 80.
- When app-3 crashes, the sessions it held in memory disappear: Priya and the reseller are logged out and lose their carts.
Stickiness works, but it has three costs. Load becomes uneven: one heavy user, or a whole office behind one IP, pins a lot of traffic to one server, and the balancer cannot move it.
A crash or a deploy loses every session held by that server, so those users are logged out and lose their carts. And scaling in is slow, because a server cannot leave until its users' sessions expire.
Predict the output
Predict the lost carts
Read the code, then pick what it prints.
Each user is pinned to a server. app-2 crashes.
Stateless servers are easier
Session store is a shared place, such as Redis, where every server reads and writes the login and cart data of users. Because no server holds a session itself, any server can answer any request.
ShopLite keeps sessions in a shared store, so no server needs stickiness. Example 2 compares memory-only sessions with a shared store.
Example 2 · Stateless servers with a shared session store
import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class SharedSessionDemo { public static void main(String[] args) { Map<String, String> sessionStore = new HashMap<>(); // stands in for Redis sessionStore.put("Asha", "logged in, cart: 1 x Redmi Note 13 5G"); sessionStore.put("bulk-reseller", "logged in, cart: 50 x Cotton Kurta");
List<String> servers = new ArrayList<>(List.of("app-1", "app-2", "app-3")); Map<String, Integer> load = new LinkedHashMap<>(); int next = 0; for (int r = 0; r < 900; r++) { // the reseller's 900 requests String server = servers.get(next++ % servers.size()); // any server will do load.merge(server, 1, Integer::sum); } System.out.println("Reseller's requests per server: " + load);
servers.remove("app-3"); String server = servers.get(next++ % servers.size()); System.out.println("After app-3 crashes, Asha's next request goes to " + server + ": " + sessionStore.get("Asha")); }}Reseller's requests per server: {app-1=300, app-2=300, app-3=300}
After app-3 crashes, Asha's next request goes to app-1: logged in, cart: 1 x Redmi Note 13 5GWhat this code does
- With sessions in a shared store, the reseller's 900 requests can be spread 300, 300, 300.
- After app-3 crashes, Asha's next request goes to another server, which reads her session from the store: she stays logged in with her cart.
A signed JWT that the client sends with each request, as ShopLite's Spring Security setup does, is the other way to keep sessions out of server memory. Spring Session can also keep them in Redis.
The balancer can then use round robin or least connections freely, a crash loses no sessions, and servers can be added or removed at any time. The cost is a fast network read of the session (with Redis), or the care JWTs need (they cannot be revoked easily, so keep them short-lived).
CDN basics: edge, origin and cache hits
CDN (content delivery network) is a set of edge servers in many cities that cache files and serve them near the user, so most requests for images, scripts and styles never reach ShopLite's own servers.
A CDN edge answers from its copy and asks the origin only on a miss. Example 3 follows 3,000 views of one product image.
Example 3 · Three CDN edges serving one product image
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;
class EdgeServer { final String city; final Map<String, Long> cachedUntil = new HashMap<>(); // path -> expiry time (seconds) int hits = 0; int misses = 0;
EdgeServer(String city) { this.city = city; }
void get(String path, long now, long maxAge, int[] originRequests) { Long until = cachedUntil.get(path); if (until != null && now < until) { hits++; // served from the city's edge return; } misses++; originRequests[0]++; // fetch once from ShopLite's origin cachedUntil.put(path, now + maxAge); }}
public class CdnEdgeDemo { public static void main(String[] args) { Map<String, EdgeServer> edges = new LinkedHashMap<>(); for (String city : new String[] {"Mumbai", "Delhi", "Chennai"}) { edges.put(city, new EdgeServer(city)); } int[] originRequests = {0}; String path = "/images/redmi-note-13.v2.jpg"; long maxAge = 86_400;
String[] cities = {"Mumbai", "Delhi", "Chennai"}; for (int i = 0; i < 3_000; i++) { edges.get(cities[i % 3]).get(path, i, maxAge, originRequests); } for (EdgeServer e : edges.values()) { System.out.printf("%-8s hits=%d misses=%d%n", e.city, e.hits, e.misses); } System.out.println("Requests that reached the origin: " + originRequests[0] + " of 3000"); }}Mumbai hits=999 misses=1 Delhi hits=999 misses=1 Chennai hits=999 misses=1 Requests that reached the origin: 3 of 3000
What this code does
- Each city's edge fetches the image from the origin once, then serves it from its own cache for the rest of the
max-age. - Only 3 of 3,000 requests reach ShopLite's origin; the other 2,997 are edge hits near the users.
Users are routed to a nearby edge. If it has a fresh copy of the file, it answers at once: an edge cache hit, often in 10-20 ms. If not, it fetches the file from the origin (ShopLite's own servers or storage), keeps a copy for the time the headers allow, and answers.
So a popular image is fetched from the origin once per edge per TTL, not once per user. The origin sees a tiny share of the traffic, and users far from the data centre still get fast pages.
Order of execution
One cache miss
Put the steps of one CDN cache miss in order.
What to put on a CDN: headers and versioned files
File versioning is naming each static file after a hash of its content, such as app.3f2a9c1b.js. A changed file gets a new name, so the old name can be cached for a year without anyone seeing stale content.
Static files go on the CDN and personal answers never do. Example 4 builds versioned file names from a content hash.
Example 4 · Versioned file names from a content hash
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.HexFormat;
public class FileVersioningDemo { // Build tools name each file after a hash of its content: change the content, get a new name static String versionedName(String baseName, String ext, String content) throws NoSuchAlgorithmException { byte[] digest = MessageDigest.getInstance("SHA-256").digest(content.getBytes(StandardCharsets.UTF_8)); String shortHash = HexFormat.of().formatHex(digest).substring(0, 8); return baseName + "." + shortHash + "." + ext; }
public static void main(String[] args) throws NoSuchAlgorithmException { String v1 = "function addToCart(id) { cart.push(id); }"; String v2 = "function addToCart(id, qty) { cart.push({id, qty}); }";
String name1 = versionedName("app", "js", v1); String name2 = versionedName("app", "js", v2); System.out.println("release 1: " + name1 + " Cache-Control: public, max-age=31536000, immutable"); System.out.println("release 2: " + name2 + " (new name, so no old copy can be served)"); System.out.println("same content again: " + versionedName("app", "js", v1)); System.out.println("index.html Cache-Control: no-cache (always checked, it points to the new names)"); }}release 1: app.cd6859f3.js Cache-Control: public, max-age=31536000, immutable release 2: app.92c58c58.js (new name, so no old copy can be served) same content again: app.cd6859f3.js index.html Cache-Control: no-cache (always checked, it points to the new names)
What this code does
- The name is the first 8 hex characters of the SHA-256 of the file's content: release 2 changed the code, so it gets a new name, and the same content always gives the same name.
- Because a name never points to different content, versioned files can be cached for a year; only
index.html, which lists the names, must be checked every time.
Put static files on the CDN: product images, JavaScript, CSS, fonts, icons. They are the same for every user and make up most of the bytes of a page. Personal API responses (cart, orders) should not be cached there, and short-TTL public API responses only with care.
Versioned files can be cached for a year with Cache-Control: public, max-age=31536000, immutable. The HTML page that lists the file names gets no-cache so browsers always check it and pick up new names. Without versioning, a fixed file needs a CDN purge (invalidation) and users may still hold the old copy.
Fix the error
Fix the cache header
Each response has the wrong header. Pick the line that fixes it.
Round 1 of 2
The response to GET /api/v1/me/orders is cached by the CDN.
Error
A shopper sees another customer's orders after the CDN cached the answer.
ShopLite's request path
Edge / origin are the two ends of a CDN: the edge is the nearby CDN server that users talk to, and the origin is ShopLite's own server or storage that the edge asks on a miss.
Put together, a product page load splits into two paths: static files through the CDN, API calls through the balancer.
[Browser] --static files--> [CDN edge (Mumbai)] --miss--> [Origin] /index.html, /assets/app.3f2a9c1b.js, /images/*.jpg[Browser] --/api/v1/...--> [Load balancer] --> [App x3] (stateless) |--> [(Redis)] (sessions, cache) |--> [(MySQL primary + replicas)]Example 5 · Where each part of a product page comes from
import java.util.List;
public class RequestPathDemo { record Resource(String path, boolean cdnHit) { }
static String trace(Resource r) { if (r.path().startsWith("/api/")) { return "browser -> load balancer -> app server -> Redis / MySQL (~60 ms)"; } if (r.path().endsWith(".html")) { return "browser -> CDN edge -> origin asks \"changed?\" -> 304 (~50 ms)"; } if (r.cdnHit()) { return "browser -> CDN edge (Mumbai) (~15 ms)"; } return "browser -> CDN edge -> origin (load balancer -> app) (~90 ms, then cached)"; }
public static void main(String[] args) { List<Resource> productPage = List.of( new Resource("/index.html", true), new Resource("/assets/app.3f2a9c1b.js", true), new Resource("/assets/app.77c0e512.css", true), new Resource("/images/redmi-note-13.v2.jpg", true), new Resource("/images/new-arrival.v1.jpg", false), new Resource("/api/v1/products/1", false), new Resource("/api/v1/me/orders", false)); for (Resource r : productPage) { System.out.printf("%-30s %s%n", r.path(), trace(r)); } }}/index.html browser -> CDN edge -> origin asks "changed?" -> 304 (~50 ms) /assets/app.3f2a9c1b.js browser -> CDN edge (Mumbai) (~15 ms) /assets/app.77c0e512.css browser -> CDN edge (Mumbai) (~15 ms) /images/redmi-note-13.v2.jpg browser -> CDN edge (Mumbai) (~15 ms) /images/new-arrival.v1.jpg browser -> CDN edge -> origin (load balancer -> app) (~90 ms, then cached) /api/v1/products/1 browser -> load balancer -> app server -> Redis / MySQL (~60 ms) /api/v1/me/orders browser -> load balancer -> app server -> Redis / MySQL (~60 ms)
What this code does
- Versioned assets and images are edge hits; a new image is fetched from the origin once and then cached;
index.htmlis revalidated and usually gets a 304. - API calls skip the CDN and go through the load balancer to the stateless app servers, which read Redis and MySQL. The millisecond figures are rough examples.
Static files go to the CDN edge and only reach the origin on a miss. API calls go through the load balancer to any stateless app server, which reads Redis and MySQL.
Next step
Check your understanding
11 quick questions