Use cache-aside with Redis, explicit invalidation, TTLs as a safety net, and stampede protection. Basic setup - Spring Cache abstraction with Redis: @EnableCaching and spring-boot-starter-data-redis, with a RedisCacheManager configured with JSON serialisation (GenericJackson2JsonRedisSerializer) and a default TTL per cache. @Cacheable(cacheNames = "product", key = "#id") public ProductDto getProduct(long id) { return mapper.toDto(repository.findById(id).orElseThrow()); } @CacheEvict(cacheNames = "product", key = "#id") @Transactional public ProductDto updateProduct(long id, UpdateProductRequest req) { ... } Invalidation strategy - Evict or update keys when products change (@CacheEvict or @CachePut). Be careful with transactions: evicting before the commit can let another request re-cache stale data. Evict after commit with @TransactionalEventListener(phase = AFTER_COMMIT). - List and search caches are hard to invalidate precisely; use short TTLs or versioned keys (store a catalog version number and include it in list keys; incrementing it invalidates all lists at once). - Several services or instances: publish change events (Kafka or Redis pub/sub) so every consumer evicts its copies, especially if you also use a local in-memory cache (Caffeine) as a first level. - Always set TTLs, with random jitter so many keys do not expire at the same moment. Stampede (thundering herd) control - Per-instance: @Cacheable(sync = true) makes only one thread per instance load a missing key while others wait. - Across instances: a short Redis lock (SET key value NX PX 5000, or Redisson's RLock) so only one instance rebuilds a hot key. - Stale-while-revalidate: store the value with a soft expiry; serve the stale value while one request refreshes it in the background. - Probabilistic early refresh for very hot keys. - Cache negative results (product not found) briefly to stop repeated database hits for missing IDs. Operational concerns - Redis outages: configure timeouts and fall back to the database (a custom CacheErrorHandler that logs and continues), protected by a circuit breaker such as Resilience4j. - Memory: set maxmemory and an eviction policy (allkeys-lru), keep values small, and avoid caching huge lists. - Security: never mix tenant or user-specific data under shared keys. - Monitor hit ratio, latency, evictions and memory, and load-test cold-cache scenarios.
Ravindra Wadile · · 0 likes