Caching & Redis strategies, invalidation and stampedes
Cache-aside, read-through, write-through and write-behind, TTLs, invalidation, the thundering herd, Spring Cache with Redis, and the other things Redis does (rate limits, locks, pub/sub, sessions).
“There are only two hard things in computer science: cache invalidation and naming things.” (Phil Karlton)
Where you’ve touched it
ReportLineRepository.java:38 · CommunityLineRepository.java:24@Cacheable(value = "reportLines", key = "#types.toString()")
List<ReportLine> findByTypes(Set<ReportLineType> types);This uses @EnableCaching with the default in-memory ConcurrentMapCacheManager: no TTL, no size limit, and per instance. That’s fine for static reference data that only changes at deploy time.
Caching patterns
| Pattern | Flow | Use |
|---|---|---|
| Cache-aside (lazy) | App reads the cache; on a miss it reads the DB and fills the cache | Most common; what @Cacheable does |
| Read-through | The cache library loads from the DB itself | Caffeine LoadingCache |
| Write-through | Write the cache and DB together | Read-heavy data that must be fresh |
| Write-behind | Write the cache now, the DB later | Very high write rates; risk of loss |
| Refresh-ahead | Refresh hot keys before they expire | Predictable hot data |
Spring Cache + Redis
spring:
cache.type: redis
data.redis.url: ${REDIS_URL}
cache.redis.time-to-live: 10m
@Cacheable(cacheNames = "hostelDetails", key = "#id")
public HostelDetailsResponseDto details(UUID id) { /* expensive joins */ }
@CacheEvict(cacheNames = "hostelDetails", key = "#id")
public void update(UUID id, UpdateHostelRequest r) { /* ... */ }
Cache DTOs, never JPA entities (lazy proxies don’t serialise well). Include the tenant id in keys for SaaS.
Invalidation strategies
- TTL. Simple; data can be stale for up to the TTL.
- Explicit eviction on writes (
@CacheEvict). Correct only if every write path evicts. - Event-driven eviction. Listen for domain events (
HostelUpdated) and evict. Works across instances through Redis pub/sub. - Versioned keys.
hostel:42:v7; bump the version to invalidate.
The thundering herd (cache stampede)
A hot key expires, and 1,000 concurrent requests all miss and hit the DB at once. Mitigations:
- Request coalescing. One loader fetches while the others wait (
@Cacheable(sync = true), Caffeine). - Jittered TTLs so keys don’t all expire together.
- Stale-while-revalidate. Serve the old value while one request refreshes it.
Layers of caching
Browser cache (Cache-Control, ETag) -> CDN (Cloudflare/CloudFront) -> app local cache (Caffeine)
-> distributed cache (Redis) -> DB buffer cache (shared_buffers) -> disk
Cache-Control: public, max-age=300 on GET /api/hostels lets Cloudflare absorb most of that traffic for free.
What else Redis gives you
| Feature | Fixes in your projects |
|---|---|
| Atomic counters and Lua scripts | Distributed rate limiting (Hostel, SperoTek) |
SET key val NX PX 30000 / Redisson locks / ShedLock-Redis |
Cluster-safe schedulers (IR3D) |
| Pub/Sub | Cross-instance SSE and WebSocket fan-out (RM, IR3D) |
| Spring Session | Shared sessions if you ever need them |
| Streams | A lightweight queue |
| GEO | Fast nearby search (alternative to PostGIS for live locations) |
| Sorted sets | Leaderboards, the FYP feed ranking in IR3D |
Alternatives
Caffeine (an in-process cache with TTL and size limits, far better than the default ConcurrentMap), Memcached (simpler, no persistence), Valkey/KeyDB/Dragonfly (Redis-compatible), and Postgres materialized views.