Video in progress
When Redis goes down, the `@Cacheable` methods throw exceptions too and the whole API returns 500. How do you soften this?
Spring's default SimpleCacheErrorHandler rethrows cache errors. If you provide your own CacheErrorHandler that logs the error and treats it as a miss, the method falls through to the DB. You also need a short Redis timeout, otherwise every request waits for seconds.
📖 Answer
A cache is an optimization. When it fails, the business function shouldn't fail with it, but the default behavior is exactly that: RedisConnectionFailureException goes all the way up to the controller.
@Configuration
@EnableCaching
class CacheConfig implements CachingConfigurer {
private static final Logger log = LoggerFactory.getLogger(CacheConfig.class);
@Override
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler() {
public void handleCacheGetError(RuntimeException e, Cache c, Object key) {
log.warn("Kesh o'qilmadi {}::{}", c.getName(), key, e); // we carry on as a miss
}
public void handleCachePutError(RuntimeException e, Cache c, Object key, Object v) {
log.warn("Keshga yozilmadi {}::{}", c.getName(), key, e);
}
public void handleCacheEvictError(RuntimeException e, Cache c, Object key) {
log.error("Evict bo'lmadi {}::{}", c.getName(), key, e);
}
public void handleCacheClearError(RuntimeException e, Cache c) {
log.error("Clear bo'lmadi {}", c.getName(), e);
}
};
}
}
Without a timeout this is a half-solution. In practice this problem usually shows up on the first Redis restart: if Redis doesn't answer, every call waits for the default timeout.
spring:
data:
redis:
timeout: 200ms
connect-timeout: 500ms
Two subtle points:
- if you swallow an evict error, the old value is still in Redis when it comes back. So export evict errors to metrics and don't make the TTL unlimited;
- now the entire load lands on the DB. Will the DB survive if Redis stays down for long? Check it in a load test, and add a circuit breaker if needed.
Sign up to mark studied questions and save your progress.