Redis is unavailable, multiple instances — how to ensure cache consistency?
sobes.tech AI
Answer from AI
When Redis is unavailable and there are multiple application instances, several approaches can be used to ensure cache consistency:
-
Fallback to local cache — if Redis is unavailable, instances can temporarily use a local cache (e.g., MemoryCache in C#). This reduces load but requires careful management of data lifetime.
-
Use of distributed cache with redundancy — set up a Redis cluster with replication and automatic master failover (Sentinel, Cluster mode) to minimize downtime.
-
Cache invalidation mechanism via messages — when data is updated, one instance publishes an event (e.g., via Redis Pub/Sub or another messaging system) so that other instances reset or update their local caches.
-
Optimistic locking and version control — store data versions in the cache to correctly synchronize state upon reconnection.
-
Use of Cache-Aside pattern — the application first tries to get data from the cache, and if absent or on error, queries the database and updates the cache.
Example of using MemoryCache with fallback:
private MemoryCache localCache = new MemoryCache(new MemoryCacheOptions());
public async Task<T> GetDataAsync<T>(string key, Func<Task<T>> fetchFromDb)
{
try
{
var cached = await redis.GetAsync<T>(key);
if (cached != null) return cached;
}
catch
{
// Redis is unavailable, use local cache
if (localCache.TryGetValue(key, out T localCached))
return localCached;
}
var data = await fetchFromDb();
try
{
await redis.SetAsync(key, data);
}
catch
{
localCache.Set(key, data, TimeSpan.FromMinutes(5));
}
return data;
}
Thus, by combining Redis fault tolerance and local cache, data consistency and availability can be ensured.