How can I delete cache entries by key prefix using built-in hybrid caching in ASP.NET Core 9?

How can I delete cache entries by key prefix using built-in hybrid caching in ASP.NET Core 9?
typescript
Ethan Jackson

What is the best way to implement prefix-based deletion of cached keys using only the built-in caching packages (without third-party libraries like Ziggurat or EasyCaching)?

Example:

Let’s say I have cached multiple items with the following keys:

"user-picture-1","user-picture-2","user-info-1",...

I want to remove only the cache entries whose keys start with "user-picture-", so that it deletes:

"user-picture-1","user-picture-2"

and does not delete other entries like "user-info-1".

Answer

ASP.NET Core's built-in caching mechanisms (MemoryCache and DistributedCache) do not natively support deletion by key prefix. This is by design — both cache implementations treat keys as opaque strings and lack built-in enumeration or prefix-based operations for performance and scalability reasons.

However, you can implement prefix-based deletion yourself by maintaining a key index or using a naming/versioning pattern.

public class CacheManager { private readonly IMemoryCache _cache; private readonly Dictionary<string, HashSet<string>> _prefixIndex = new(); public CacheManager(IMemoryCache cache) { _cache = cache; } public void Set<T>(string key, T value, string prefix, TimeSpan? expiration = null) { // Add to cache var options = new MemoryCacheEntryOptions(); if (expiration.HasValue) { options.SetAbsoluteExpiration(expiration.Value); } _cache.Set(key, value, options); // Track key in index if (!_prefixIndex.ContainsKey(prefix)) { _prefixIndex[prefix] = new HashSet<string>(); } _prefixIndex[prefix].Add(key); } public T? Get<T>(string key) { return _cache.TryGetValue(key, out T value) ? value : default; } public void RemoveByPrefix(string prefix) { if (_prefixIndex.TryGetValue(prefix, out var keys)) { foreach (var key in keys) { _cache.Remove(key); } _prefixIndex.Remove(prefix); } } }

Related Articles