[EN] Efficiently Deleting Redis Keys by Pattern in .NET
Traditional Approach: The Drawbacks of Single Key Deletion
When working with Redis, you might typically use a method like the following to delete keys:
public class CacheManager {
private readonly IDistributedCache _cache;
public CacheManager(IDDistributedCache cache) {
_cache = cache;
}
public async Task RemoveKeys() {
await Cache.RemoveAsync("key-1");
await Cache.RemoveAsync("key-2");
await Cache.RemoveAsync("key-3");
}
}
The only problem with this approach is that we perform a round-trip for each key deletion, that is, we call the redis server at each deletion. In times when latency is important, and the number of keys, this can make a big difference. What if we could delete multiple keys?
Optimized Solution: Using Regex Patterns for Bulk Deletion
The first necessary change is to use an IConnectionMultiplexer, as we will need to run scripts directly on the redis instance. Afterwards, execute a Lua script, which will be the following:
for i, name in ipairs(
redis.call
('KEYS', @prefix)) do
redis.call
('DEL', name); end
Implementing the Solution: Leveraging IConnectionMultiplexer and Lua Scripts
Going back to the code, we would end up with something like this:
public class CacheManager
{
private readonly IConnectionMultiplexer _multiplexer;
public CacheManager(IConnectionMultiplexer multiplexer)
{
_multiplexer = multiplexer;
}
public async Task RemoveKeys(string prefix)
{
var prepared = LuaScript.Prepare("for i, name in ipairs(redis.call('KEYS', @prefix)) do redis.call('DEL', name); end");
await _multiplexer.GetDatabase().ScriptEvaluateAsync(prepared, new { prefix = prefix });
}
}
// Then, we use it like this:
...
await manager.RemoveKeys("key-*");
Conclusion: Enhancing Performance with Efficient Key Management
In conclusion, efficiently deleting multiple Redis keys by pattern in a .NET application can significantly reduce latency and improve performance. By leveraging the IConnectionMultiplexer and executing a Lua script directly on the Redis instance, you can streamline the deletion process and avoid the overhead of multiple round-trips to the server. This approach not only optimizes your application's interaction with Redis but also ensures that your key management is both effective and scalable. For further details and examples, refer to the provided links on scripting with StackExchange.Redis and relevant StackOverflow discussions.