Sub topic 15
Monitoring caches with Actuator and Micrometer
This chapter assumes you have a working cache from the earlier chapters. That means @EnableCaching, at least one @Cacheable method, and Caffeine or Redis configured as the provider. It also assumes you know how to add a Boot starter and edit application.properties. Here you will see what the cache is doing at runtime: which caches exist, how often they answer from memory, and how often they miss.
Why a cache needs monitoring
A cache that works is invisible, so a cache that doesn't work is invisible too. Three failures look identical from the outside, because the application returns correct data in all of them:
- A key expression produces a different key on every call, so every call is a miss.
- A TTL is so short that entries expire before they are reused.
- A size limit is so small that entries are evicted before they are reused.
In each case you pay for the cache and get none of the speed. The only way to tell is to count hits and misses. Spring Boot provides two pieces for this. The Actuator caches endpoint shows structure and lets you clear caches. Micrometer, the metrics library Actuator uses, supplies the counters.
Adding the dependencies
Add spring-boot-starter-actuator. It brings in Micrometer. Then expose the endpoints you want. Actuator exposes only health over HTTP by default.
management.endpoints.web.exposure.include=health,caches,metrics
spring.cache.type=caffeine
spring.cache.cache-names=products,productSearch
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m,recordStatsTwo details matter here. First, recordStats is required for Caffeine. Without it Caffeine does not count hits and misses, so the hit and miss counters stay at zero. Second, cache-names creates the caches at startup. Boot registers metrics for the caches that exist when the CacheManager initializes. A cache created lazily later may not be instrumented, so predefine the names you care about.
How the pieces connect
Boot looks at each CacheManager bean and each cache it holds. For every cache it finds, it asks a provider-specific binder to register meters in the MeterRegistry. Actuator and any monitoring backend then read from that registry.
The caches endpoint
GET /actuator/caches lists every cache grouped by cache manager. The response looks like this:
{
"cacheManagers": {
"cacheManager": {
"caches": {
"products": { "target": "com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalManualCache" },
"productSearch": { "target": "com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalManualCache" }
}
}
}
}This confirms that the provider you intended is active and that the cache names match what your annotations use. A typo in cacheNames shows up here as a missing cache, or as an error at runtime if the manager does not create caches dynamically.
The endpoint can also change state:
GET /actuator/caches/productsreturns one cache.DELETE /actuator/caches/productsclears that cache.DELETE /actuator/cachesclears every cache.
When several cache managers exist, add ?cacheManager=name to disambiguate.
Reading hit and miss counters
The metrics endpoint lists meter names at GET /actuator/metrics. The ones you will use for caches are in this table.
| Meter | Meaning | Notes |
|---|---|---|
| `cache.gets` | Lookups, tagged `result:hit` or `result:miss` | Core meter for hit ratio |
| `cache.puts` | Entries added | Caffeine and Redis |
| `cache.evictions` | Entries removed by the provider's policy | Caffeine only |
| `cache.size` | Approximate number of entries | Caffeine; not available for Redis |
| `cache.removals` | Entries removed by explicit invalidation | Redis |
Each meter carries the tags cache (the cache name) and cacheManager. Query one value with a tag filter:
# GET /actuator/metrics/cache.gets?tag=result:hit&tag=cache:products
# GET /actuator/metrics/cache.gets?tag=result:miss&tag=cache:productsThe response contains a COUNT measurement. Hit ratio is hits divided by hits plus misses. Misses alone also mislead: the first call for every key is always a miss, so a freshly started service has a low ratio that climbs as the cache warms.
Enabling Redis statistics
The Redis cache does not record statistics unless you ask for them:
spring.cache.type=redis
spring.cache.redis.enable-statistics=trueWith this setting, cache.gets, cache.puts and cache.removals appear. Redis counters are kept per application instance, so each instance reports only its own traffic. Your monitoring system must aggregate across instances.
Reading metrics from code
Sometimes you want the ratio inside the application, for example in a custom health indicator or a log line. Inject the MeterRegistry and look the counters up. Caffeine and Redis report cache.gets as function counters.
import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;
@Component
public class CacheHitRatio {
private final MeterRegistry registry;
public CacheHitRatio(MeterRegistry registry) {
this.registry = registry;
}
public double ratio(String cacheName) {
double hits = count(cacheName, "hit");
double misses = count(cacheName, "miss");
double total = hits + misses;
return total == 0 ? 0.0 : hits / total;
}
private double count(String cacheName, String result) {
FunctionCounter counter = registry.find("cache.gets")
.tag("cache", cacheName)
.tag("result", result)
.functionCounter();
return counter == null ? 0.0 : counter.count();
}
}The null check matters. If the cache was never bound, for instance because recordStats is missing or the cache name is wrong, functionCounter() returns null. Treating that as zero keeps the monitoring code from failing, but a ratio stuck at 0.0 with real traffic is a sign to check your configuration.
Sending metrics to a monitoring backend
The metrics endpoint shows only current values. To see trends, add a registry for your backend. For Prometheus, add micrometer-registry-prometheus and expose the endpoint:
management.endpoints.web.exposure.include=health,caches,metrics,prometheusPrometheus renames meters. cache.gets becomes cache_gets_total, and tags become labels. A query for the hit ratio over five minutes looks like this:
# PromQL
sum(rate(cache_gets_total{cache="products",result="hit"}[5m]))
/
sum(rate(cache_gets_total{cache="products"}[5m]))Using rate rather than raw totals means the figure reflects recent behavior, not the whole lifetime of the process.
Interpreting what you see
Use the counters to diagnose, not just to report.
- Low hit ratio and
cache.evictionsrising fast: the size limit is too small for your working set. RaisemaximumSize. - Low hit ratio and few evictions: entries are not being reused. Check the key expression, and check whether the TTL is shorter than the gap between repeated requests.
- High hit ratio but users report stale data: the cache is working too well. Review
@CachePut,@CacheEvictand the TTL. - Zero hits and zero misses on a cache with traffic: the annotated method is probably not going through the proxy. Review self-invocation from the earlier chapter.
- Zero for both on a Caffeine cache, but
/actuator/cacheslists it:recordStatsis missing.
Limits of these metrics
- Metrics count lookups, not value. A 95 percent hit ratio on a cheap query saves little. Compare against the cost of the underlying call.
cache.sizeis an estimate, and Caffeine may count entries pending eviction.- Statistics add a small overhead. For Caffeine this is negligible, and it is rarely a reason to turn them off.
- Counters reset when the process restarts, so a new deployment starts at zero.
Exercise
After deploying, /actuator/caches lists the products cache, and the service clearly serves repeated requests quickly. However, cache.gets with result:hit stays at zero for products. The provider is Caffeine, configured with spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m. What is the most likely cause, and how do you fix it?
Show answer
The Caffeine spec does not include recordStats, so Caffeine never counts hits and misses and the counters stay at zero even though caching works. Add recordStats to the spec: maximumSize=500,expireAfterWrite=10m,recordStats. Then restart and query cache.gets again.
Exercise
Why is the rate of cache_gets_total a better dashboard input than the raw total when you watch hit ratio after a deployment?
Show answer
Raw totals accumulate over the whole life of the process, so early traffic and cache warm-up dominate the figure and hide recent changes. Using rate over a window such as five minutes reflects only recent lookups, so a drop in hit ratio caused by the new deployment becomes visible quickly.