Caching in C#: Redis, Memcached, and Built-in Solutions — A Complete Guide
In modern web development, application performance is one of the key success factors. Caching allows you to significantly reduce the load on the database and speed up system response. In the C# (.NET) ecosystem, developers have three main approaches: built-in in-memory caching (IMemoryCache), distributed solutions (IDistributedCache), and external caching servers such as Redis and Memcached. In this article, we will cover each of them from theory to practical code examples.
1. Built-in Caching in .NET: IMemoryCache
Built-in caching is the simplest and fastest way to temporarily store data. In ASP.NET Core, it is implemented through the IMemoryCache interface. Data is stored in the RAM of a single process, ensuring minimal latency.
When to use:
- Data does not need to be synchronized across multiple servers.
- The volume of cached data is small.
- Maximum performance is required without configuring external services.
Implementation example:
using Microsoft.Extensions.Caching.Memory;
public class WeatherService{ private readonly IMemoryCache _cache;
public WeatherService(IMemoryCache cache) { _cache = cache; }
public async Task<WeatherData> GetWeatherAsync(string city) { string cacheKey = $"weather_{city}";
if (!_cache.TryGetValue(cacheKey, out WeatherData data)) { // Data not in cache — load from external source data = await FetchWeatherFromApi(city);
// Cache configuration: 5-minute lifetime var cacheOptions = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
_cache.Set(cacheKey, data, cacheOptions); }
return data; }
private async Task<WeatherData> FetchWeatherFromApi(string city) { // Simulate an external API call await Task.Delay(1000); return new WeatherData { City = city, Temperature = 22.5 }; }}
public class WeatherData{ public string City { get; set; } public double Temperature { get; set; }}Key methods: TryGetValue, Set, Remove. It is important to remember that IMemoryCache is not suitable for microservice architecture.
2. Distributed Caching: IDistributedCache and Its Providers
For applications running on multiple servers, distributed caching is necessary. In .NET, it is abstracted through the IDistributedCache interface. This allows you to easily change the provider (Redis, SQL Server, NCache) without modifying business logic.
Main methods:
GetAsync / SetAsync— for working with bytes.GetStringAsync / SetStringAsync— for string data.RefreshAsync— resetting the sliding expiration timer.RemoveAsync— deleting an entry.
Example with Redis:
// In Program.cs register the providerbuilder.Services.AddStackExchangeRedisCache(options =>{ options.Configuration = "localhost:6379"; options.InstanceName = "SampleApp";});
// Usage in a servicepublic class ProductService{ private readonly IDistributedCache _cache;
public ProductService(IDistributedCache cache) { _cache = cache; }
public async Task<Product> GetProductAsync(int id) { string cacheKey = $"product_{id}"; string cachedData = await _cache.GetStringAsync(cacheKey);
if