Careful Caching

Steve Ellwood
1 min readDec 31, 2020

--

Caching is hard and shouldn’t be undertaken lightly. What I am going to describe here is one workaround for one of the common questions about caching. Specifically how to not have a cache containing null values. This technique also works for other invalid values — such as an empty list. Although I’m going to use .net and LazyCache, this technique should be easily transferable to other languages and caching frameworks.

Typically I will have something like the following in my code

result = myCache.GetOrAdd(myCacheKey, () => mySearch(myParameter),myCacheDuration);

In my case I usually expect a collection of objects to be returned. Also in my case - if it’s got to this point - then the list returned should have at least one value so any null value or empty list is considered invalid and I don’t want it cached. Obviously in your case an empty list might be valid and that should be taken into account. Given that’s the case if the result is null or empty I can remove it from the cache

if (result.IsNullOrEmpty) {myCache.Remove(myCacheKey)};

This is by no means an ideal workaround as it doesn’t prevent the initial caching of invalid values but in my case it can be sufficient and it may be useful to others.

--

--

Steve Ellwood
Steve Ellwood

Written by Steve Ellwood

Senior Integrations Officer at Doncaster Council Any views expressed are entirely my own.

No responses yet