Skip to lesson

Where caches live: browser, CDN, application, database

On sale day thousands of shoppers open the same ShopLite product page, and MySQL answers the same question again and again. Where could a ready answer be kept so that most requests never reach the database?

Your turn: ShopLite is slow on sale day

ShopLite is a Stage 5 project that got popular. Before reading on, think for two minutes and write down your answers. Nothing is graded; you will compare with one good design afterwards.

  • What is slow here, and why is asking MySQL the same question thousands of times wasteful?
  • Where could a copy of a product live so that most requests never reach MySQL? List every place between the shopper and the database.
  • Which numbers matter: how many reads per write, and how old may a copy be before it does harm?

Why caching works

A cache is a small, fast store that keeps a copy of data you read often, so the next read does not have to go back to the slow original.

The program below sends the same 10 product reads straight to a slow database, then through a Map placed in front of it.

Example 1 · The cache idea: same reads, far fewer database trips

CacheIdeaDemo.javaJava
import java.util.HashMap;import java.util.Map;
class SlowDatabase {    private final Map<Integer, String> rows = new HashMap<>();    int reads = 0;
    SlowDatabase() {        rows.put(1, "Redmi Note 13 5G");        rows.put(6, "boAt Airdopes 141");    }
    String find(int id) {        reads++;                        // pretend each read costs 50 ms        return rows.get(id);    }}
public class CacheIdeaDemo {    static final int DB_MS = 50;        // one database read (simplified)    static final int MEMORY_MS = 1;     // one look in memory (rounded up)
    public static void main(String[] args) {        int[] requests = {1, 1, 6, 1, 1, 6, 1, 1, 1, 6};
        SlowDatabase db = new SlowDatabase();        int timeNoCache = 0;        for (int id : requests) {            db.find(id);            timeNoCache += DB_MS;        }        System.out.println("Without cache: " + db.reads + " DB reads, " + timeNoCache + " ms");
        SlowDatabase db2 = new SlowDatabase();        Map<Integer, String> cache = new HashMap<>();        int timeWithCache = 0;        int hits = 0;        for (int id : requests) {            timeWithCache += MEMORY_MS;            String name = cache.get(id);            if (name != null) {                hits++;            } else {                name = db2.find(id);                cache.put(id, name);                timeWithCache += DB_MS;            }        }        System.out.println("With cache:    " + db2.reads + " DB reads, " + timeWithCache + " ms");        System.out.println("Cache hits:    " + hits + " of " + requests.length);    }}
Output
Without cache: 10 DB reads, 500 ms
With cache:    2 DB reads, 110 ms
Cache hits:    8 of 10

What this code does

  • Without a cache, all 10 requests go to the database: 10 × 50 = 500 ms of database time.
  • With a Map in front, only the first read of product 1 and of product 6 are misses. The other 8 are hits, so total time drops to 110 ms and the database is read twice.

Caching works for two reasons. Reads far outnumber writes: a product is viewed thousands of times for every price change. And memory is much faster than disk, which is much faster than a trip over the network.

A cache hit means the data was found in the cache. A cache miss means it was not, so the slow source had to be asked. You pay the slow read once and serve every other read from memory.

The millisecond numbers in this module's programs are simplified round values, chosen to show the idea. Real numbers depend on the hardware and the network.

One good design: cache layers, closest first

A cache layer is one place along the request path that can keep a copy and answer on its own. The first layer with a fresh copy answers.

A request for GET /api/v1/products/1 passes these layers in order. The picture shows the same path with the time to reach each layer.

Text
Asha's phone            Mumbai edge            ShopLite data centre[browser cache] --> [CDN edge cache] --> [app server memory] --> [shared cache: Redis] --> [MySQL]   0 ms                 ~15 ms                 ~55 ms                     ~56 ms                 ~86 ms (only Asha)        (everyone nearby)       (one server only)          (all servers)       (buffer pool inside)
  • Browser cache: on the user's own device. Fastest, but it helps only that one user.
  • CDN (content delivery network): servers in many cities that keep copies of public files and responses near users.
  • App memory and shared cache: a Map inside one app server, or a separate cache server such as Redis that all app servers share.
  • Database buffer pool: MySQL's InnoDB keeps recently used table pages in memory, so even a database read often skips the disk.
A product request passes five layers, closest first: browser cache 0 ms for one user, CDN edge 15 ms for everyone nearby, app server memory 55 ms for one server, shared Redis 56 ms for all servers, and MySQL 86 ms. The first layer with a fresh copy answers.

Example 2 · A request falling through the cache layers

CacheLayersDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
class Layer {    final String name;    final int costMs;                       // extra time to reach this layer (simplified)    final Map<String, String> store = new HashMap<>();
    Layer(String name, int costMs) {        this.name = name;        this.costMs = costMs;    }}
public class CacheLayersDemo {    static final Map<String, String> database =            Map.of("/api/v1/products/1", "{\"id\":1,\"name\":\"Redmi Note 13 5G\"}");    static final int DATABASE_MS = 30;    static final Layer cdn = new Layer("CDN edge", 15);    static final Layer appMemory = new Layer("app memory", 40);    static final Layer sharedCache = new Layer("shared cache", 1);    static final Map<String, Layer> browsers = new HashMap<>();
    static void get(String user, String url) {        Layer browser = browsers.computeIfAbsent(user, u -> new Layer("browser", 0));        List<Layer> path = List.of(browser, cdn, appMemory, sharedCache);        List<Layer> missed = new ArrayList<>();        int ms = 0;        for (Layer layer : path) {            ms += layer.costMs;            String body = layer.store.get(url);            if (body != null) {                missed.forEach(m -> m.store.put(url, body));   // copy into the closer layers                System.out.printf("%-6s -> %-12s hit  %3d ms%n", user, layer.name, ms);                return;            }            missed.add(layer);        }        ms += DATABASE_MS;        String body = database.get(url);        missed.forEach(m -> m.store.put(url, body));        System.out.printf("%-6s -> %-12s      %3d ms%n", user, "database", ms);    }
    public static void main(String[] args) {        String url = "/api/v1/products/1";        get("Asha", url);     // nothing cached yet        get("Asha", url);        get("Ravi", url);
        cdn.store.clear();        get("Meena", url);
        cdn.store.clear();        appMemory.store.clear();        get("Kabir", url);    }}
Output
Asha   -> database           86 ms
Asha   -> browser      hit    0 ms
Ravi   -> CDN edge     hit   15 ms
Meena  -> app memory   hit   55 ms
Kabir  -> shared cache hit   56 ms

What this code does

  • Each Layer is checked in order. On a hit, the copy is also stored in every closer layer that missed, so the next request stops earlier.
  • Asha's second request never leaves her phone (0 ms). Ravi has an empty browser cache but shares the CDN copy. When the CDN and app memory lose their copies, the shared cache still saves the database trip.

Each layer is a trade-off. A closer layer is faster but helps fewer users and is harder to clear when the data changes. A farther layer serves more users and is easier to control, but every request pays more time to reach it.

Compare this with your own list: the usual answer is a copy in the browser, near the user, inside the app server and in one shared cache.

Predict the output

Which layer answers?

Read what each layer holds, then pick the layer that answers.

Round 1 of 3

Asha opens product 1, closes the page and opens it again within a minute.

browser cache: /products/1 (fresh)
CDN edge: /products/1 (fresh)
app memory: empty
Redis: /products/1

HTTP caching headers: Cache-Control, ETag and 304

Cache-Control is a response header that tells browsers and CDNs whether they may keep a copy of the response and for how long.

The server sends the caching rule together with the response. The second request below asks whether the saved copy is still right.

Terminal
$ curl -i https://shoplite.example.com/api/v1/products/1HTTP/1.1 200 OKCache-Control: public, max-age=60ETag: "94b65bee"{"id":1,"price":17999.00}$ curl -i -H 'If-None-Match: "94b65bee"' https://shoplite.example.com/api/v1/products/1HTTP/1.1 304 Not ModifiedCache-Control: public, max-age=60ETag: "94b65bee"

Example 3 · ETag and 304 Not Modified

ETagDemo.javaJava
class ProductEndpoint {    String body = "{\"id\":1,\"price\":17999.00}";
    String etag() {        // A short fingerprint of the body: same body, same tag        return "\"" + Integer.toHexString(body.hashCode()) + "\"";    }
    String handle(String ifNoneMatch) {        if (etag().equals(ifNoneMatch)) {            return "304 Not Modified, 0 bytes of body";        }        return "200 OK, ETag " + etag() + ", " + body.length() + " bytes of body";    }}
public class ETagDemo {    public static void main(String[] args) {        ProductEndpoint server = new ProductEndpoint();        String savedTag = null;                 // what the browser remembers
        System.out.println("1st visit:   " + server.handle(savedTag));        savedTag = server.etag();
        System.out.println("2nd visit:   " + server.handle(savedTag));
        server.body = "{\"id\":1,\"price\":16999.00}";   // price drop for the sale        System.out.println("After sale:  " + server.handle(savedTag));        savedTag = server.etag();
        System.out.println("Next visit:  " + server.handle(savedTag));    }}
Output
1st visit:   200 OK, ETag "94b65bee", 25 bytes of body
2nd visit:   304 Not Modified, 0 bytes of body
After sale:  200 OK, ETag "2cd52f0f", 25 bytes of body
Next visit:  304 Not Modified, 0 bytes of body

What this code does

  • The ETag here is the hex form of String.hashCode() of the body: the same body always gives the same tag. Real servers use a stronger hash; Spring's ShallowEtagHeaderFilter, for example, uses MD5.
  • When the browser's saved tag matches, the server sends 304 and no body. After the sale price changes, the tag changes too, so the browser gets the new body with 200.

Cache-Control: public, max-age=60 means "anyone may cache this for 60 seconds". During those 60 seconds the browser does not even send a request. After that the copy is stale (possibly out of date), but it may still be correct.

An ETag is a short fingerprint of the response body. The browser sends it back in an If-None-Match header. If the body has not changed, the server replies 304 Not Modified with no body and the browser reuses its copy. If it changed, the server sends 200 with the new body and a new ETag.

Order of execution

A 304 round trip

Put the steps of a conditional request in order.

A 304 still costs one round trip. It saves the body, not the request. max-age saves the whole request.

Hit ratio and average latency

The hit ratio is the number of cache hits divided by the total number of requests: 8 hits in 10 requests is 80%.

The program below prints the average time and the database reads for six hit ratios, using a 1 ms hit and a 51 ms miss.

Example 4 · Average latency and database load for each hit ratio

HitRatioDemo.javaJava
public class HitRatioDemo {    static final double HIT_MS = 1;          // answer found in the cache    static final double MISS_MS = 1 + 50;    // look in the cache, then ask the database
    static double averageMs(double hitRatio) {        return hitRatio * HIT_MS + (1 - hitRatio) * MISS_MS;    }
    public static void main(String[] args) {        int requests = 10_000;        int[] hitPercents = {0, 50, 80, 90, 95, 99};
        System.out.println("Hit ratio | Average | DB reads per 10,000 requests");        for (int p : hitPercents) {            double h = p / 100.0;            int dbReads = requests * (100 - p) / 100;            System.out.printf("%8d%% | %4.1f ms | %d%n", p, averageMs(h), dbReads);        }    }}
Output
Hit ratio | Average | DB reads per 10,000 requests
       0% | 51.0 ms | 10000
      50% | 26.0 ms | 5000
      80% | 11.0 ms | 2000
      90% |  6.0 ms | 1000
      95% |  3.5 ms | 500
      99% |  1.5 ms | 100

What this code does

  • averageMs is the formula from this section: hit ratio × hit time + miss ratio × miss time.
  • Average latency falls steadily, but database reads fall even faster at the top end: 1,000 at 90% and only 100 at 99%.

Latency is how long one request takes. Average latency = hit ratio × hit time + (1 − hit ratio) × miss time. A miss costs the cache check plus the database read, so with a 1 ms hit and a 51 ms miss, an 80% hit ratio gives 0.8 × 1 + 0.2 × 51 = 11 ms.

The last few percent matter most for the database. Going from 90% to 99% hits cuts database reads from 1,000 to 100 per 10,000 requests: ten times less load.

Predict the output

Estimate before you calculate

Hit time is 1 ms and miss time is 51 ms. Pick the answer.

Round 1 of 3

What is the average latency at a 50% hit ratio?

double hit = 0.5;
double average = hit * 1 + (1 - hit) * 51;
System.out.println(average);

What not to cache

Two bugs follow from caching the wrong thing: a key shared by every user, and a stock count that is already out of date. The program below shows both.

Example 5 · Two caching bugs: a shared key and a stale stock count

WhatNotToCacheDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class WhatNotToCacheDemo {    static final Map<String, String> sharedCache = new HashMap<>();    static final Map<String, String> ordersOf = Map.of(            "Asha", "[order 11: Redmi Note 13 5G, Bengaluru address]",            "Ravi", "[order 14: Airdopes 141, Pune address]");
    // Bug: the key is only the URL, so every user shares one entry    static String myOrdersBuggy(String user) {        return sharedCache.computeIfAbsent("/api/v1/me/orders", k -> ordersOf.get(user));    }
    // Fix: the user is part of the key (or do not put this in a shared cache at all)    static String myOrdersFixed(String user) {        return sharedCache.computeIfAbsent("orders:" + user, k -> ordersOf.get(user));    }
    public static void main(String[] args) {        System.out.println("Buggy key:");        System.out.println("  Asha sees " + myOrdersBuggy("Asha"));        System.out.println("  Ravi sees " + myOrdersBuggy("Ravi"));
        System.out.println("Fixed key:");        System.out.println("  Asha sees " + myOrdersFixed("Asha"));        System.out.println("  Ravi sees " + myOrdersFixed("Ravi"));
        int stock = 2;        String cachedStock = "Only " + stock + " left";      // cached for 60 seconds        stock -= 2;        System.out.println("Stock page at 30 s: \"" + cachedStock + "\", real stock " + stock);    }}
Output
Buggy key:
  Asha sees [order 11: Redmi Note 13 5G, Bengaluru address]
  Ravi sees [order 11: Redmi Note 13 5G, Bengaluru address]
Fixed key:
  Asha sees [order 11: Redmi Note 13 5G, Bengaluru address]
  Ravi sees [order 14: Airdopes 141, Pune address]
Stock page at 30 s: "Only 2 left", real stock 0

What this code does

  • With the buggy key /api/v1/me/orders, Asha's request fills the entry and Ravi gets her orders and address: a real data leak.
  • Putting the user in the key (orders:Ravi) fixes the leak. The stock line shows the other trap: a 60-second copy still says "Only 2 left" after both units sold.

Per-user and secret data (orders, addresses, login tokens) must never sit in a shared cache under a key that other users can hit. Send Cache-Control: no-store for secrets and private for per-user data, and put the user id in any server-side cache key. Fast-changing numbers such as stock during a sale go stale within seconds: show them from the database, or cache them for a second or two, and always re-check stock when the order is placed.

  • Cache well: product details, category lists, images, prices that change a few times a day.
  • Cache carefully: per-user data, only with the user in the key and private headers.
  • Do not cache: passwords, tokens, OTPs, payment details, live stock at checkout.

Find the bug

Find the caching mistake

Each snippet caches something it should not. Tap the wrong line.

The "My orders" page uses a shared cache.

Round 1 of 3

Next step

Check your understanding

12 quick questions