
Previous article: ASP.NET Core Performance Hacks: Async, Profiling & Optimization Techniques (Part - 26 of 40)
Table of Contents
The Caching Revolution
Caching Fundamentals & Architecture
In-Memory Caching Deep Dive
Distributed Caching with Redis
Response Caching Strategies
Real-World E-Commerce Caching
Cache Invalidation Patterns
Performance Monitoring & Analytics
Advanced Caching Patterns
Security & Best Practices
Testing Caching Strategies
Production Deployment
1. The Caching Revolution
Why Caching is Your Performance Silver Bullet
Caching transforms application performance by reducing database load, decreasing response times, and improving scalability. In modern web applications, caching isn't just an optimization—it's a necessity.
Real-Life Analogy: Imagine a busy coffee shop. Without caching, every customer order would require:
Going to the supplier warehouse (database)
Selecting beans (query execution)
Grinding fresh (data processing)
Brewing individually (response generation)
With caching, popular drinks are pre-prepared and ready to serve instantly!
// Performance impact demonstrationpublic class ProductServiceWithoutCaching{
private readonly ApplicationDbContext _context;
public async Task<Product> GetProductAsync(int id)
{
// Every call hits the database - SLOW!
return await _context.Products
.Include(p => p.Category)
.Include(p => p.Reviews)
.FirstOrDefaultAsync(p => p.Id == id);
}}
public class ProductServiceWithCaching{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _cache;
public async Task<Product> GetProductAsync(int id)
{
// Try cache first - FAST!
if (_cache.TryGetValue($"product_{id}", out Product product))
return product;
// Cache miss - get from database
product = await _context.Products
.Include(p => p.Category)
.Include(p => p.Reviews)
.FirstOrDefaultAsync(p => p.Id == id);
// Store in cache for future requests
_cache.Set($"product_{id}", product, TimeSpan.FromMinutes(30));
return product;
}}
The Caching Performance Impact
| Scenario | Without Caching | With Caching | Improvement |
|---|---|---|---|
| Database Queries | 1000 queries/sec | 50 queries/sec | 20x reduction |
| Response Time | 200ms | 5ms | 40x faster |
| Server Load | 80% CPU | 20% CPU | 4x reduction |
| Cost | $1000/month | $250/month | 75% savings |
2. Caching Fundamentals & Architecture
Caching Architecture Patterns
// Comprehensive caching service interfacepublic interface ICacheService{
Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiration = null);
Task<T> GetAsync<T>(string key);
Task SetAsync<T>(string key, T value, TimeSpan? expiration = null);
Task RemoveAsync(string key);
Task<bool> ExistsAsync(string key);
Task RemoveByPatternAsync(string pattern);}
// Implementation supporting multiple cache providerspublic class CacheService : ICacheService{
private readonly IMemoryCache _memoryCache;
private readonly IDistributedCache _distributedCache;
private readonly ILogger<CacheService> _logger;
private readonly CacheSettings _settings;
public CacheService(IMemoryCache memoryCache, IDistributedCache distributedCache,
ILogger<CacheService> logger, IOptions<CacheSettings> settings)
{
_memoryCache = memoryCache;
_distributedCache = distributedCache;
_logger = logger;
_settings = settings.Value;
}
public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiration = null)
{
try
{
// Try memory cache first (fastest)
if (_memoryCache.TryGetValue(key, out T cachedValue))
{
_logger.LogDebug("Memory cache hit for key: {Key}", key);
return cachedValue;
}
// Try distributed cache
var distributedValue = await _distributedCache.GetAsync<T>(key);
if (distributedValue != null)
{
_logger.LogDebug("Distributed cache hit for key: {Key}", key);
// Populate memory cache for faster subsequent access
var memoryCacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiration ?? _settings.DefaultExpiration
};
_memoryCache.Set(key, distributedValue, memoryCacheOptions);
return distributedValue;
}
// Cache miss - execute factory method
_logger.LogDebug("Cache miss for key: {Key}, executing factory", key);
var value = await factory();
if (value != null)
{
// Store in both caches
var cacheExpiration = expiration ?? _settings.DefaultExpiration;
// Memory cache
var memoryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = cacheExpiration
};
_memoryCache.Set(key, value, memoryOptions);
// Distributed cache
var distributedOptions = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = cacheExpiration
};
await _distributedCache.SetAsync(key, value, distributedOptions);
}
return value;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in GetOrCreateAsync for key: {Key}", key);
// If caching fails, fall back to factory method
return await factory();
}
}
public async Task<T> GetAsync<T>(string key)
{
// Implementation similar to above without factory fallback
if (_memoryCache.TryGetValue(key, out T memoryValue))
return memoryValue;
var distributedValue = await _distributedCache.GetAsync<T>(key);
if (distributedValue != null)
{
// Populate memory cache
_memoryCache.Set(key, distributedValue,
TimeSpan.FromMinutes(_settings.MemoryCacheExpirationMinutes));
return distributedValue;
}
return default(T);
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiration = null)
{
var cacheExpiration = expiration ?? _settings.DefaultExpiration;
// Memory cache
_memoryCache.Set(key, value, cacheExpiration);
// Distributed cache
await _distributedCache.SetAsync(key, value,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = cacheExpiration
});
}
public async Task RemoveAsync(string key)
{
_memoryCache.Remove(key);
await _distributedCache.RemoveAsync(key);
_logger.LogInformation("Cache removed for key: {Key}", key);
}
public async Task<bool> ExistsAsync(string key)
{
return _memoryCache.TryGetValue(key, out _) ||
await _distributedCache.GetAsync(key) != null;
}
// Pattern-based removal for cache invalidation
public async Task RemoveByPatternAsync(string pattern)
{
// This is a simplified version - actual implementation depends on cache provider
_logger.LogInformation("Removing cache entries matching pattern: {Pattern}", pattern);
// In real implementation, you'd use Redis keys command or similar
// This is a conceptual implementation
}}
// Configuration modelpublic class CacheSettings{
public TimeSpan DefaultExpiration { get; set; } = TimeSpan.FromMinutes(30);
public int MemoryCacheExpirationMinutes { get; set; } = 10;
public string RedisConnectionString { get; set; }
public bool UseDistributedCache { get; set; } = true;}
Cache Configuration in Program.cs
// Program.cs - Comprehensive caching setupvar builder = WebApplication.CreateBuilder(args);
// Configure cache settings
builder.Services.Configure<CacheSettings>(builder.Configuration.GetSection("CacheSettings"));
// Add memory cache (always available)
builder.Services.AddMemoryCache(options =>{
options.SizeLimit = 1024 * 1024 * 100; // 100MB limit
options.CompactionPercentage = 0.25; // Compact when 25% full});
// Add distributed cache based on configurationvar cacheSettings = builder.Configuration.GetSection("CacheSettings").Get<CacheSettings>();if (cacheSettings.UseDistributedCache && !string.IsNullOrEmpty(cacheSettings.RedisConnectionString)){
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = cacheSettings.RedisConnectionString;
options.InstanceName = "MyApp:";
});
// Register Redis connection for direct access
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
ConnectionMultiplexer.Connect(cacheSettings.RedisConnectionString));}else{
// Fallback to distributed memory cache (for development)
builder.Services.AddDistributedMemoryCache();}
// Register caching services
builder.Services.AddScoped<ICacheService, CacheService>();
builder.Services.AddScoped<IProductCacheService, ProductCacheService>();
builder.Services.AddScoped<IUserCacheService, UserCacheService>();
// Add response caching
builder.Services.AddResponseCaching(options =>{
options.MaximumBodySize = 1024 * 1024; // 1MB
options.UseCaseSensitivePaths = false;});
// Add output caching (ASP.NET Core 7+)
builder.Services.AddOutputCache(options =>{
options.AddBasePolicy(builder =>
builder.Expire(TimeSpan.FromMinutes(10)));
options.AddPolicy("Products", builder =>
builder.Expire(TimeSpan.FromMinutes(5))
.Tag("products"));});
var app = builder.Build();
// Use response caching middleware
app.UseResponseCaching();
// Use output caching middleware
app.UseOutputCache();
app.Run();
3. In-Memory Caching Deep Dive
Advanced Memory Cache Patterns
// Smart memory cache service with eviction policiespublic class SmartMemoryCacheService{
private readonly IMemoryCache _cache;
private readonly ILogger<SmartMemoryCacheService> _logger;
private readonly ConcurrentDictionary<string, CacheEntryInfo> _cacheEntries;
public SmartMemoryCacheService(IMemoryCache cache, ILogger<SmartMemoryCacheService> logger)
{
_cache = cache;
_logger = logger;
_cacheEntries = new ConcurrentDictionary<string, CacheEntryInfo>();
}
public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> factory,
CacheOptions options = null)
{
options ??= new CacheOptions();
if (_cache.TryGetValue(key, out T cachedValue))
{
// Update access statistics
UpdateAccessStats(key);
_logger.LogDebug("Cache hit for {Key}", key);
return cachedValue;
}
// Cache miss - use factory method
_logger.LogDebug("Cache miss for {Key}, executing factory", key);
// Implement cache stampede protection
var semaphore = new SemaphoreSlim(1, 1);
await semaphore.WaitAsync();
try
{
// Double-check after acquiring lock
if (_cache.TryGetValue(key, out cachedValue))
{
UpdateAccessStats(key);
return cachedValue;
}
var value = await factory();
if (value != null)
{
var cacheEntryOptions = CreateCacheEntryOptions(options);
// Register callback for eviction
cacheEntryOptions.RegisterPostEvictionCallback(EvictionCallback);
_cache.Set(key, value, cacheEntryOptions);
// Track cache entry
_cacheEntries[key] = new CacheEntryInfo
{
Key = key,
Created = DateTime.UtcNow,
LastAccessed = DateTime.UtcNow,
AccessCount = 1,
Size = EstimateSize(value),
Options = options
};
}
return value;
}
finally
{
semaphore.Release();
}
}
public CacheStatistics GetStatistics()
{
var entries = _cacheEntries.Values.ToList();
return new CacheStatistics
{
TotalEntries = entries.Count,
TotalSize = entries.Sum(e => e.Size),
HitRate = CalculateHitRate(),
MostAccessed = entries.OrderByDescending(e => e.AccessCount).Take(10),
OldestEntries = entries.OrderBy(e => e.LastAccessed).Take(10)
};
}
public void Cleanup()
{
var now = DateTime.UtcNow;
var toRemove = new List<string>();
foreach (var entry in _cacheEntries)
{
var age = now - entry.Value.LastAccessed;
if (age > entry.Value.Options.MaxIdleTime)
{
toRemove.Add(entry.Key);
}
}
foreach (var key in toRemove)
{
_cache.Remove(key);
_cacheEntries.TryRemove(key, out _);
_logger.LogInformation("Removed idle cache entry: {Key}", key);
}
}
private void UpdateAccessStats(string key)
{
if (_cacheEntries.TryGetValue(key, out var info))
{
info.LastAccessed = DateTime.UtcNow;
info.AccessCount++;
}
}
private void EvictionCallback(object key, object value, EvictionReason reason, object state)
{
_logger.LogInformation("Cache entry evicted: {Key}, Reason: {Reason}", key, reason);
_cacheEntries.TryRemove(key.ToString(), out _);
}
private MemoryCacheEntryOptions CreateCacheEntryOptions(CacheOptions options)
{
var cacheOptions = new MemoryCacheEntryOptions
{
Size = options.Size
};
if (options.AbsoluteExpiration.HasValue)
cacheOptions.SetAbsoluteExpiration(options.AbsoluteExpiration.Value);
if (options.SlidingExpiration.HasValue)
cacheOptions.SetSlidingExpiration(options.SlidingExpiration.Value);
if (options.Priority.HasValue)
cacheOptions.SetPriority(options.Priority.Value);
return cacheOptions;
}
private long EstimateSize<T>(T value)
{
// Simple size estimation - in production, use more accurate methods
if (value == null) return 0;
try
{
using var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, value);
return stream.Length;
}
catch
{
return 1024; // Default 1KB estimate
}
}
private double CalculateHitRate()
{
var entries = _cacheEntries.Values.ToList();
if (entries.Count == 0) return 0;
var totalAccesses = entries.Sum(e => e.AccessCount);
var hits = entries.Sum(e => e.AccessCount - 1); // First access is always miss
return totalAccesses > 0 ? (double)hits / totalAccesses : 0;
}}
// Supporting classespublic class CacheOptions{
public TimeSpan? AbsoluteExpiration { get; set; }
public TimeSpan? SlidingExpiration { get; set; }
public TimeSpan MaxIdleTime { get; set; } = TimeSpan.FromHours(24);
public long Size { get; set; } = 1;
public CacheItemPriority? Priority { get; set; }}
public class CacheEntryInfo{
public string Key { get; set; }
public DateTime Created { get; set; }
public DateTime LastAccessed { get; set; }
public long AccessCount { get; set; }
public long Size { get; set; }
public CacheOptions Options { get; set; }}
public class CacheStatistics{
public int TotalEntries { get; set; }
public long TotalSize { get; set; }
public double HitRate { get; set; }
public IEnumerable<CacheEntryInfo> MostAccessed { get; set; }
public IEnumerable<CacheEntryInfo> OldestEntries { get; set; }}
Real-World Memory Cache Implementation
// E-commerce product catalog with intelligent cachingpublic class ProductCatalogService{
private readonly IProductRepository _productRepository;
private readonly SmartMemoryCacheService _cache;
private readonly ILogger<ProductCatalogService> _logger;
private const string ProductsByCategoryKey = "products_category_{0}";
private const string FeaturedProductsKey = "products_featured";
private const string ProductDetailsKey = "product_{0}";
private const string ProductSearchKey = "products_search_{0}";
public ProductCatalogService(IProductRepository productRepository,
SmartMemoryCacheService cache,
ILogger<ProductCatalogService> logger)
{
_productRepository = productRepository;
_cache = cache;
_logger = logger;
}
public async Task<List<Product>> GetProductsByCategoryAsync(int categoryId, int page = 1, int pageSize = 20)
{
var cacheKey = string.Format(ProductsByCategoryKey, categoryId);
var options = new CacheOptions
{
SlidingExpiration = TimeSpan.FromMinutes(15),
AbsoluteExpiration = DateTimeOffset.Now.AddHours(1)
};
return await _cache.GetOrCreateAsync(cacheKey, async () =>
{
_logger.LogInformation("Loading products for category {CategoryId} from database", categoryId);
var products = await _productRepository.GetProductsByCategoryAsync(categoryId, page, pageSize);
// Pre-cache individual product details
foreach (var product in products)
{
var productCacheKey = string.Format(ProductDetailsKey, product.Id);
await _cache.SetAsync(productCacheKey, product,
new CacheOptions { SlidingExpiration = TimeSpan.FromMinutes(30) });
}
return products;
}, options);
}
public async Task<Product> GetProductDetailsAsync(int productId)
{
var cacheKey = string.Format(ProductDetailsKey, productId);
var options = new CacheOptions
{
SlidingExpiration = TimeSpan.FromMinutes(30),
AbsoluteExpiration = DateTimeOffset.Now.AddHours(2)
};
return await _cache.GetOrCreateAsync(cacheKey, async () =>
{
_logger.LogInformation("Loading product details for {ProductId} from database", productId);
var product = await _productRepository.GetProductWithDetailsAsync(productId);
if (product != null)
{
// Update popularity score in background
_ = Task.Run(async () =>
{
await _productRepository.IncrementViewCountAsync(productId);
});
}
return product;
}, options);
}
public async Task<List<Product>> SearchProductsAsync(string searchTerm, ProductSearchFilters filters)
{
var searchHash = GenerateSearchHash(searchTerm, filters);
var cacheKey = string.Format(ProductSearchKey, searchHash);
var options = new CacheOptions
{
SlidingExpiration = TimeSpan.FromMinutes(10),
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30)
};
return await _cache.GetOrCreateAsync(cacheKey, async () =>
{
_logger.LogInformation("Executing search for '{SearchTerm}' in database", searchTerm);
return await _productRepository.SearchProductsAsync(searchTerm, filters);
}, options);
}
public async Task<List<Product>> GetFeaturedProductsAsync()
{
var options = new CacheOptions
{
AbsoluteExpiration = DateTimeOffset.Now.AddHours(4) // Refresh every 4 hours
};
return await _cache.GetOrCreateAsync(FeaturedProductsKey, async () =>
{
_logger.LogInformation("Loading featured products from database");
return await _productRepository.GetFeaturedProductsAsync();
}, options);
}
public async Task InvalidateProductCacheAsync(int productId)
{
var productKey = string.Format(ProductDetailsKey, productId);
await _cache.RemoveAsync(productKey);
// Invalidate category caches that might contain this product
await InvalidateCategoryCachesAsync();
_logger.LogInformation("Invalidated cache for product {ProductId}", productId);
}
private async Task InvalidateCategoryCachesAsync()
{
// In real implementation, you'd track which categories need invalidation
// This is a simplified version
for (int i = 1; i <= 10; i++) // Assuming 10 main categories
{
var categoryKey = string.Format(ProductsByCategoryKey, i);
await _cache.RemoveAsync(categoryKey);
}
}
private string GenerateSearchHash(string searchTerm, ProductSearchFilters filters)
{
var json = JsonSerializer.Serialize(new { searchTerm, filters });
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(json));
return Convert.ToBase64String(hash);
}}

Join the conversation! Your thoughts help the community grow.