api-rpgoramming

From Hell To Heaven: Safeguarding your application – Part 1

Have you ever wondered how to safeguard your application when using the database and a cache like Redis? What if one of them is down? What should we do? These are questions that every developer should ask themselves when building an API that needs to be reliable 24/7.

In this guide, we will be configuring a cache error handler that will cover every scenario where Spring Cache annotations are used.

Building the cache error handler

The reason to build a custom error handler is simple: we want the application working even though the cache is down.

We will need to do two things: Implement the CacheErrorHandler interface and registering into our application. Below is the implementation of our class:

package com.jerieshandal.api.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.interceptor.CacheErrorHandler;

@Slf4j
public class CustomCacheErrorHandler implements CacheErrorHandler {

    @Override
    public void handleCacheGetError(RuntimeException e, Cache cache, Object o) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void handleCacheClearError(RuntimeException e, Cache cache) {
        log.error(e.getMessage(), e);
    }
}

The final step is to registering into a class extending CachingConfigurerSupport as shown in the code below:

package com.jerieshandal.api.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;

public class CacheConfig extends CachingConfigurerSupport {

    @Override
    public CacheErrorHandler errorHandler() {
        return new CustomCacheErrorHandler();
    }
}

Testing

After implementing the previous code, you can stop your Redis instance or connect to an invalid host. Then do several calls to your API, which will show the error in the logs but the API will continue working.

This is the ending of the part 1 of the safeguarding your application guide. In the next post, we will be looking into building a strategy to cover those special scenarios where we build custom cache interaction around a certain service.

Feel free to ask any questions or post any comments about this topic.