Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·53

Caching

Exercises for Volume 3, chapter 53: why caches work (locality and skew) and what they cost; cache layers; local against distributed caches; Redis; cache-aside, read-through and write-through; TTLs and eviction policies; invalidation; stampedes; hot keys; negative caching; and caches across languages. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The code uses Caffeine 3.2.4, Spring Framework 7.0.9's cache abstraction (@Cacheable with ConcurrentMapCacheManager), Redis 7 with Lua scripts and redis-benchmark, all running for real on JDK 21. Every quoted output is real, and five of them catch experienced developers:

  • P5. Two @Cacheable("dishes") methods taking the same String id shared one key. price("d1") after name("d1") threw ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer, with no database call.
  • P5. A method returning null was called 3 times and hit the database once, because null was cached. With unless = "#result == null" it hit the database 3 times.
  • P1, P5. A caller that modified the list it got back from the cache changed what every later caller saw, in both Caffeine and Spring's ConcurrentMapCache: [Idli, Dosa, Free biryani (admin preview)].
  • P2. Caffeine's refreshAfterWrite returned the old value in 6 ms while it reloaded in the background. expireAfterWrite made the first reader wait 201 ms.
  • P1. On the same Zipf workload, Caffeine's W-TinyLFU hit 59.3% against LRU's 50.6%. With 30% one-off "scan" keys mixed in, it hit 40.9% against 32.0%.

The chapter's lab already covered these, and the exercises build on them rather than repeat them:

  • skew deciding hit rate: uniform 1% against Zipf 50.6% with a cache of 1% of keys;
  • layer costs: an in-process map at 0.033 µs, Redis on localhost at 13.8 µs, a PostgreSQL primary-key lookup at 20.2 µs;
  • a stampede: 50 database loads with plain cache-aside, 1 with single-flight or a Redis lock;
  • the invalidation race leaving ₹30 cached for 300 s after a change to ₹35;
  • negative caching: 1,000 database queries against 1;
  • a full Redis: noeviction rejecting writes against allkeys-lru evicting 16,055 keys.

Coverage map.

Chapter component Exercises
locality and skew T1, P1
staleness and complexity T1, T6
cache layers T2
local against distributed T2, P3
Redis T3, P6
cache-aside T4, P5
read-through, write-through T4, P2
TTL T5, P4
eviction policies T5, P1
invalidation T6, P6
stampede T7, P2
hot keys T8, P7
negative caching T8, P5
caches across languages T9

Theory

T1. Why caches work, and what they cost

  1. Explain temporal locality, spatial locality and skew. The lab: with a cache holding 1% of keys, uniform traffic hit 1.0% and Zipf traffic 50.6%. Why does the hit rate under uniform traffic equal the fraction of keys cached? Which TiffinBox data is skewed (today's menu, popular dishes, active kitchens) and which isn't (order history, individual receipts)?
  2. The costs: staleness, inconsistency between layers and instances, memory, invalidation code, cold starts, stampedes, and harder debugging ("works after restart"). The lab measured a warm PostgreSQL primary-key lookup at 20.2 µs against Redis at 13.8 µs. When is a cache not worth it?
  3. Decide for each candidate whether to cache, where, and how stale it may be: - the menu for a kitchen; - a dish's price at checkout; - a customer's profile; - the computed delivery fee by pin code; - the order status shown on the tracking page; - an expensive report.

T2. Cache layers, local against distributed

  1. Name the layers from the user outwards: - the browser (Cache-Control, ETags; ch45); - the CDN (static assets, public menu JSON); - the reverse proxy or gateway cache; - the application's in-process cache (Caffeine); - the distributed cache (Redis); - the database's buffer cache; - the OS page cache.

What does each cost per hit, and who can invalidate it? 2. Local against distributed. The lab: an in-process map at 0.033 µs, about 400× faster than Redis. P7's redis-benchmark: one client got about 28,000 GET/s at p50 0.039 ms; with 100 clients, about 108,600 GET/s with p50 0.471 ms and p99 1.119 ms. Compare consistency across instances, memory per instance, cold starts, and network failures. When do you use both (a two-level, "near" cache)? 3. With 6 instances, each with a local menu cache, an admin changes a price. How do the other 5 learn about it (TTL only, Redis pub/sub invalidation, Spring Cloud Bus, CDC events)? What happens if an invalidation message is lost?

T3. Redis for caching

  1. Explain what makes Redis fast (in-memory, single-threaded command execution, I/O threads, pipelining), its data types for caching (strings, hashes for objects, sorted sets for leaderboards, EXPIRE), and why one slow command (KEYS *, a large HGETALL, a big Lua script) blocks everyone.
  2. Memory and eviction. The lab: with maxmemory 5mb and noeviction, writes failed with OOM command not allowed; with allkeys-lru, 16,055 keys were evicted and writes continued. Explain the policies (noeviction, allkeys-lru, allkeys-lfu, volatile-*), why caches and data you can't lose (sessions, rate limits, queues: ch51) shouldn't share an instance, and what to monitor (used_memory, evicted_keys, keyspace_hits/misses, latency).
  3. Serialisation and client settings: JSON against Java serialisation against Kryo or Protobuf (size, speed, versioning across deploys, security), key naming (tb:menu:v3:k7), connection pools or multiplexing (Lettuce), timeouts, and what the application does when Redis is down (treat it as a miss, with a breaker: ch52).

T4. Access patterns: cache-aside, read-through, write-through, write-behind

  1. Explain cache-aside (the application reads the cache, on a miss loads from the source and populates; on writes updates the source and deletes the key), and why deleting is safer than updating the cache on writes.
  2. Read-through (the cache calls a loader: Caffeine's LoadingCache, P2), write-through (writes go through the cache to the source synchronously), write-behind (the cache acknowledges and writes later), and refresh-ahead (P2: refreshAfterWrite served menu v1 in 6 ms while reloading). When is write-behind acceptable, and why is it dangerous for orders?
  3. Spring's cache abstraction: @Cacheable, @CachePut, @CacheEvict, @Caching, key generation (SimpleKey from the parameters), condition and unless, sync = true, cache managers (Caffeine, Redis). P5 found four traps: - two methods sharing a cache name and parameter types collided (ClassCastException); - null results were cached; - self-invocation skipped the cache (2 database calls for 2 calls); - returned objects were shared and mutable.

Explain each and the fix.

T5. TTLs and eviction

  1. TTLs: how to choose one (how stale may it be × how expensive is a miss × change rate), absolute against sliding (expireAfterAccess) expiry, and jitter. P4: 1,000 keys cached at once with a 60 s TTL all expired in one second; with ±10% jitter the peak was 97 per second over 12 seconds. Why does that matter for the database?
  2. Eviction policies: LRU, LFU, FIFO, random, and W-TinyLFU (Caffeine: a small LRU window plus a frequency sketch deciding admission to the main area). P1: on Zipf traffic, Caffeine hit 59.3% against LRU's 50.6%; with 30% one-off scan keys, 40.9% against 32.0%. Explain why LRU suffers from scans and one-hit wonders, and what "admission" adds.
  3. Sizing: by entry count (maximumSize) or by weight (maximumWeight with a weigher for variable-sized values), how to read hit-rate curves (the lab's experiment 1: diminishing returns), and Caffeine's recordStats() (hit rate, eviction count, load time). How big should the menu cache be?

T6. Cache invalidation

  1. The lab's race: a reader loaded ₹30, paused, an admin updated to ₹35 and deleted the key, and the reader then wrote ₹30, which stayed for 300 s. Walk through the interleaving, and explain the defences: - short TTLs as the backstop; - versioned writes (P6: a Lua script refused to overwrite version 2 with version 1, returning 0, and the cache kept v 2, price 3500); - leases (Facebook's memcache); - delayed double delete; - CDC-driven invalidation.
  2. Who invalidates? Writers in the same service (after commit: ch46's @TransactionalEventListener), other services' events (DishChanged, ch51), or nobody (TTL only). Why must invalidation happen after commit, not before?
  3. Tag-based and bulk invalidation (evict "all menus that contain dish d1"), versioned namespaces (bump tb:menu:v3 → v4 to invalidate everything at once), and invalidating CDN and browser caches (versioned URLs, purge APIs, stale-while-revalidate).

T7. Cache stampedes

  1. The lab: 200 requests for a missing menu key with 50 threads produced 50 database loads with plain cache-aside, and 1 with single-flight or a Redis lock. P3: 200 concurrent cache.get("menu", loader) calls on a cold Caffeine cache made 1 load. Explain why stampedes happen (expiry of a hot key, a cold start, Redis restart, mass invalidation) and the defences: - single-flight per instance (Caffeine's get(key, loader), Spring's sync = true); - distributed locks (SET NX PX) with waiters reading again; - refresh-ahead (P2); - probabilistic early expiration (XFetch); - TTL jitter (P4); - serving stale while revalidating.
  2. With 6 instances, single-flight per instance still means up to 6 loads per key. When is that acceptable, and when do you add a distributed lock? What happens if the lock holder dies (lock TTLs), and how long should waiters wait?
  3. Cold starts after a deploy or a Redis failover: warming strategies (preload hot keys at startup, gradual traffic shift, request coalescing at the edge) and protecting the database (bulkheads and shedding on the loader: ch52).

T8. Hot keys and negative caching

  1. Hot keys: one key (the most popular kitchen's menu during lunch, a viral dish) receives a huge share of traffic. In Redis Cluster, one key lives on one shard, so that shard saturates while the others idle. Explain the fixes: - a local near cache with a short TTL (absorbs reads in-process); - key replication (menu:k7#0..#7 with random reads); - client-side caching (Redis 6's tracking and invalidation); - read replicas.

How do you find hot keys (redis-cli --hotkeys with LFU, client-side sampling)? 2. Negative caching. The lab: 1,000 lookups of a missing dish made 1,000 database queries without negative caching, and 1 with a 30-second "not found" marker. P5: Spring caches null by default. When is negative caching right (deleted items, typos, enumeration attacks), how short should its TTL be, and when do you use a Bloom filter instead? 3. Caching errors and partial results: should a failed call to maps be cached (briefly, to avoid hammering a failing dependency; ch52's breaker does this better)? What about caching empty search results?

T9. Caches across languages and platforms

  1. Compare: - Java (Caffeine, Ehcache, JCache JSR-107, Spring's abstraction, Hazelcast, Infinispan); - .NET (IMemoryCache, IDistributedCache, the new HybridCache with stampede protection); - Python (functools.lru_cache, cachetools, Django's cache framework, aiocache); - Node (lru-cache, keyv); - Go (groupcache with singleflight, ristretto with TinyLFU, golang.org/x/sync/singleflight); - Rust (moka, a Caffeine port).

Which give single-flight and TinyLFU-style admission by default? 2. HTTP caching (ch45) as the cache you get for free: Cache-Control (private, public, max-age, s-maxage, no-store, stale-while-revalidate), ETag and conditional requests, Vary. Which TiffinBox responses should be cacheable by CDNs, and which must be private or no-store (anything with personal data: ch50)? 3. Database-side caches and materialisation: PostgreSQL's buffer cache (shared_buffers), materialised views (refreshed on a schedule or concurrently), denormalised read tables fed by events (ch51's read models). When is a materialised view better than an application cache?

Programming exercises

P1. Hit rates: LRU against W-TinyLFU, and shared mutable values

Generate 1 million Zipf requests over 100,000 keys. With caches of 1,000 entries, compare a LinkedHashMap LRU and Caffeine maximumSize(1000), on plain Zipf and with 30% one-off scan keys mixed in. Then show the shared-mutable-value bug (a caller modifying a cached list) and fix it with immutable values.

P2. Read-through, refresh-ahead and single-flight with Caffeine

With a 200 ms loader: 1. compare expireAfterWrite(300 ms) with refreshAfterWrite(300 ms) plus expireAfterWrite(10 s) for 5 reads after the entry has aged 350 ms (latencies, values, loads); 2. fire 200 concurrent cache.get("menu", loader) calls on a cold cache, and count loads; 3. build the menu cache with an AsyncLoadingCache, recordStats() and Micrometer metrics.

P3. Local, Redis and two-level caches

Measure lookup costs for an in-process map, Caffeine, Redis (one client and 100 clients with redis-benchmark) and PostgreSQL by primary key. Then build a two-level menu cache (Caffeine, 10 s, in front of Redis, 60 s) with pub/sub invalidation across instances. Test what happens when an invalidation message is lost (an instance disconnected during publish).

P4. TTL jitter and synchronised expiry

  1. Cache 1,000 keys at once with a 60 s TTL, with and without ±10% jitter, and count expiries per second.
  2. Then, in Redis, set 10,000 keys with and without jitter, run a load that re-reads them, and plot database reloads per second around expiry time.
  3. Finally, implement Caffeine's Expiry with jitter.

P5. Spring's cache abstraction and its traps

With @EnableCaching and a ConcurrentMapCacheManager, show: 1. two methods sharing a cache name colliding (ClassCastException); 2. null cached by default, and unless; 3. self-invocation skipping the cache; 4. mutable returned values shared between callers.

Then configure Caffeine and Redis cache managers with per-cache TTLs, explicit keys, sync = true, JSON serialisation with a versioned prefix, and after-commit eviction. Write tests for each.

P6. The invalidation race, fixed with versions

Reproduce the lab's race (a slow reader writing a stale value after an update and delete). Then fix it with a version stored alongside the value and a Lua script that writes only if the stored version is older. Test the interleaving deterministically (latches), and add delayed double delete as a comparison.

P7. Hot keys and a near cache

Simulate a lunchtime hot key: 95% of 100,000 requests read menu:k7. Measure Redis commands per second and client p99 with and without a 5-second Caffeine near cache with refresh-ahead, across 6 simulated instances. Then find the hot key with redis-cli --hotkeys (with an LFU policy) and with client-side sampling.

P8. Negative caching and Bloom filters

Measure 1,000 lookups of a non-existent dish id: - without negative caching; - with a 30 s "not found" marker; - with a Bloom filter of all dish ids (Guava, or a hand-written one) checked before the cache.

Then simulate an enumeration attack (100,000 random ids), and compare database queries and memory for the marker approach against the Bloom filter.

P9. HTTP caching for the public menu

Configure the public menu endpoint with Cache-Control: public, max-age=30, stale-while-revalidate=60, a deep ETag (ch48's P4), and Vary: Accept-Encoding. Run a local caching proxy (nginx with proxy_cache, or Varnish, if available) and measure origin requests for 1,000 client requests over a minute. Make sure every personalised endpoint sends private or no-store, with a test that fails otherwise.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–53)

C1. Menu and catalogue caching, end to end

Design and build TiffinBox's menu caching across layers: - HTTP caching and the CDN for the public menu (P9); - a two-level cache (Caffeine with refresh-ahead and single-flight, Redis with jitter; P2–P4); - after-commit invalidation via events (ch51) with versioned writes (P6) and pub/sub for local copies; - negative caching and a Bloom filter (P8); - hot-key protection (P7); - immutable cached types (P1); - price exactness at checkout (never from cache); - metrics and alerts (hit rates, evictions, load time, Redis memory); - a load test showing database load and p99 with and without caching, and during a Redis outage.

Combines: ch45's HTTP caching, ch47's metrics, ch48's ETags, ch49's versions, ch51's events, ch52's breakers and bulkheads, and this chapter.

C2. Caching for the kitchen dashboard and reports

The kitchen dashboard shows today's orders, prep times and sales. Reports show per-day totals. Design caching and precomputation: - what's live (SSE, ch48; not cached); - what's cached briefly (aggregates for today, 10 s, single-flight); - what's precomputed (past days as materialised views or a report table filled by a job, ch51); - per-kitchen cache keys and access control (a kitchen must never see another's cached data: ch50); - invalidation when late orders arrive.

Combines: ch48's SSE, ch49's queries and materialised views, ch50's authorisation, ch51's jobs, and this chapter.

C3. A caching review of an existing service

Review a service from earlier chapters for caching: - the hit rates and memory of each cache; - correctness (keys, nulls, mutability, self-invocation: P5); - stampede protection; - TTL jitter; - invalidation after commit and races (P6); - Redis policies and instance sharing (sessions or queues sharing with caches); - HTTP caching headers; - personal data in shared caches.

Deliver findings with evidence and fixes.

Combines: ch46–48's Spring and web layers, ch49's persistence, ch50's security, and this chapter.

What the chapter leaves out

Distributed data grids and replicated caches

Hazelcast, Infinispan and Apache Ignite replicate or partition cached data across application instances, with near caches, queries and compute. They give low latency without a separate Redis, at the cost of more complex operations and memory in every application instance. Coherence and consistency settings decide what "a write" means.

Memoisation and computed caches

Caching a pure function's results (memoize) is the simplest and safest cache: no invalidation is needed when inputs determine outputs. Use it for parsing, template compilation, regexes (Pattern.compile once), and expensive pure computations. Keep it bounded (Caffeine), or it becomes a memory leak.

Cache security

Shared caches can leak data (a wrong Cache-Control, cache keys missing the tenant or user), or be poisoned (a cache key that ignores a header the response depends on, so an attacker's variant is served to everyone: web cache poisoning). Include every input that changes the response in the key (Vary), never cache responses that set cookies publicly, and keep tenant ids in keys.

Redis persistence and high availability

RDB snapshots and AOF logs make Redis durable. Replication with Sentinel or Redis Cluster provides failover, with possible loss of the last writes. For pure caches, persistence mostly speeds warm restarts. For durable data (sessions, queues), configure AOF and replication, and test failover (ch52's game day).

Measuring cache value

A cache is worth what it saves: (hit rate × cost of a miss) − (cost of a hit + staleness incidents + complexity). Track the hit rate per cache, the load it removes from the source, and incidents caused by staleness. Remove caches that don't pay for themselves.

Senior exercises

S1. TiffinBox's caching standard

Write the standard: - what may be cached, and what never (prices at checkout, balances, authorisation decisions without the full context); - the layer choice per data type; - Caffeine as the local default, with immutable values; - Redis instances by purpose with eviction policies; - key naming with versions; - TTLs with jitter and staleness budgets; - single-flight and refresh-ahead for hot keys; - after-commit invalidation with versions; - negative caching rules; - HTTP caching defaults (no-store for APIs); - metrics, alerts and reviews.

Tie each to an output.

S2. Review a caching pull request

A PR adds: - @Cacheable("orders") on getOrder(id) used by both customers and support; - @Cacheable("dishes") on getDish(id) and getDishPrice(id); - @CacheEvict inside a @Transactional update method (evicting before commit); - redisTemplate.opsForValue().set(key, value) without a TTL; - Cache-Control: public, max-age=300 on /api/orders/{id}; - a HashMap field used as a cache in a singleton bean.

Write the review.

S3. Diagnose a caching incident

Symptoms: every 5 minutes, database CPU spikes to 100% for about 20 seconds and checkout p99 jumps to 3 s. The spikes started after a release that "warmed the cache at startup". Redis INFO shows normal memory. Caffeine stats show the hit rate dropping from 98% to 20% during each spike. Find the cause, the evidence needed, and the fixes.

S4. Teach "caches are correctness code" with five outputs

Prepare a 20-minute session using: - the lab's skew (uniform 1% against Zipf 50.6%); - the lab's invalidation race (₹30 for 300 s) and P6's versioned fix; - P5's key collision (ClassCastException); - P1's mutated cached list; - the lab's stampede (50 loads) and P3's single-flight (1).

S5. Plan a caching programme

As platform lead, plan two quarters: - an inventory of every cache across 14 services (type, layer, TTL, key scheme, hit rate); - removing caches that don't pay (S1's measure); - the starter's cache library (Caffeine defaults, immutability checks, jitter, single-flight, refresh-ahead, metrics); - Redis split by purpose with the right policies; - the invalidation library (after commit, versions, pub/sub); - HTTP caching defaults and CDN rollout for public data; - hot-key detection; - the incident fixes (S3); - training (S4).

Give milestones, risks and metrics.