Cache-aside, write-through and expiry
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's product page reads MySQL on every view. Adding a cache raises new questions: who fills it, who updates it when a price changes, and how long may a copy live?
Your turn: who fills the cache, who updates it?
You have a cache and a MySQL database. Before reading on, write down how your own design would work. Then compare it with one good design below. Nothing is graded.
- A shopper asks for product 7. In what order do you look in the cache and the database, and what do you do when the cache has no copy?
- The price of product 7 changes. Do you write the new price into the cache, delete the cached copy, or leave it alone?
- What if a copy is sometimes wrong? How old may it be for the product page, and how old for the order status?
One good design: cache-aside
Cache-aside is a pattern where the application checks the cache first, loads the database on a miss and fills the cache itself; an update deletes the cached copy.
The app asks the cache first and goes to the database only when there is no copy. The method below shows the whole read path in four steps.
String getProduct(int id) { String p = cache.get(id); // 1. look in the cache if (p != null) return p; // hit: done p = db.findById(id); // 2. miss: ask the database if (p != null) cache.put(id, p); // 3. keep a copy return p;}Example 1 · Cache-aside with a slow Map database
import java.util.HashMap;import java.util.Map;
class ProductDb { private final Map<Integer, String> rows = new HashMap<>(); int calls = 0;
ProductDb() { rows.put(1, "Redmi Note 13 5G Rs 17999"); rows.put(4, "Lenovo IdeaPad Slim 3 Rs 42990"); rows.put(9, "Clean Code Rs 499"); }
String findById(int id) { calls++; try { Thread.sleep(50); // artificial delay: a slow query } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return rows.get(id); }}
class ProductService { private final ProductDb db; private final Map<Integer, String> cache = new HashMap<>();
ProductService(ProductDb db) { this.db = db; }
String getProduct(int id) { String product = cache.get(id); // 1. look in the cache if (product != null) { System.out.println("HIT " + id + " " + product); return product; } product = db.findById(id); // 2. miss: load from the database if (product != null) { cache.put(id, product); } System.out.println("MISS " + id + " " + product); return product; }}
public class CacheAsideDemo { public static void main(String[] args) { ProductDb db = new ProductDb(); ProductService service = new ProductService(db); int[] requests = {1, 4, 1, 1, 9, 4, 1}; for (int id : requests) { service.getProduct(id); } System.out.println("Requests: " + requests.length + ", database calls: " + db.calls); }}MISS 1 Redmi Note 13 5G Rs 17999 MISS 4 Lenovo IdeaPad Slim 3 Rs 42990 HIT 1 Redmi Note 13 5G Rs 17999 HIT 1 Redmi Note 13 5G Rs 17999 MISS 9 Clean Code Rs 499 HIT 4 Lenovo IdeaPad Slim 3 Rs 42990 HIT 1 Redmi Note 13 5G Rs 17999 Requests: 7, database calls: 3
What this code does
ProductDb.findByIdsleeps 50 ms to act like a slow query; you can feel the three misses when you run it.- Seven requests touch the database only three times: once for each different id. Every later read of the same id is a
HIT.
The cache sits "aside": only the application talks to both stores. Only data that someone asks for gets cached, so memory is not wasted on cold rows. The price is that every first read is a miss and pays the full database time.
On an update, cache-aside writes the database and then deletes the cached copy, so the next read loads the new value.
Order of execution
The miss path
Put the steps of one cache-aside read, when the cache is empty, in order.
Write-through and write-behind
Write-through is a pattern where every write goes to the database and the cache in the same call, so the cache has the latest value right after a write.
Cache-aside deletes the copy on an update. Two other patterns write more eagerly. The programs below compare all three after one price change, then show a crash.
Example 2 · The three write patterns side by side
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class WritePatternsDemo { static Map<Integer, Integer> db = new HashMap<>(); // product id -> price static Map<Integer, Integer> cache = new HashMap<>(); static List<String> pendingWrites = new ArrayList<>(); // for write-behind
static void reset() { db = new HashMap<>(Map.of(1, 17999)); cache = new HashMap<>(Map.of(1, 17999)); pendingWrites.clear(); }
static void show(String step) { System.out.printf(" %-26s db=%s cache=%s%n", step, db.get(1), cache.get(1)); }
// Cache-aside: write the database, then remove the cached copy static void updateCacheAside(int id, int price) { db.put(id, price); cache.remove(id); }
static void updateWriteThrough(int id, int price) { db.put(id, price); cache.put(id, price); }
static void updateWriteBehind(int id, int price) { cache.put(id, price); pendingWrites.add(id + "=" + price); }
static void flush() { for (String w : pendingWrites) { String[] p = w.split("="); db.put(Integer.parseInt(p[0]), Integer.parseInt(p[1])); } pendingWrites.clear(); }
public static void main(String[] args) { System.out.println("Cache-aside:"); reset(); updateCacheAside(1, 16999); show("after update");
System.out.println("Write-through:"); reset(); updateWriteThrough(1, 16999); show("after update");
System.out.println("Write-behind:"); reset(); updateWriteBehind(1, 16999); show("after update"); flush(); show("after background flush"); }}Cache-aside: after update db=16999 cache=null Write-through: after update db=16999 cache=16999 Write-behind: after update db=17999 cache=16999 after background flush db=16999 cache=16999
What this code does
- Cache-aside leaves the cache empty (
null) after the update, so the next read is a miss that loads 16999. - Write-through has the new price in both stores at once. Write-behind has it only in the cache until the background flush copies it to the database.
Example 3 · Mistake: write-behind loses data in a crash
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class WriteBehindCrashDemo { public static void main(String[] args) { Map<Integer, Integer> db = new HashMap<>(Map.of(6, 120)); // product 6: stock 120 Map<Integer, Integer> cache = new HashMap<>(db); List<Integer> pending = new ArrayList<>(); // stock values not yet saved
for (int order = 1; order <= 3; order++) { int stock = cache.get(6) - 1; cache.put(6, stock); // fast: memory only pending.add(stock); System.out.println("Order " + order + " placed, cache stock = " + stock); }
System.out.println("Cache server crashes before the flush"); cache.clear(); pending.clear();
System.out.println("Database stock after restart = " + db.get(6) + " (3 sales lost)"); }}Order 1 placed, cache stock = 119 Order 2 placed, cache stock = 118 Order 3 placed, cache stock = 117 Cache server crashes before the flush Database stock after restart = 120 (3 sales lost)
What this code does
- Each order updates stock in the cache and queues the write in memory. The database still says 120.
- When the cache server crashes, the queue is gone too. After a restart the database shows 120 although three units were sold, which is why stock and orders never use write-behind.
With write-through, reads after a write are hits, but every write pays for two stores, and data that is written but never read still fills the cache.
Write-behind (also called write-back) writes only the cache first and saves to the database later, often in batches. Writes become very fast, but if the cache server dies before the flush, the queued writes are lost.
- Cache-aside: write the database, delete the cache entry. The usual default.
- Write-through: write the database and the cache. Fresh reads right after writes.
- Write-behind: write the cache, the database later. Only for data you can afford to lose, such as view counters.
Predict the output
What is left after the update?
The price changes from 17999 to 16999. Pick what the stores hold.
Round 1 of 3
Write-through, right after the update call.
TTL expiry: value plus expiresAt
TTL (time to live) is how long a cached copy may be used before it counts as expired and the next read is a miss.
Each value is stored with an expiresAt time. The program below reads one product at several moments, using a fake clock that we move by hand.
Example 4 · A TTL cache with a fake clock
import java.util.HashMap;import java.util.Map;
class FakeClock { long nowMs = 0;
void advanceSeconds(int s) { nowMs += s * 1000L; }}
record Entry(String value, long expiresAt) { }
class TtlCache { private final Map<String, Entry> map = new HashMap<>(); private final FakeClock clock; private final long ttlMs;
TtlCache(FakeClock clock, long ttlMs) { this.clock = clock; this.ttlMs = ttlMs; }
void put(String key, String value) { map.put(key, new Entry(value, clock.nowMs + ttlMs)); }
String get(String key) { Entry e = map.get(key); if (e == null) { return null; // never cached } if (clock.nowMs >= e.expiresAt()) { map.remove(key); // too old: treat as a miss return null; } return e.value(); }}
public class TtlCacheDemo { public static void main(String[] args) { FakeClock clock = new FakeClock(); TtlCache cache = new TtlCache(clock, 60_000); // TTL = 60 seconds
cache.put("product:1", "Redmi Note 13 5G Rs 17999"); int[] waits = {0, 30, 29, 1, 10}; for (int w : waits) { clock.advanceSeconds(w); String v = cache.get("product:1"); System.out.printf("t=%3d s %s%n", clock.nowMs / 1000, v == null ? "MISS (expired or absent)" : "HIT " + v); } }}t= 0 s HIT Redmi Note 13 5G Rs 17999 t= 30 s HIT Redmi Note 13 5G Rs 17999 t= 59 s HIT Redmi Note 13 5G Rs 17999 t= 60 s MISS (expired or absent) t= 70 s MISS (expired or absent)
What this code does
putstoresEntry(value, now + ttl).getreturns the value only whilenow < expiresAt.- At t=59 s the entry is still fresh; at t=60 s it has expired, so
getremoves it and reports a miss. The fake clock makes the run the same every time.
expiresAt is the time the value was stored plus the TTL. On every read, compare the current time with expiresAt: if it has passed, remove the entry and treat the read as a miss.
A TTL is a safety net. Even if the code forgets to delete a copy after an update, the wrong value can live at most one TTL. Tests use a fake clock (a clock you move forward by hand) so expiry can be checked without waiting.
Fix the error
Fix the expiry check
Each snippet expires entries wrongly. Pick the line that fixes it.
Round 1 of 2
Stored at 5000 ms with a TTL of 30 seconds, but entries never seem to expire in time.
Error
The entry is reported expired after 30 ms, not 30 seconds.
Choosing a pattern: catalogue vs order status
The right pattern depends on how often the data changes and how bad an old value is. The program below shows how long each kind of data can show an old value.
Example 5 · How long can a reader see an old value?
public class ChoosingTtlDemo { // How long can a reader see an old value? At most until the cached copy expires. static void staleWindow(String data, int ttlSeconds, int changedAtSecond, int[] readSeconds) { System.out.println(data + " (TTL " + ttlSeconds + " s, changes at t=" + changedAtSecond + " s)"); int cachedAt = 0; // copy made at t=0 for (int t : readSeconds) { if (t - cachedAt >= ttlSeconds) { cachedAt = t; // expired: reload from the database } boolean stale = cachedAt < changedAtSecond && t >= changedAtSecond; System.out.printf(" read at t=%3d s -> %s%n", t, stale ? "OLD value" : "current value"); } }
public static void main(String[] args) { int[] reads = {10, 40, 70, 130, 610}; staleWindow("Product description", 600, 30, reads); staleWindow("Order status", 5, 30, new int[] {10, 28, 31, 33, 34}); }}Product description (TTL 600 s, changes at t=30 s) read at t= 10 s -> current value read at t= 40 s -> OLD value read at t= 70 s -> OLD value read at t=130 s -> OLD value read at t=610 s -> current value Order status (TTL 5 s, changes at t=30 s) read at t= 10 s -> current value read at t= 28 s -> current value read at t= 31 s -> OLD value read at t= 33 s -> current value read at t= 34 s -> current value
What this code does
- With a 600-second TTL, a description changed at t=30 s is shown old until the copy expires and reloads at t=610 s. That is fine for a description.
- With a 5-second TTL, the order status is old only for the read at t=31 s; by t=33 s the copy has reloaded. A short TTL keeps the stale window small.
A product description changes rarely and an old one does little harm, so cache-aside with a long TTL (say 10 minutes) works well. An order's status changes from PLACED to SHIPPED and a customer wants the truth, so use a very short TTL (a few seconds), delete the entry on every status change, or skip the cache. The TTL sets the worst case: a reader can see an old value for at most one TTL after a change that the code did not invalidate.
- Product details, category list: cache-aside, TTL 5-15 minutes, delete on update.
- Product price: cache-aside, delete on every price change, shorter TTL.
- Order status: delete on change plus a TTL of a few seconds, or no cache.
- View counters: write-behind is fine; losing a few views is acceptable.
Predict the output
Pick the better design
Choose the pattern and TTL that fit the data.
Round 1 of 3
Which design fits the ShopLite category list?
Next step
Check your understanding
11 quick questions