1

Is there a native way in Redis to invalidate a cache item when other specified items get removed from the cache? Is there an eviction policy based on dependencies?

Here is an example of what I want to accomplish.

Let's say in Redis we have a cache item whose key is mainKey. I would like this item to be automatically removed if another specific item gets removed. If ,for example, mainKey has dependencies on the keys d1 and d2, then I would like mainKey to be removed from the cache as soon as either d1 or d2 is removed from the cache.

In .Net, for example, something like this is fairly easy to code using MemoryCache.

[TestMethod] public void TestCacheItemIsRemovedWhenADependencyGetsRemoved() { // ARRANGE var cache = new MemoryCache(name: "MyCache"); // insert dependencies cache items var dummyValue = 1; cache.Set("d1", dummyValue, absoluteExpiration: DateTime.Now.AddDays(1)); cache.Set("d2", dummyValue, absoluteExpiration: DateTime.Now.AddDays(1)); // build cache policy for main cache item var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(10) }; var dependencies = new[] { "d1", "d2" }; var changeMonitor = cache.CreateCacheEntryChangeMonitor(dependencies); policy.ChangeMonitors.Add(changeMonitor); // insert main cache item cache.Set("mainKey", "this is the main value", policy); // ACT // remove a dependency key cache.Remove("d1"); // ASSERT // mainKey is removed as a consequence of removing "d1" Assert.IsFalse(cache.Contains("mainKey")); // only "d2" remains in the cache Assert.AreEqual(1, cache.GetCount()); Assert.IsTrue(cache.Contains("d2")); } 

1 Answer 1

0

This is a known obstacle in cache invalidation and you need Cache Tagging to overcome it.

for example, mainKey has dependencies on the keys d1 and d2, then I would like mainKey to be removed from the cache as soon as either d1 or d2 is removed from the cache.

TL;DR - You need to tag keys that are dependent on each other, and when some action (update or delete) occurs to one of them, you would need to remove all the cached items that are sharing the the same tag.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.