Caching Custom Realm Plugin tokens

I have a custom realm plugin implemented to which I want to add caching until a certain time period and invalidate the cache. There is a CachingRealm interface which I can implement for the cache eviction APIs.
I was looking at the example in the link below and I see that there is a different cache realm type defined and it's extending the custom realm, doing some cache lookups/insertion and calling the super custom realm methods. I feel like this is some kind of duplication and could have the custom realm class itself implement the CachingRealm and have the logic there. Is there any specific reason it's done this way in the example? Also, why is the caching type not mapped in the .yml file?

Also, wanted to confirm if elastic is adding some kind of built-in caching for custom realm types like it does for some configured realms, I presume it's not.

Hey,

the different type was just implemented as an example (you should only have one of those in your plugin and that should the caching). You are good to go to implement the CachingRealm interface and yes, you have to implement the caching yourself (the example shows a time based expiry, but you can either tweak the (also other available) options of that one or just come up with your own implementations suiting your needs better). Check the org.elasticsearch.common.cache.CacheBuilder class for more info.

--Alex

1 Like

I went through the org.elasticsearch.common.cache.CacheBuilder implementation, looks like the setExpireAfterAccess and setExpireAfterWrite already throw out a Key after the specified amount of time, if that's the case why do we have this method to evict a Key from the Cache?
/**
* Removes the entry from the cache identified by the username
* @param username the identifier for the user to remove
*/
@Override
public void expire(String username) {
cache.invalidate(username);
}

If I just want to store my tokens in a cache for a certain period of time, looks like I don't even have to implement the CachingRealm, is my understanding right? I'm trying to think of a use case where this makes sense, is this for explicit removal of Key based on some custom logic?

If your realm caches information about users then it should implement CachingRealm so that the realm manager can clear the cache when it needs to.
Mostly that's in response to the clear cache API, but it can be triggered on other cases.

1 Like

One more thing I observed in the example is that the cache is not static, this would end up creating a new cache for every authorization call.

 private final Cache<String, UserHolder> cache = CacheBuilder.<String, UserHolder>builder()
            .setExpireAfterAccess(TimeValue.timeValueMinutes(30))
            .build();

Your Realm is a singleton. There is 1 instance of your realm per ES node, so a non-static cache is fine.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.