We recently thought we could benefit from having a 2-tier caching solution, using Redis as a distributed cache, and the benefits of Caffeine as a local cache. Our reasoning was that while Redis does have a local cache component to it, we are storing json as our values, resulting in deserialization of the text json payload into the actual object every time we have a cache hit. Caffeine stores the raw object, so we would avoid that hit, and hence, the cpu overhead of deserializing from json.
In our case, this ultimately did not prove useful in it’s most basic form. Our performance testing showed that in our case, we cannot store enough objects in-memory to make the 2-tier caching effective enough. Granted, our performance testing doesn’t really reflect the true production usage of our service, but we’re also dealing with sizable objects (1.3M each) so configuring Caffeine to store just 1000 objects is a prohibitively large amount of memory. I did want to take the time to document what is involved in setting up a 2-tier cache, though, both for my own use, and for others use, as an example.
This was influenced quite heavily by this Baeldung article … though I am pretty sure their example won’t work without some of the extra wiring that we have performed here.
Our application configuration consists of building several components:
- CacheManager (the caffeineCacheManager)
- CacheManager (the primaryCacheManager — which is our redisCacheManager)
- CacheInterceptor (our menuCacheInterceptor)
/**
* This builds the Caffeine cache manager; the primary configuration is the "expireAfter", which sets the expiration of the entry in the caffeine
* cache to be based upon the expiration attribute contained within the menu itself. In this way, the caffeine cache and the redis cache are kept
* in sync, barring manual clearing of cache entries within redis, or via the admin api.
*
* @param cacheExpiration
* @return
*/
@Bean
CacheManager caffeineCacheManager( final CacheExpiration cacheExpiration,
@Value( "${menu.cache.caffeineMaximumSize:1000}" ) final long maximumSize ) {
// Setting the expiration in Caffeine cache to be the expiration based off the menu.
caffeineCache = Caffeine.newBuilder().maximumSize( maximumSize ).recordStats().expireAfter( new CaffeineExpiry( cacheExpiration ) ).build();
CaffeineCache getSiteMenuCache = new CaffeineCache( MENU_CACHE_PREFIX, caffeineCache );
SimpleCacheManager manager = new SimpleCacheManager();
manager.setCaches( Arrays.asList( getSiteMenuCache ) );
return manager;
}
static class CaffeineExpiry implements Expiry<Object, Object> {
final CacheExpiration cacheExpiration;
CaffeineExpiry( final CacheExpiration cacheExpiration ) {
this.cacheExpiration = cacheExpiration;
}
@Override
public long expireAfterCreate( Object key, Object value, long currentTime ) {
if ( value instanceof MenuResponse ) {
return cacheExpiration.expirationNanos( (MenuResponse) value );
}
return 0L;
}
@Override
public long expireAfterUpdate( Object key, Object value, long currentTime, long currentDuration ) {
return currentDuration;
}
@Override
public long expireAfterRead( Object key, Object value, long currentTime, long currentDuration ) {
return currentDuration;
}
}
@Bean
@Primary // any dynamic caches created will be redis caches.
CacheManager primaryCacheManager( @Qualifier( "redisCacheManager" ) final CacheManager redisCacheManager ) {
return redisCacheManager;
}
@Bean
public CacheInterceptor menuCacheInterceptor( final BeanFactoryCacheOperationSourceAdvisor cacheAdvisor, final CacheExpiration cacheExpiration,
@Qualifier( "caffeineCacheManager" ) final CacheManager caffeineCacheManager,
final CacheOperationSource cacheOperationSource,
final RedisTemplate<String, MenuResponse> redisTemplate ) {
CacheInterceptor interceptor = new MenuCacheInterceptor( cacheExpiration, caffeineCacheManager, cacheOperationSource, redisTemplate );
cacheAdvisor.setAdvice( interceptor ); // Enable the interceptor inside of Spring.
return interceptor;
}
There really isn’t anything special about the creation of the redisCacheManager; it’s done in the normal spring-data-redis fashion. We do this within a library, and provide configuration for it — this @Bean is just to force our redis CacheManager to be the primary CacheManager for the application.
The purpose of the menuCacheInterceptor is to intercept the calls made to the menu cache, and keep the caffeine cache up to date.
The CaffeineExpiration is included because I found this interesting — that with Caffeine, you can provide a function to set the expiration times on a per-entry basis. In our case, the object we are storing contains an expiration date/time, so this function just utilizes a different class we created that determines the appropriate expirations in both formats required (for redis, and for caffeine).
The CacheExpiration class is rather straight forward, and we used this:
@Component
public class CacheExpiration implements Serializable {
private static final long serialVersionUID = 1L;
private final long ttlMarginSecs;
private final long minimumTtlSecs;
public CacheExpiration( @Value( "${menu.cache.minimumTtlSecs:60}" ) final long minimumTtlSecs ) {
this.minimumTtlSecs = minimumTtlSecs;
}
public Instant expiration( final MenuResponse response ) {
Instant expireAt = response.getMenuLists().getCacheExpirationDate().toInstant();
// Expire at "now" (in time zone of menu time) plus minimumCacheTimeSecs
Instant expireMin = Calendar.getInstance( response.getMenuLists().getCacheExpirationDate().getTimeZone() ).toInstant()
.plus( minimumTtlSecs, ChronoUnit.SECONDS );
// Return the latter of expireMin or expireAt
return expireMin.isAfter( expireAt ) ? expireMin : expireAt;
}
public long expirationNanos( final MenuResponse response ) {
Instant expire = expiration( response );
long diffInMillis = expire.toEpochMilli() - Instant.now().toEpochMilli();
return 1_000_000 * diffInMillis;
}
}
The “expiration” method is the core method, and we use that for Redis. The “expirationNanos” is used for the Caffeine expiration, since it requires a nanoseconds-until-expiration.
The next class we use is a bit hokey; I refer you to this stack overflow posting I made for explanation:
@Component
public class InterceptorRegistration {
public InterceptorRegistration( CacheInterceptor menuCacheInterceptor ) {
}
}
Now we come to the real meat of the system — the MenuCacheInterceptor:
public class MenuCacheInterceptor extends CacheInterceptor {
private final CacheExpiration cacheExpiration;
private final CacheManager caffeineCacheManager;
private final RedisTemplate<String, MenuResponse> redisTemplate;
public MenuCacheInterceptor( final CacheExpiration cacheExpiration, final CacheManager caffeineCacheManager,
final CacheOperationSource cacheOperationSource, final RedisTemplate<String, MenuResponse> redisTemplate ) {
this.cacheExpiration = cacheExpiration;
this.caffeineCacheManager = caffeineCacheManager;
this.redisTemplate = redisTemplate;
this.setCacheOperationSources( cacheOperationSource );
}
@Override
protected Cache.ValueWrapper doGet( final Cache cache, final Object key ) {
Cache.ValueWrapper existingCacheValue = super.doGet( cache, key );
if ( existingCacheValue != null && cache.getClass() == RedisCache.class ) {
// If we did a get from Redis, it means we did not have a hit in Caffeine .... so we need to update Caffeine.
// This is because if we have a complete miss ... i.e., spring-cache sees a miss on both caches, it will update
// both caches via a doPut. If there is a hit only on the second cache (Redis), then spring-cache will not
// invoke the doPut at all, ignoring the miss on the first cache. So we have to do it manually.
updateCaffeineCache( cache, key, existingCacheValue );
}
return existingCacheValue;
}
private void updateCaffeineCache( final Cache cache, final Object key, final Cache.ValueWrapper existingCacheValue ) {
Cache caffeineCache = caffeineCacheManager.getCache( cache.getName() );
if ( caffeineCache != null ) {
// Always put, because the redis cache was updated -- force update caffeine.
// The cache has the name built in, so don't add the CACHE_NAME and CACHE_MENU.
caffeineCache.put( key, existingCacheValue.get() );
}
}
@Override
protected void doPut( final Cache cache, final Object key, @Nullable final Object value ) {
super.doPut( cache, key, value );
if ( cache.getClass() == RedisCache.class && CacheConfiguration.MENU_CACHE_PREFIX.equals( cache.getName() ) ) {
if ( value instanceof MenuResponse menuResponse ) {
Instant expirationTime = cacheExpiration.expiration( menuResponse );
redisTemplate.boundValueOps( CacheConfiguration.MENU_CACHE_PREFIX + "::" + key.toString() ).expireAt( expirationTime );
}
}
}
}
This is where the main action is. We’ve wired our MenuCacheInterceptor as an interceptor on the redis cache.
What this leads to is that we can configure our component that retrieves Menus with annotations such as:
@Caching(cacheable = {
@Cacheable( cacheManager = "caffeineCacheManager", cacheNames = CACHE_NAME_PREFIX, key = "#siteNumber ),
@Cacheable( cacheManager = "redisCacheManager", cacheNames = CACHE_NAME_PREFIX, key = "#siteNumber" )
})
public MenuResponse getSiteMenu( String siteNumber ) { ... }
We use the @Caching annotation to specify @Cacheable twice. Spring-cache will handle this just fine, but we need the interceptor to help keep the caches in sync. What Spring-cache will do when it encounters this situation is:
- Use the first cache to look up a value
- if there is a cache miss, go to the second cache
- if there is a cache hit, use that value and return
- If the first cache is missed, use the second cache to look up a value
- if there is a cache miss, perform a cache put on both caches
- if there is a cache hit, return that value and continue
- if there is a cache miss, perform a cache put on both caches
What we need to do in our interceptor is to intercept that doGet on the redis cache, because if we got to there, and there was a cache hit, that means Caffeine didn’t have the value — so we have to manually insert that into the cache. Fortunately, we can just look up the Caffeine cache and perform a put on it, and we’re done. The expiration handling will take place due to our configuration of the CaffeineCache itself.
What we are doing the interception of the doPut on the redis cache is to appropriately set the expiration ttl from the data in the object. This keeps cache code out of our business logic, and it’s handled purely in the context of the @Cacheable annotation.
And …. that’s basically it. There might be a few things missing … but at this point, they should be easily figured out.
