How to clear all keys Redis Cache keys in .Net Core

Redis is a great scalable and high performance key-value store. It is widely used as distributed cache store. I have used Redis as distributed cache for my Asp.Net web applications for a very long time. StackExchange.Redis is a great .Net Client library that makes it very easy to work with Redis server.

A typical implementation of a distributed caching mechanism implements following actions on a cache.

  • Set data in a key
  • Get data for a given key
  • Delete data for a particular key
  • Delete data based on key pattern

A lot of time we get faced with situations when we want to clear all the keys in cache. Some .Net implementations keep track of all the keys in its internal list. Later on when the application wants to clear all the cached data, it iterates over all the key and remove them one by one using standard Delete per key process. For most part this strategy works great. In my experience I have come across cases where either in-memory keys have become out of sync or I just want to dump all the cached data in one shot. If you are Redis server admin, you can accomplish this by running Redis CLI commands. Other option will be for you to use some Redis Management application and then perform server management tasks to clear all the keys.

If you are looking into integrating ClearCache kind of concept in your application workflow, then you will need to write some additional code. Following code snippets shows how to use StackExchange.Redis .Net Client library to clear all keys.

public async Task<IList<string>> ClearAsync(int database = 0)
            var flushedKeys = new List<string>();
            var options = ConfigurationOptions.Parse(_keyValueStorageConfig.ConnectionString);
            options.AllowAdmin = true;
            var connection = await ConnectionMultiplexer.ConnectAsync(options);
            using (connection)
                foreach (var endPoint in connection.GetEndPoints())
                    var server = connection.GetServer(endPoint);
                    var keys = server.Keys(database);
                    flushedKeys.AddRange(keys.Select(key => key.ToString()));
                    await server.FlushDatabaseAsync(database);

            return flushedKeys;

This code performs following actions.

  • Parses connection string to create ConfigurationOptions object

  • A very important part of this process is setting AllowAdmin property. By default the process will not allow you to execute FlushDatabase command. It won't to ensure that you know what you are doing and only right person with right authorization executes this critical step. If you do not set AllowAdmin value, you will receive the following error.

    This operation is not available unless admin mode is enabled: FLUSHDB
  • Next you will iterate through all end points. This step will be required if your configuration has multiple endpoints for Redis server.

  • Execute FLUSHDB command against the server number. My sample implementation iterates over all the keys to create a report. It is not required to iterate over the keys if only thing that you want to do is just flush all the keys. You can eliminate that part of the implementation if you don't need information about the keys.

Some words of caution against performing this full flush of Redis keys. When Redis is installed in a clustered configuration, then your logical database may be spread over multiple nodes and end points. Most of Redis commands work against single server. FLUSHDB happens to be one of those commands as well. Therefore, in clustered deployment it could be a tricky and anti-pattern implementation to perform FLUSHDB. The above implementation for clearing cache should work fine but use it with caution.




15.6 °C / 60.1 °F

weather conditions Clouds

Monthly Posts

Blog Tags