The Cache-Aside pattern (also known as lazy loading) ensures application code reads data from cache first. If a cache miss occurs, data is retrieved from the primary database and written back into Redis for future requests.
C# .NET Implementation Example
Here is an example implementing this caching strategy using the official StackExchange.Redis library in .NET.
using StackExchange.Redis;
using System.Text.Json;
public class CacheService
{
private readonly IDatabase _db;
public CacheService(IConnectionMultiplexer redis)
{
// Retrieve database instance from multiplexer
_db = redis.GetDatabase();
}
public async Task GetUserAsync(int userId)
{
string key = $"user:{userId}";
// Attempt fetching item string from Redis cache
string cachedValue = await _db.StringGetAsync(key);
if (!string.IsNullOrEmpty(cachedValue))
{
// Deserialize cached JSON back to target object
return JsonSerializer.Deserialize(cachedValue);
}
// Fallback to database query on cache miss
UserDto dbUser = await FetchUserFromDbAsync(userId);
if (dbUser != null)
{
// Store result into Redis with 30-minute expiration
string json = JsonSerializer.Serialize(dbUser);
await _db.StringSetAsync(key, json, TimeSpan.FromMinutes(30));
}
return dbUser;
}
private async Task FetchUserFromDbAsync(int id)
{
// Simulated database call
return await Task.FromResult(new UserDto { Id = id, Name = "John Doe" });
}
}
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; }
}