Sub topic 5
Controlling cache keys
Every cache entry is stored under a key. If two calls produce the same key, the second call gets the first call's result. If equivalent calls produce different keys, the cache never hits. This chapter covers how Spring builds keys by default, how to write your own with SpEL (Spring Expression Language), and where keys go wrong. It assumes you can already annotate a method with @Cacheable and know what a cache name is.
How the default key is built
When you don't set a key, Spring uses a SimpleKeyGenerator with these rules:
| Method parameters | Resulting key |
|---|---|
| None | `SimpleKey.EMPTY`, a shared constant |
| One | The argument itself |
| Two or more | A `SimpleKey` wrapping all arguments |
A SimpleKey compares by equals and hashCode over its arguments. Your parameter types therefore need correct equals and hashCode. String, Long, enums and records already have them. A plain class without them gets a new key on every call, and every call becomes a miss.
The default only looks at arguments. It ignores the method name and the class. That causes the most common key bug.
Collisions between methods
@Service
public class CatalogService {
@Cacheable("catalog")
public Product productById(Long id) {
return null; // load product
}
@Cacheable("catalog")
public Category categoryById(Long id) {
return null; // load category
}
}Both methods take one Long, so productById(5L) and categoryById(5L) both use the key 5L in the cache catalog. The second caller receives a Product where it expects a Category, which usually fails with a ClassCastException at the call site. There are two fixes. Use a separate cache name per kind of data, or make the key explicit:
@Cacheable(cacheNames = "catalog", key = "'category:' + #id")
public Category categoryById(Long id) {
return null; // load category
}Separate cache names are usually better. They also let you give each cache its own expiry and size settings.
Writing keys with SpEL
The key attribute takes a SpEL expression. Spring evaluates it for each call with the method arguments in scope. A string literal needs single quotes inside the expression, as in 'category:' above.
You can reach arguments in three ways:
- By name:
#id,#product.id(). - By position:
#p0or#a0for the first argument. - Through the root object:
#root.args[0].
The root object also exposes #root.methodName, #root.method, #root.target (the real bean, not the proxy), #root.targetClass and #root.caches.
@Cacheable(
cacheNames = "prices",
key = "#productId + ':' + #currency.toUpperCase()")
public java.math.BigDecimal priceFor(Long productId, String currency) {
// Slow pricing lookup.
return new java.math.BigDecimal("19.90");
}With this key, priceFor(7L, "eur") and priceFor(7L, "EUR") share one entry. Normalizing in the key stops near-duplicate arguments from filling the cache.
Reading properties of an argument
When a parameter is an object, key on the fields that identify the result and leave out the rest:
public record SearchCriteria(String category, int page, int size, String requestId) {}
@Cacheable(
cacheNames = "searches",
key = "#criteria.category() + '-' + #criteria.page() + '-' + #criteria.size()")
public java.util.List<Product> search(SearchCriteria criteria) {
return java.util.List.of();
}Here requestId differs on every call, so using the whole criteria as the key would never hit. Naming the identifying fields fixes that.
Parameter names must be available
#id only works if Spring can read parameter names. Spring Boot's Maven and Gradle plugins compile with -parameters, and debug information is another source. In a build without either, #id can fail to resolve. Use #p0 or #a0 in that case.
Which variables are available when
The key is normally evaluated before the method runs, so the result does not exist yet.
| Expression | `@Cacheable` key | `@CachePut` key | `@CacheEvict` key |
|---|---|---|---|
| Arguments (`#id`) | Yes | Yes | Yes |
| `#root.*` | Yes | Yes | Yes |
| `#result` | No | Yes | Only with `beforeInvocation = false` (the default) |
#result in a @Cacheable key is an error, because Spring needs the key to look up the entry before calling the method. In @CachePut the method always runs first, so #result is a valid key source:
@CachePut(cacheNames = "products", key = "#result.id()")
public Product create(String name, java.math.BigDecimal price) {
Product saved = new Product(System.nanoTime(), name, price);
return saved;
}How a key is resolved
Using a custom KeyGenerator
If many methods need the same key rule, write it once as a KeyGenerator bean and refer to it by name:
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
@Component("methodKeyGenerator")
public class MethodKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + ":" + method.getName()
+ ":" + Arrays.deepToString(params);
}
}@Cacheable(cacheNames = "reports", keyGenerator = "methodKeyGenerator")
public String load(String name) {
return "report:" + name;
}key and keyGenerator are mutually exclusive on one annotation. Setting both fails at startup. To change the default for the whole application, define a bean of type CachingConfigurer that returns your generator from keyGenerator(). Methods that set their own key still override it.
Because this generator includes the method name, two methods can share a cache name without colliding. The cost is that @CacheEvict on a different method can no longer remove the entry, since the method name is part of the key. Keep that in mind when you pair reads with evictions.
Keys in Redis
A local provider such as Caffeine stores your key object directly in a map, so equals and hashCode are all that matter. Redis needs a string key. RedisCache converts the key with a conversion service. It handles strings and numbers, and it falls back to toString() for classes that override it. Records and SimpleKey qualify. A key class with no toString override and no registered converter fails with an IllegalStateException that says the key cannot be converted to a string.
Two consequences follow:
- Build keys from simple values, as in the earlier
'category:' + #idexamples. They convert predictably and are readable inredis-cli. - Two different objects with the same
toString()output collide. Make sure that output includes every identifying field.
Redis also adds the cache name, and optionally a prefix, in front of your key. The spring.cache.redis.key-prefix setting from the provider chapter controls that prefix.
Failure modes
- Null arguments.
#name.toLowerCase()throwsNullPointerExceptionwhennameis null. Use the safe-navigation operator,#name?.toLowerCase(), or reject null earlier. A null key itself is an error. - Mutable key objects. If you mutate an object after using it as a key in a local cache, its
hashCodechanges and the entry can't be found again. Prefer records or immutable values. - Over-specific keys. Including timestamps, request IDs or whole entities makes every call a miss. Check hit rates with metrics to catch this.
- Under-specific keys. Leaving out an argument that changes the result (a locale, a tenant ID) returns wrong data to the wrong caller. Treat a missing identifying argument as a correctness bug, not a performance one.
- Key mismatch across annotations.
@Cacheable(key = "#id")and@CachePut(key = "#product.id()")only work together if both produce the same key value and type. ALongkey1and aStringkey"1"are different entries.
Exercise
A service has two methods, findUser(Long id) and findOrder(Long id), both annotated @Cacheable("data") with no key. After calling findUser(3L), calling findOrder(3L) returns a User object. Why does this happen, and name two ways to fix it.
Show answer
With no key set, the default generator uses the single argument as the key, so both methods use the key 3L in the cache data. The second call hits the entry the first call stored. Fix it by giving each method its own cache name (for example users and orders), or by making the keys distinct with SpEL, such as key = "'user:' + #id" and key = "'order:' + #id".
Exercise
Write a @Cacheable key expression for List<Product> byTag(String tag, int page) so that byTag("Sale", 0) and byTag("sale", 0) share one entry, and explain why #result can't be used in it.
Show answer
key = "#tag.toLowerCase() + ':' + #page". Spring must compute the key before calling the method to check for a cached value, so the result does not exist yet and #result is not available in a @Cacheable key.