Sub topic 1
Why and when to cache
Prerequisites
This chapter assumes you can read basic Java and know how a Spring Boot application is laid out. You should understand Spring beans and dependency injection, and you should be able to add a dependency with Maven or Gradle. You should also know where application.properties or application.yml lives. No caching knowledge is needed. This chapter covers the reasoning that comes before any annotation.
What a cache is
A cache is a fast store that keeps the result of earlier work so that a later request for the same result can skip that work. The slow source of truth stays where it is. The cache sits in front of it and holds a copy.
A copy can become wrong. Every decision about caching is a trade between speed and how much staleness you can accept. Spring's caching support is simple to switch on, so the hard part is knowing whether a given method should be cached at all.
The cost a cache removes
A method is a candidate for caching when calling it is expensive. Typical costs are:
- A database query that scans or joins many rows.
- A call to a remote HTTP service with network latency and rate limits.
- A heavy computation, such as rendering a report or calculating a price table.
- A call to a licensed or metered API where each request costs money.
The gain is largest when the same call is repeated with the same arguments. A cache turns repeated work into a lookup. It also protects the backend. If 1,000 requests per second ask for the same product, a cache can reduce that to a few backend reads per minute.
A simple model of the benefit
Two numbers decide whether a cache pays off: the hit ratio and the cost difference between a hit and a miss. A hit is a request answered from the cache. A miss is a request that finds nothing and must run the real method.
The average latency is:
average = hitRatio * hitCost + (1 - hitRatio) * missCostSuppose a database call takes 40 ms and a cache lookup takes 1 ms. With a hit ratio of 90 percent, the average is 0.9 × 1 + 0.1 × 40 = 4.9 ms. With a hit ratio of 20 percent, it is 0.2 × 1 + 0.8 × 40 = 32.2 ms. The cache works in both cases, but the second case gives little benefit. It also uses memory and adds a staleness risk. A low hit ratio is the usual sign that a method is a poor candidate.
Misses also cost slightly more than an uncached call, because the cache is checked first and then written to. For a method with almost no repeats, a cache makes things slightly worse.
Good candidates and poor candidates
Use these questions to judge a method.
- Is it expensive? Cheap in-memory work is not worth caching.
- Is it called often with the same arguments? Repeats are what produce hits.
- Is the result stable enough? The data should change less often than it is read.
- Is a slightly old answer acceptable? If not, caching needs strict invalidation or should be avoided.
- Is the result safe to share? A cached value is returned to every caller with the same key.
| Method | Cache it? | Reason |
|---|---|---|
| Product catalog lookup by id | Yes | Read often, changes rarely, a stale price for a few minutes is tolerable |
| Currency exchange rates from a remote API | Yes | Costly call, the data is valid for a known period |
| Current account balance | Usually no | Must be exact, and a stale value causes wrong decisions |
| Search by free text with many different terms | Rarely | Few repeated keys, so a low hit ratio |
| Method that returns the current time or a random value | No | The result is meant to differ on each call |
| Method with side effects, such as sending an email | No | Skipping the call on a hit would skip the side effect |
The last row matters. Caching assumes a method is a function: the same input gives the same output, and calling it changes nothing else. If a method writes to a database or sends a message, a cache hit silently skips that work.
What caching costs you
Caching removes latency but adds several problems.
Staleness
The cache holds a copy that can differ from the source. You limit this in two ways. You can set a time to live (TTL), after which an entry is dropped. You can also remove or refresh entries when the source changes. Later chapters cover @CachePut, @CacheEvict, and expiration. Both techniques reduce staleness without eliminating it. Between a database write and the matching eviction, a reader may still see the old value.
Memory
A cache uses memory. An unbounded cache grows until the JVM runs out of heap. Every production cache needs a size limit, an expiry, or both.
Consistency across instances
A local cache lives inside one JVM. If you run three instances of your application, each has its own copy. An update handled by instance A does not change the entries in B and C. A shared cache such as Redis avoids this, but it adds a network hop and another system to run. The provider chapters compare these options.
Added complexity
Behavior now depends on cache state. A bug may appear only when an entry is present, or only after it expires. This makes problems harder to reproduce. Tests and metrics help, and later chapters cover both.
Cold starts
After a restart, a local cache is empty. Early requests all miss and hit the backend together. A busy system can feel this as a load spike. Redis keeps its data across application restarts, so it avoids that for a shared cache.
Where Spring fits
Spring Boot does not provide a cache by itself. It provides an abstraction, a common layer of annotations and interfaces. You mark a method, and Spring wraps it so that the cache is checked first. The storage underneath can be Caffeine, Redis, or another provider, and you can change it through configuration without editing your business code.
This chapter stays on the decision. The next chapter explains the abstraction, and the following chapters turn it on and use it.
// The idea in plain Java, without Spring. A map plays the role of the cache.
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ManualCacheDemo {
private final Map<Long, String> cache = new ConcurrentHashMap<>();
private int backendCalls = 0;
String findName(Long id) {
return cache.computeIfAbsent(id, this::loadFromBackend);
}
private String loadFromBackend(Long id) {
backendCalls++;
return "product-" + id; // stands in for a slow call
}
public static void main(String[] args) {
ManualCacheDemo demo = new ManualCacheDemo();
demo.findName(1L);
demo.findName(1L);
demo.findName(2L);
System.out.println("Backend calls: " + demo.backendCalls); // prints 2
}
}Three lookups cause only two backend calls, because the second lookup of id 1 is a hit. This hand-written version has no expiry, no size limit, and no eviction. Writing those yourself, and keeping them correct under concurrent access, is the work Spring and its providers take over.
Deciding in practice
A short procedure works for most services:
- Identify a method that is slow or heavily called, using measurements.
- Check that it is free of side effects and returns the same result for the same input.
- Decide how stale the result may be. This sets your TTL and eviction needs.
- Choose local or shared storage based on how many instances run and how much inconsistency they can tolerate.
- Set a size limit and an expiry from the start.
- After release, watch the hit ratio and adjust or remove the cache if it does not help.
Summary of the trade-off
Caching exchanges freshness and simplicity for speed and lower backend load. It pays off for expensive, repeated, stable, side-effect-free reads. It does not suit exact, fast-changing, or one-off results. Treat each cache as a design decision with a defined staleness limit and a size bound, and verify with metrics that it works.
Exercise
A method fetches a customer's loyalty points from a remote service in 200 ms. A cache lookup takes 2 ms. In production, 75 percent of calls ask for a customer already requested in the last few minutes. Estimate the average latency with a cache. Then name one reason you might still choose not to cache this method.
Show answer
Average = 0.75 × 2 + 0.25 × 200 = 1.5 + 50 = 51.5 ms, down from 200 ms. A reason not to cache: points may change after each purchase, so a stale value could be shown to a customer who expects an up-to-date total. Caching is only acceptable if a delay of a few minutes is allowed or if the cache entry is evicted whenever points change.
Exercise
Why is a method that sends a confirmation email a poor candidate for caching, even if it is slow?
Show answer
A cache hit returns the stored result without running the method body. The email would be sent on the first call and silently skipped on later calls with the same arguments. Caching assumes the method has no side effects.