Design a caching strategy using Redis for a .NET product API, including invalidation and cache-stampede protection.
Freshworks · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Redis, System Design
Community answers
Posted by wasAsked editorial collection
Use cache-aside for read-heavy data: read Redis, load the authoritative store on a miss, then cache a serialized DTO with a finite TTL. Cache keys must include version and tenant scope.
Example:
var key = $"v2:{tenant.RestaurantId}:{tenant.OutletId}:product:{id}";
var cached = await cache.GetStringAsync(key, ct);
if (cached is null) {
var dto = await repository.GetAsync(id, tenant, ct);
await cache.SetStringAsync(key, JsonSerializer.Serialize(dto), options, ct);
}
Invalidate or update after a successful database commit. Add TTL jitter and request coalescing to reduce stampedes. Do not cache secrets or authorization decisions carelessly; plan for Redis failure, stale data, serialization changes, memory limits, and metrics for hit rate and latency.
Backbencher Developer · · 0 likes
Use cache-aside with Redis as a distributed cache in front of the database.
Read path:
1. Build a key from the request, e.g. product:{id} or products:list:{category}:{page}.
2. Try Redis. On a hit, return the cached value.
3. On a miss, load from the database, write it to Redis with a TTL, and return it.
In .NET, use IDistributedCache, the newer HybridCache (in-memory L1 plus Redis L2, with built-in stampede protection) or StackExchange.Redis directly. Serialize with System.Text.Json and keep values small.
Invalidation:
- On writes, delete or update the affected keys after the database commit (product:{id} and any list keys that contain it).
- For list caches that are hard to track, use versioned keys: store products:version and include it in list keys; incrementing it invalidates all lists at once.
- In multi-service systems, publish change events (outbox plus message bus or Redis pub/sub) so every service evicts its copies.
- Always set a TTL as a safety net so stale data eventually expires; add random jitter so keys do not expire at the same moment.
Cache-stampede protection (many requests miss at once and hammer the database):
- Single-flight: only one request rebuilds a key while others wait — a per-key SemaphoreSlim in process, or a short Redis lock (SET key value NX PX 5000) across instances.
- Stale-while-revalidate: keep serving the old value while one request refreshes it in the background.
- Early refresh: refresh popular keys shortly before they expire.
Other details:
- Decide what is safe to cache: never mix data between users or tenants — include the tenant or user in the key when data is personalised.
- Handle Redis outages gracefully: fall back to the database with timeouts and a circuit breaker.
- Cache negative results (not found) briefly to stop repeated lookups for missing IDs.
- Monitor hit ratio, memory use and evictions.