2-Tier Caching With Redis And Caffeine

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

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.

Posted in Software | Tagged , , , , | Leave a comment

Spring Cloud Config Server and “Cannot check out from unborn branch”

Working in a Kubernetes environment, and we’re running a Spring Cloud Config Server connecting to gitlab.com. Occasionally, we’d get an error like “Caused by: java.lang.UnsupportedOperationException: Cannot check out from unborn branch” … but yesterday we were absolutely hammered by that message. No idea why it suddenly reared it’s head, and basically took down our config server (causing apps to not be able to come up cleanly, or not be able to come up with the right configuration ….).

In the end, all it seems it took was to add the “spring.cloud.config.server.git.refreshRate” parameter to 10 (seconds). Apparently what was happening was requests for parameters coming close enough to either overlap, or … something … causing issues in the project. Note that at this point, we are not configured to have gitlab push notifications of changes to our SCCS, or have application auto-refresh on an update — so this could be avoided by doing that. By having SCCS reach out on each call for parameters, though, seems to be problematic (which is what the default refreshRate setting of zero will do).

In the end …. it appears to have been fixed, but it’s mysterious enough that I wanted to share.

Posted in Software | Tagged , , | Leave a comment

gp-saml-gui and an expired cert

This is also posted on https://github.com/dlenski/gp-saml-gui/issues/83

gp-saml-gui is a good command-line global-protect client for linux. What I posted on that link above is:

Ran into this when the company I am working for let a cert expire. I resolved it doing 2 things:

  1. launching with –no-verify
  2. modifying the init_poolmanager to add ssl_context.check_hostname = False after the set_ciphers (in gp_saml_gui.py).

Works like a charm after that.

The issue we ran into is that after adding –no-verify, we’d get an error “ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled.” That sparked some google searching, and I found a reference to setting the ssl_context.check_hostname and …. viola! Works.

Posted in Software | Tagged , | Leave a comment

Resetting Log4j/Log4j2 During a Unit Test

We are writing a log masking plugin, and need to support both PatternLayout and JsonLayout. Testing is pretty easy conceptually — create a logger, write data to the logger, and make sure the output (via OutputCaptor) is properly masked.

The issue we ran into is … while the 2 separate test classes run fine separately, running them together becomes an issue. A lot of digging via “Professor Google” turned up lots of ideas, but what worked in the end is trivially simple: just reconfigure the logger via the Configurator class.

    @BeforeEach
    public void setLogger() throws SecurityException, IllegalArgumentException, URISyntaxException
    {
        Configurator.reconfigure( new URI( "src/test/resources/log4j2-json.xml" ) );
        LOGGER = LoggerFactory.getLogger( LogMaskingConverterTest.class );
    }

You can always reset the logger back to your default after the class in exactly the same way:

    @AfterEach
    public void resetLogger() throws SecurityException, IllegalArgumentException, URISyntaxException {
        Configurator.reconfigure( new URI( "src/test/resources/log4j2.xml" ) );
        LOGGER = LoggerFactory.getLogger( LogMaskingConverterTest.class );
    }

And viola! The logger is reset to the spec in the relevant xml file.

Posted in Software | Tagged , , , , | Leave a comment

Incorrect Postgres Sequence

Just a quick one — we’ve run into this at least twice in our performance environment (PE), where we get a particular odd postgresql error.

The error we are getting is basically:

ERROR: relation "customer.customer_customer_id_seq" does not exist
  Position: 16

The key part is that it’s a sequence … and it says “does not exist Position: 16”.

Since the sequence clearly exists, we did what we always do — consult Professor Google. What he said is to look at this URL: https://discourse.hibernate.org/t/incorrect-postgres-sequence-identified-for-id-column/3828

Many thanks to JasonW on that blog post; seems the only viable solution is to restart the app. Like him, we have no idea what condition causes this state in postgresql …

Posted in Software | Tagged , , | Leave a comment

Fast Paste of Clipboard to File

I’ve struggled with this for a long time — how do you paste a large quantity of text into a file quickly? Normally, I just open a vi window in a shell, enter insert mode, and paste (talking linux, so …control-shirt-v in my shell). This then scrolls through as the paste is happening … and my 1MB json file is slowly pasted into the file.

It turns out you can just use:

xsel -b > /tmp/file.json

and the result is just about as instantaneous as you can get.

I discovered this via this stackexchange posting, by Gilles ‘SO- stop being so evil’.

There are just so many tools available — it pays to dig a little and figure out what you really need.

Posted in Software | Tagged , , , | Leave a comment

Control Logging Level for Specific Class With Log4j2.xml

Simple case — we have an application which is logging only at the ERROR level (don’t ask why … inherited this). We have a new class we added, which has some WARN logging we really need to see. The old log4j2.xml looks something like this:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="com.wendys.microservices.shared.appender">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="|%date{yyyy/MM/dd HH:mm:ss,SSS zzz}|%6level|%50.50thread|%40.40logger| %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
    <Logger name="com.co.myclasses.MySpecificClass" level="warn" additivity="false"/>
  </Loggers>
</Configuration>

For some reason, this does NOT work; the logging for MySpecificClass at the warn level does not show up. This post gave us the hint that we needed — the specific logger has to include the AppenderRef, so our log4j2.xml has to look like:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="com.wendys.microservices.shared.appender">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="|%date{yyyy/MM/dd HH:mm:ss,SSS zzz}|%6level|%50.50thread|%40.40logger| %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
    <Logger name="com.co.myclasses.MySpecificClass" level="warn" additivity="false">
      <AppenderRef ref="Console"/>
    </Logger>
  </Loggers>
</Configuration>

Note the inclusion of the AppenderRef.

Tracing this to the log4j2.xml documentation, this appears to be because of the ‘additivity=”false”‘ line .. which we added because we are using an output capture tool during testing (if memory serves correctly). In the documentation, they say:

Once an event reaches a logger with its additivity set to false the event will not be passed to any of its parent loggers, regardless of their additivity setting.

At this point, with the AppenderRef added, we are in good shape and our logging shows up properly.

Posted in Software | Tagged , | Leave a comment

Modify Outbound JSON Attribute Names on the Fly

Ok … we ended up in a stupid situation due to some poorly crafted code by someone in the past. What happened was that we had some domain classes with very similar attributes that lent themselves well to some refactoring with a common base class. The two classes looked something like this (different packages, different class names, though that doesn’t really affect things … but for completeness, worth mentioning):

public class LineItem {
    private Integer salesId;
    private Integer menuId;
    private Integer quantity;
. (other attributes)
.
}

public class OtherLineItem {
    private Integer SalesId;
    private Integer MenuId;
    private Integer Quantity;
. (other attributes, not the same as above)
.
}

The refactoring that made sense was to introduce a parent item class, so we had the following:

public class Item {
    private Integer salesId;
    private Integer menuId;
    private Integer quantity;
.
.
}

public class LineItem extends Item {
.
.
}

public class OtherLineItem extends Item {
.
.
}

The problem now is …. you’ll notice in OtherLineItem that someone, in their infinite wisdom, chose to make the attribute names capitalized, which has the effect of capitalizing the attribute name in the Jackson-jsonified version as well. Actually, to make this more aggravating, OtherLineItem has some attributes starting with upper-case, and some with lower-case — so there is no consistency.

In our case, the OtherLineItem was used just outbound, but we wanted the convenience of handling properties on inbound as well, mostly due to testing. That part is easy enough, to add an @JsonAlias annotation to Item. This has Item looking like:

public class Item {
    @JsonAlias( "SalesId" )
    private Integer salesId;

    @JsonAlias( "MenuId" )
    private Integer menuId;

    @JsonAlias( "Quantity" )
    private Integer quantity;
.
.
}

This takes care of being able to read the json, but … how do we ensure that the OtherLineItem will have the correct capitalization when you write out the json with Jackson’s ObjectMapper (which is what SpringBoot does)?

The solution is the BeanSerializerModifier. You can register your own modifier with the ObjectMapper, so when Jackson is serializing an object, it will always invoke this serializer with information about the ObjectMapper configuration, the bean itself, and the proposed way to write the properties (via a List<BeanPropertyWriter>). Our approach to this solution was heavily influenced by an answer in posting on stackoverflow, by Bhashit Parikh.

We introduce a custom BeanSerializerModifier that is something like this:

public class OtherLineItemBeanSerializerModifier extends BeanSerializerModifier {

    private static final Map<String, String> RENAMEABLE_PROPERTIES = Map.of(
        "salesItemId", "SalesItemId",
        "menuItemId", "MenuItemId",
        "quantity", "Quantity" );

    @Override
    public List<BeanPropertyWriter> changeProperties( SerializationConfig config,
                                                      BeanDescription beanDesc,
                                                      List<BeanPropertyWriter> beanPropertyWriters ) {

        if ( beanDesc.getBeanClass() == OtherLineItem.class ) {
            Map<Integer, BeanPropertyWriter> newWriters = new HashMap<>();

            for ( int i = 0; i < beanPropertyWriters.size(); i++ ) {
                BeanPropertyWriter writer = beanPropertyWriters.get( i );

                String newPropertyName = RENAMEABLE_PROPERTIES.get( writer.getName() );
                if ( newPropertyName != null ) {
                    newWriters.put( i, new OurBeanPropertyWriter( writer, new PropertyName( newPropertyName ) ) );
                }
            }

            if ( !newWriters.isEmpty() ) {
                for ( Map.Entry<Integer, BeanPropertyWriter> entry : newWriters.entrySet() ) {
                    beanPropertyWriters.set( entry.getKey(), entry.getValue() );
                }
            }
        }

        return beanPropertyWriters;
    }

    private class OurBeanPropertyWriter extends BeanPropertyWriter {
        public OurBeanPropertyWriter( BeanPropertyWriter base, PropertyName name ) {
            super( base, name );
        }
    }
}

Basically, what is happening is that when the OtherLineItem is being serialized, this method will be invoked giving us the opportunity to make changes in pretty much any part of the output. We only want to change the name of the attribute ( salesId => SalesId, etc). We do this by replacing the BeanPropertyWriter that comes in for each property we want to change, replacing it with an instance of OurBeanPropertyWriter. We make use of a method to clone the original writer, including our new name in the method.

All that is left is to register this custom BeanSerializerModifier with ObjectMapper, and have SpringBoot pick it up for it’s own use. The Spring part is easy — just define an ObjectMapper bean, and SpringBoot will prefer that to it’s own. So what we have is an @Configuration class that looks like:

@Configuration
public class ObjectMapperConfiguration {

	@Bean
	public ObjectMapper objectMapper() {
	    SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier( new OtherLineItemBeanSerializerModifier() );

	    ObjectMapper objectMapper = new ObjectMapper();
	    objectMapper.setSerializerFactory( serializerFactory );

	    return objectMapper;
	}
}

With that, we are done. Whenever we have a controller that outputs a LineItem, the constructed json will have lower-case attribute names; whenever we output OtherLineItem, the relevant attributes will start with an upper-case letter.

Ultimately, in our application, we need to modify the clients to read lower-case attributes (really, read case-insensitive attributes for now, with @JsonAlias), and then modify our server-side code to output json only with lower-case attribute names. For now, this is good enough.

Posted in Software | Tagged , , , , , , , | Leave a comment

Delete an Element From a List Via Streams By Index

We’ve been looking for a way to do this for a while, and it’s actually quite simple. We have a List<some type> and we have an equivalence between the contained object and the object that specifies what we’d like to delete.

With a for loop, this looks like:

void remove( List<MyObject> objectList, OtherObject spec ) {
    for ( int i = 0; i < objectList.size(); i++ ) {
        if ( spec.isSameItem( objectList.get( i ) ) ) {
            objectList.remove( i );
            break;
        }
    }
}

The “spec.isSameItem(…)” method is testing equivalence between the 2 types; since they are different types, we can’t rely on equals(), so …. isSame(…) based on a subset of attributes (yes, they have a common root in the inheritance hierarchy).

A way to do this via streams is actually pretty straight-forward; what we did is this:

void remove( List<MyObject> objectList, OtherObject spec ) {
    OptionalInt indexToDeleteOpt = IntStream
        .range(0, objectList.size() )
        .filter( index -> spec.isSameItem( objectList.get( index ) ) )
        .findFirst()
        .ifPresent( lineItemListWithIndex::remove );
}

With the findFirst returning an OptionalInt, we can use the ifPresent(….) to remove that element.

And viola! A streaming way to remove a matching element from a List via a Stream.

Posted in Software | Tagged , , , , | Leave a comment

Mocking a Static Method with Mockito

There are lots of tutorials on how to do this; what I’m interested in explaining is that in our Spring Boot application, we get the mockito-core dependency transitively, and do not include the mockito-inline dependency. We still can mock static classes, however, without issue.

If you are set up like we are, and you mock a static class, you may see an error like:

The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks

If you don’t want to include the mockito-inline dependency, you can just create a file in src/test/resources/mockito-extensions name org.mockito.plugins.MockMaker with the contents:

mock-maker-inline

and you are done. Mocking of statics will now work.

I was reminded of this when I ran into this issue for the second time, and stumbled across this post.

Posted in Software | Tagged , , | Leave a comment