Caching 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.
Caching bugs and interview slips cluster in four places: LRU traces, update paths that forget the cache, the wrong layer or TTL, and hit-ratio maths. Each has a short method you can repeat.
Tracing an LRU cache of size 3
Keep one line of keys, least recently used on the left and most recently used on the right. The program below prints one line per access.
Example 1 · LRU of size 3, one line per access
import java.util.LinkedHashMap;import java.util.Map;
public class LruTraceDemo { public static void main(String[] args) { int capacity = 3; String[] evicted = {null}; Map<String, String> lru = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, String> eldest) { if (size() > capacity) { evicted[0] = eldest.getKey(); return true; } return false; } };
String[] accesses = {"P1", "P2", "P3", "P1", "P4", "P2", "P1", "P5", "P3"}; int hits = 0; for (String key : accesses) { evicted[0] = null; String result; if (lru.get(key) != null) { hits++; result = "hit "; } else { lru.put(key, "page"); result = "miss"; } System.out.printf("%-3s %s LRU->MRU %-15s %s%n", key, result, lru.keySet(), evicted[0] == null ? "" : "evicted " + evicted[0]); } System.out.println("hits=" + hits + " of " + accesses.length); }}P1 miss LRU->MRU [P1] P2 miss LRU->MRU [P1, P2] P3 miss LRU->MRU [P1, P2, P3] P1 hit LRU->MRU [P2, P3, P1] P4 miss LRU->MRU [P3, P1, P4] evicted P2 P2 miss LRU->MRU [P1, P4, P2] evicted P3 P1 hit LRU->MRU [P4, P2, P1] P5 miss LRU->MRU [P2, P1, P5] evicted P4 P3 miss LRU->MRU [P1, P5, P3] evicted P2 hits=2 of 9
What this code does
- The list is printed least recently used first. The hit on
P1moves it to the right end, soP4evictsP2, notP1. - Only two of nine accesses hit: with five pages cycling through three slots, a small cache cannot keep the working set.
A hit moves the key to the right end. A miss adds the key on the right; if that makes four keys, remove the leftmost one. Interviewers ask this to check that you move keys on hits too, not only on inserts: forgetting that turns LRU into FIFO. Review: LRU and TTL eviction (opens in a new tab)
Mistake: an update path that never invalidates
The program below renames a product and still serves the old name, then fixes the update path.
Example 2 · Bug and fix: renaming a product leaves the old name
import java.util.HashMap;import java.util.Map;
class ProductCatalogue { private final Map<Integer, String> db = new HashMap<>(Map.of(13, "Running Shoes Rs 2499")); private final Map<Integer, String> cache = new HashMap<>(); private final boolean invalidate;
ProductCatalogue(boolean invalidate) { this.invalidate = invalidate; }
String get(int id) { return cache.computeIfAbsent(id, db::get); }
void rename(int id, String newText) { db.put(id, newText); if (invalidate) { cache.remove(id); // the missing line in the buggy version } }}
public class MissingInvalidationDemo { static void run(String label, ProductCatalogue c) { c.get(13); c.rename(13, "Running Shoes (new model) Rs 2299"); System.out.println(label + c.get(13)); }
public static void main(String[] args) { run("Buggy: ", new ProductCatalogue(false)); run("Fixed: ", new ProductCatalogue(true)); }}Buggy: Running Shoes Rs 2499 Fixed: Running Shoes (new model) Rs 2299
What this code does
- The buggy version updates the database but keeps serving the cached "Rs 2499" text.
- The fixed version adds one line,
cache.remove(id), after the database write, so the nextgetloads the new model and price.
The most common cache bug is an update method that writes the database and never touches the cache. Tests that only read still pass; the bug shows up after an edit, as an old name, an old price or a "Buy now" button on a product that was switched off.
The fix is the cache-aside rule: write the database, then delete every key the change affects. When you review code, search for every method that writes the table and check that each one evicts. Review: Cache invalidation (opens in a new tab)
Find the bug
Find the update that forgets the cache
Each update leaves an old copy in the cache. Tap the wrong line.
A product is renamed, but the page keeps showing the old name.
Round 1 of 2Choosing the cache layer and TTL
The program below gives a cache layer and a TTL to six kinds of ShopLite data.
Example 3 · A cache plan for six kinds of ShopLite data
import java.util.List;
record CachePlan(String data, String layer, String ttl, String why) { }
public class CachePlanDemo { public static void main(String[] args) { List<CachePlan> plan = List.of( new CachePlan("Product images", "CDN + browser", "1 year", "file name changes when the image changes"), new CachePlan("Category list", "Redis", "30 min", "changes a few times a month"), new CachePlan("Product details", "Redis", "10 min", "evicted on every edit"), new CachePlan("Home page deals", "Redis", "60 s", "hot key: refresh early"), new CachePlan("Order status", "none", "-", "customer needs the truth"), new CachePlan("Stock at checkout", "none", "-", "read in the order transaction")); System.out.printf("%-18s %-14s %-7s %s%n", "Data", "Layer", "TTL", "Why"); for (CachePlan p : plan) { System.out.printf("%-18s %-14s %-7s %s%n", p.data(), p.layer(), p.ttl(), p.why()); } }}Data Layer TTL Why Product images CDN + browser 1 year file name changes when the image changes Category list Redis 30 min changes a few times a month Product details Redis 10 min evicted on every edit Home page deals Redis 60 s hot key: refresh early Order status none - customer needs the truth Stock at checkout none - read in the order transaction
What this code does
- Images and the category list are the same for everyone and rarely change, so they get long TTLs in the closest possible layer.
- Order status and stock at checkout are not cached at all: an old value there means a wrong answer to a customer or an oversold product.
For each kind of data ask three questions: Is it the same for every user? How often does it change? What does an old value cost? Public, rarely changing files go to the CDN and the browser. Shared data that changes now and then goes to Redis with a TTL and eviction on update. Per-user, fast-changing or money-related data is read from the database. Review: Where caches live (opens in a new tab)
Predict the output
Pick the layer
Choose the best caching choice for each kind of data.
Round 1 of 3
The login endpoint returns an access token.
redmi-13.v2.jpg). The CDN lesson in the Load Balancing module covers this.Average latency from a hit ratio
The program below works out the average latency for a one-level and a two-level cache.
Example 4 · Average latency for one and two cache levels
public class LatencyMathDemo { public static void main(String[] args) { // One level: Redis in front of MySQL double h = 0.90, hitMs = 1, missMs = 1 + 20; double oneLevel = h * hitMs + (1 - h) * missMs; System.out.printf("One level: 0.90 x 1 + 0.10 x 21 = %.2f ms%n", oneLevel);
// Two levels: local map (0.05 ms), then Redis (+1 ms), then MySQL (+20 ms) double local = 0.60, redis = 0.30, db = 0.10; // shares of all requests double twoLevel = local * 0.05 + redis * (0.05 + 1) + db * (0.05 + 1 + 20); System.out.printf("Two levels: %.2f ms%n", twoLevel); System.out.printf("DB reads per 1,000 requests: %d (same in both)%n", Math.round(db * 1000)); }}One level: 0.90 x 1 + 0.10 x 21 = 3.00 ms Two levels: 2.45 ms DB reads per 1,000 requests: 100 (same in both)
What this code does
- One level: 90% of requests take 1 ms and 10% take 21 ms, so the average is 3 ms.
- Adding a local map in front of Redis lowers the average to 2.45 ms, but the database still gets 100 of every 1,000 requests. Only a higher overall hit ratio reduces database load.
For one level: average = h × hit time + (1 − h) × miss time, where the miss time includes the cache check. With several levels, multiply each level's share of all requests by the total time to reach that level, and add the results.
Keep every time in the same unit (milliseconds) and check that the shares add up to 1. The database share usually dominates the average, which is why raising the hit ratio matters more than making the cache faster.
Finish up
Mark complete & continue
Next: Project: ShopLite product cache simulation