Caching Without Serving Stale or Broken Data

Caching Without Serving Stale or Broken Data in Spring Boot: A busy pharmacy keeps a "will-call" shelf behind the counter: prescriptions already counted,…

The Analogy: The Pharmacy Will-Call Shelf

A busy pharmacy keeps a "will-call" shelf behind the counter: prescriptions already counted, bagged, and labelled, waiting for the patient to walk in and collect them. Filling a prescription is the slow, expensive part -- pulling the stock, counting tablets, checking interactions, printing the label. Once that work is done, the pharmacist does not want to repeat it every time the phone rings to ask "is it ready?" The bagged order sits on the shelf, and handing it over is a two-second lookup instead of a ten-minute fill. That shelf is a cache: costly work performed once, its result held ready so the next request is answered cheaply.

The shelf only works because every bag carries a label that identifies exactly one order. A careful pharmacy files each bag under the patient's full name and date of birth, often the last digits of a phone number as well -- enough that no two bags can be confused. When a customer gives their name, the technician reads the labels, pulls the one bag that matches, and the handoff is both instant and correct. The label is the cache key, and the discipline is simple: it must capture everything that makes this order different from any other.

The shelf is not infinite. When it fills, the staff clear space by pulling the bags that have sat longest uncollected and returning their contents to stock; if that patient turns up later, the order has to be filled again from scratch. Every bag also carries a discard-by date, and once it passes the bag is pulled even if the shelf is half empty, because a fill from three weeks ago may no longer match the current prescription. Finite space forces eviction, and the discard-by date is a deliberate ceiling on how stale a waiting bag is allowed to be.

The disaster is a shortcut in the labelling. Suppose a rushed pharmacy files bags by the drug name alone -- one bin marked "amoxicillin" -- instead of by the patient. Two different people on the same medication now collide in that single bin, and the next person who asks for their amoxicillin is handed whichever bag happens to be there: possibly a stranger's, with a different dose and a different name printed on it. The shelf is faster than ever and quietly, dangerously wrong, and nobody notices until a patient reads the label at the car. A key built from too little information does not slow anything down; it hands out the wrong answer with total confidence, and that is the failure this lesson is really about.

Syntax or Core Structure

Turn caching on with @EnableCaching, then annotate the expensive method:

@Configuration
@EnableCaching
public class CacheConfig { }
@Service
public class CatalogService {

    @Cacheable(cacheNames = "productSummary", key = "#id")
    public ProductSummary summary(Long id) {
        // slow work: query, map, compute
        return load(id);
    }
}

The contract is one sentence: on a call, if the region already holds an entry for the computed key, return it and do not enter the method; otherwise run the method, store the result under that key, and return it. A hit skips the body; a miss runs it. Trace six calls against an empty productSummary region keyed on #id:

Output:

call    key   result   method ran
---------------------------------
1       1     miss     yes
2       2     miss     yes
3       1     hit      no
4       3     miss     yes
5       2     hit      no
6       1     hit      no
---------------------------------
total calls        : 6
distinct keys      : 3
misses (ran)       : 3
hits (skipped)     : 3
method executions  : 3

Six calls, but the method body ran only three times -- once per distinct key. The three repeat calls were served from the region without executing anything. That ratio, three saved executions out of six calls, is the entire value proposition, and it is why the method must be genuinely expensive and genuinely repeated for a cache to earn its place.

Technical Depth: Keys, Collisions and Eviction

The key decides correctness, not just hit rate

The default key is built from every method argument. That is fine until an argument that matters is left out. The most damaging version keys on too little and lets two logically different calls share one entry:

// Wrong -- the patient is not in the key
@Cacheable(cacheNames = "prescription", key = "#drug")
public Record load(String patient, String drug) { ... }

Trace two patients requesting the same drug against the buggy key, then against a key that includes the patient:

Output:

config   call                 cache key      served record   correct?
---------------------------------------------------------------------
buggy    load(alice,insulin)  insulin        alice           yes
buggy    load(bob,insulin)    insulin        alice           no
fixed    load(alice,insulin)  alice:insulin  alice           yes
fixed    load(bob,insulin)    bob:insulin    bob             yes
---------------------------------------------------------------------
buggy wrong-patient served: 1
fixed wrong-patient served: 0
safe key                  : patient+drug

The buggy configuration serves Alice's record to Bob because both requests collapse to the key insulin. This is not a slow endpoint; it is a cross-patient data leak produced entirely by the cache, and no amount of load testing reveals it because the fast path is the wrong path. The rule is mechanical: if two calls can legitimately return different values, they must not share a key. Anything user-, tenant-, or permission-scoped belongs in the key.

A bounded region evicts, and re-reading an evicted key costs a reload

A cache must have a maximum size; an unbounded one is a memory leak with good intentions. Once full, inserting a new key forces the provider to evict an existing one, and the usual policy is least-recently-used (LRU): the entry untouched longest is discarded first. Trace an LRU region of maximum size three against the access sequence A, B, C, A, D, B:

Output:

access  result  evicted  resident (lru..mru)
----------------------------------------------
A       miss    -        A
B       miss    -        A,B
C       miss    -        A,B,C
A       hit     -        B,C,A
D       miss    B        C,A,D
B       miss    C        A,D,B
----------------------------------------------
maximum size    : 3
accesses        : 6
hits            : 1
misses          : 5
evictions       : 2
final resident  : A,D,B

Two details matter. First, the second access to A is a hit and promotes A to most-recently-used, which is why B -- not A -- is evicted when D arrives. Second, the final access to B is a miss: B was evicted at the previous step, so a key that was cached moments earlier now costs a full reload. A cache sized smaller than the working set thrashes, and the hit rate collapses toward zero while you still pay for every lookup.

The annotation you choose is the write contract

Three annotations cover the lifecycle. Every write path that changes the underlying data must evict or overwrite, or the region serves data that contradicts the database until the entry expires.

AnnotationEffect
@CacheableReturn the cached value if present, otherwise run the method and store the result
@CachePutAlways run the method, then overwrite the entry
@CacheEvictRemove one entry
@CacheEvict(allEntries = true)Clear the whole region

TTL is the safety net under imperfect eviction. Spring's caching abstraction has no TTL of its own -- the provider supplies it (expireAfterWrite in Caffeine, a key TTL in Redis) -- and it bounds how long any missed-eviction bug can keep lying to users. Choose it from the business tolerance for staleness: minutes for a price, seconds or nothing for a permission check.

Real World Example: One Catalogue Cache, Three Instances

The service below caches product summaries and evicts on update. It runs behind a load balancer on three identical instances, each with its own in-process Caffeine region.

@Service
public class CatalogService {

    @Cacheable(cacheNames = "productSummary", key = "#id")
    public ProductSummary summary(Long id) {
        Product p = repository.findById(id).orElseThrow();
        return ProductSummary.from(p);   // immutable projection, safe to share
    }

    @CacheEvict(cacheNames = "productSummary", key = "#id")
    public void rename(Long id, String name) {
        Product p = repository.findById(id).orElseThrow();
        p.setName(name);                 // committed by the transaction
    }
}

The code gets two things right that are easy to get wrong: it caches an immutable ProductSummary record rather than the mutable JPA Product (so no caller can mutate a shared entry and no lazy association detaches), and every write path is annotated to evict. On a single instance it is correct. The problem appears only when it is scaled out: a rename lands on whichever instance the balancer picks, and @CacheEvict clears the entry on that instance only. Trace a read of the renamed product on each instance immediately after the write, first with these local regions and then with one shared Redis region:

Output:

cache type   instance  post-write value   stale?
--------------------------------------------------
local        inst-1    v2 (fresh)         no
local        inst-2    v1 (old)           yes
local        inst-3    v1 (old)           yes
shared       inst-1    v2 (fresh)         no
shared       inst-2    v2 (fresh)         no
shared       inst-3    v2 (fresh)         no
--------------------------------------------------
instances                : 3
write handled by         : inst-1
local stale instances    : 2
shared stale instances   : 0
safe for read-after-write: shared

With local caches, two of the three instances are stale the instant after a successful write, and a client refreshing the page sees the new name or the old one depending purely on which instance answers -- a coin-flip that looks like a caching glitch and is nearly impossible to reproduce on a developer's single-instance laptop. The shared region holds one copy for every instance, so the single eviction reaches all readers and zero instances are stale.

The design flaw in the code shown is not a typo; it is the choice of a local cache for data that must be consistent immediately after a write, deployed behind a balancer with no sticky routing. The fix is a shared cache (Redis) so eviction has global reach, or a TTL short enough that the staleness window is acceptable, or an explicit decision that this data tolerates seconds of lag. A second, subtler limit: even the shared version assumes every write goes through rename, so a bulk SQL update or an admin tool that bypasses the service leaves every cache stale with no eviction at all.

Common Mistakes

  1. Keying on too little. Omitting a scoping argument (tenant, patient, user) lets two different calls collide on one entry, and the cache silently serves one caller's data to another -- a correctness and security bug, not a performance one.
  2. Caching a mutable managed entity. Returning a JPA entity from a @Cacheable method shares one object across threads, detaches its lazy associations, and holds data no one committed. Cache an immutable projection instead.
  3. No maximum size. An unbounded region under a key space you do not control (search terms, ids from user input) grows until the JVM runs out of heap and dies.
  4. No TTL. Without an expiry, a single missed eviction lies to users indefinitely; a short TTL bounds the blast radius of every invalidation bug.
  5. Forgetting a write path. Annotating the main update but not the bulk import, the admin tool, or the batch job leaves the cache contradicting the database until entries expire.
  6. Assuming local eviction is global. With a per-instance cache behind a load balancer, @CacheEvict clears one instance and the others keep serving stale values for a full TTL.
  7. Caching cheap methods. If the method is already fast, the cache adds a network hop, memory pressure, and an invalidation bug for no measurable gain.
  8. Self-invocation. Calling a @Cacheable method from another method of the same bean bypasses the Spring proxy, so no caching happens and the miss is silent.
  9. Caching security decisions with a long TTL. Cached permissions or roles keep granting access after a revocation, turning a convenience cache into an authorisation hole.

Best Practices

  • Build the key from every input the result depends on, and write it explicitly rather than trusting the argument-derived default.
  • Cache immutable projections or DTOs, never managed entities that carry ORM lifecycle and shared mutable state.
  • Always set both a maximum size and a TTL; treat an unbounded, never-expiring cache as a defect in review.
  • Evict on every write path, and keep a short TTL as a safety net for the path you inevitably miss.
  • Reach for a shared cache when read-after-write correctness must hold across instances; a local cache is for data that tolerates per-instance lag.
  • Keep security-relevant data -- permissions, roles, feature gates -- out of long-lived caches, or scope its TTL to seconds.
  • Measure the hit rate in production and remove any cache that does not clear a useful threshold; low-hit caches are pure risk.
  • Defend hot keys against stampede with a loading cache, refresh-ahead, or TTL jitter so entries do not all expire together.

Practice Exercises

  1. Given an LRU region of maximum size 2 and the access sequence A, B, A, C, B, produce the hit, miss, and eviction trace with the final resident set, and state how many method executions occurred.
  2. A @Cacheable method takes (tenantId, reportId) but is keyed on #reportId. Describe the exact failure a second tenant experiences and give the corrected key expression.
  3. A service caches a JPA entity in a local Caffeine region across four instances with a ten-minute TTL and evicts on update. List every distinct defect and the consequence of each.
  4. Choose between Caffeine and Redis for (a) per-request memoization of a pure computation and (b) a session-permissions lookup that must reflect revocation within one second, justifying each choice in terms of eviction reach and consistency.