A tiny, production-style starter showing Spring Cache abstraction with Caffeine.
- Spring Boot 3.3.x, Java 21
@EnableCaching
+ Caffeine spec viaapplication.yml
- REST endpoints to fetch/update/delete users
- Single-flight caching (
sync=true
) to avoid stampede - Actuator with cache metrics exposed
Prereqs: Java 21 and Maven 3.9+
cd caffeine-cache-demo
mvn spring-boot:run
First call is slow (~400ms), subsequent calls are cached and fast.
# First call (cache miss -> slow)
curl -s localhost:8080/api/users/1 | jq
# Second call (cache hit -> fast)
curl -s localhost:8080/api/users/1 | jq
# See how many times the underlying load ran
curl -s localhost:8080/api/debug/loadCount
# -> 1
# Update (write-through into cache)
curl -s -X PUT "localhost:8080/api/users/1?name=Vinod" | jq
# Evict by delete
curl -i -X DELETE localhost:8080/api/users/1
# Miss again (load count increments)
curl -s localhost:8080/api/users/1 | jq
curl -s localhost:8080/api/debug/loadCount
Edit spring.cache.caffeine.spec
in application.yml
:
maximumSize=10000,expireAfterWrite=10m,recordStats
Common options: expireAfterAccess
, initialCapacity
, refreshAfterWrite
(use with loading cache patterns).
With Actuator:
GET /actuator/metrics/cache.gets
(tagscache=users
etc.)GET /actuator/metrics/cache.hit.ratio
You can wire Prometheus/Grafana later; Micrometer auto-binds Caffeine stats.