Recipe 3.2 · C#
Expiration and Size Limits
Problem
An in-memory cache with no limits is a memory leak with a nicer name. A cache of product details keyed by product ID grows with every product anyone views, and on a catalog of two million products the web server eventually spends more time in garbage collection than serving pages. Meanwhile items that nobody has asked for in days stay in memory.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: unbounded and never evicted.
public ProductDetails GetProduct(int id)
{
string key = "Product_" + id;
var cached = HttpRuntime.Cache[key] as ProductDetails;
if (cached != null) return cached;
cached = ProductData.Load(id);
HttpRuntime.Cache.Insert(key, cached, null,
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
return cached;
}
The improved recipe
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
namespace ImproveCode.Caching;
public sealed record ProductDetails(
int ProductId, string Name, decimal ListPrice);
public interface IProductRepository
{
Task<ProductDetails?> FindAsync(int productId, CancellationToken ct);
}
public sealed class ProductDetailsCache : IDisposable
{
private static readonly TimeSpan Sliding = TimeSpan.FromMinutes(10);
private static readonly TimeSpan Absolute = TimeSpan.FromHours(1);
private static readonly TimeSpan NotFound = TimeSpan.FromMinutes(1);
private readonly MemoryCache _cache = new(new MemoryCacheOptions
{
SizeLimit = 5_000,
CompactionPercentage = 0.20,
TrackStatistics = true
});
private readonly IProductRepository _repository;
public ProductDetailsCache(IProductRepository repository) =>
_repository = repository;
public Task<ProductDetails?> GetAsync(
int productId, CancellationToken ct = default) =>
_cache.GetOrCreateAsync(productId, async entry =>
{
entry.Size = 1;
ProductDetails? product =
await _repository.FindAsync(productId, ct);
if (product is null)
{
entry.AbsoluteExpirationRelativeToNow = NotFound;
}
else
{
entry.SlidingExpiration = Sliding;
entry.AbsoluteExpirationRelativeToNow = Absolute;
}
return product;
});
public long CurrentEntryCount =>
_cache.GetCurrentStatistics()?.CurrentEntryCount ?? 0;
public void Dispose() => _cache.Dispose();
}
How it works
This class owns a private MemoryCache instance with a SizeLimit. The limit is in units that you define, not bytes. Here each entry has Size = 1, so the limit is simply "at most 5,000 products". When an insert would push the total over the limit, the cache refuses that insert and starts a background compaction that removes 20% of the entries, expired ones first and then the least recently used.
Each found product gets two expirations. The sliding expiration removes it after ten minutes without a read, so cold entries leave on their own. The absolute expiration removes it after one hour no matter how often it is read, so a popular product cannot keep a stale price forever. Use both together; a sliding expiration on its own can keep a hot entry alive indefinitely.
Products that do not exist are cached too, but only for a minute. That is negative caching. It stops a bot that requests random IDs from hitting the database for each one, without hiding a newly added product for long.
TrackStatistics (.NET 7 and later) enables GetCurrentStatistics(), which reports the entry count, hits, misses and estimated size. Expose those numbers on a health or diagnostics page; a cache whose hit rate you cannot see is a cache you cannot tune.
Variations and pitfalls
- Use a private instance for size limits. Once
SizeLimitis set, every entry must setSize, or the insert throws anInvalidOperationException. The sharedIMemoryCachefromAddMemoryCache()is used by other libraries that do not set sizes, so put size-limited caches in their ownMemoryCache, as this class does, and register the class as a singleton. - Size by weight when items vary. If some entries are a single record and others are a 5,000-row report, give them sizes that reflect it, such as an estimated kilobyte count.
- Expiration is lazy. An expired entry is removed when it is next accessed or during a periodic scan (
ExpirationScanFrequency, one minute by default). It is never returned after it expires, but it may hold memory a little longer. - Do not set tiny lifetimes to fix staleness. A 5-second cache on data that changes hourly is mostly misses. Fix staleness with invalidation (next recipe) and keep lifetimes realistic.