Cloud & ArchitectureComplete guide

Redis & Distributed Caching

Redis is an in-memory data structure store used in .NET applications for distributed caching, session storage, pub/sub messaging, rate limiting, and distributed coordination.

Overview

A process-local cache is fastest but each application instance holds different state and loses it on restart. A Redis-backed distributed cache gives nodes a shared L2 store, while .NET HybridCache can add a local L1, serialization, and same-process stampede protection behind one API. Cache-aside reads the cache, loads the authoritative source on a miss, and stores a bounded value with explicit expiration; writes must choose invalidate, update, versioned keys, or event-driven invalidation according to the accepted consistency window. Production design defines ownership, key namespace and tenant scope, TTL and jitter, negative caching, payload limits, hot-key behavior, eviction policy, memory headroom, connection reuse, failure fallback, observability, encryption, authentication, network isolation, and regional topology. Cache data is disposable acceleration rather than the only system of record. Redis pub/sub is not durable messaging, distributed locking has lease and fencing hazards, and sharing one instance across cache, sessions, rate limits, backplanes, and coordination couples failure and eviction blast radius. Managed Redis products, clustering, replicas, and persistence still require workload-specific recovery and capacity tests.

What you will learn

  • Choose process, distributed, and hybrid cache layers from topology and consistency needs.
  • Implement cache-aside with bounded values, versioned tenant-aware keys, expiration, and invalidation.
  • Prevent stampedes and hot-key overload while preserving source-of-truth fallback.
  • Configure Redis connections, memory, eviction, security, high availability, and observability.
  • Distinguish caching, output caching, sessions, pub/sub, streams, counters, and locks.
  • Test hit, miss, concurrency, invalidation, staleness, outage, and multi-instance behavior.

Prerequisites

  • ASP.NET Core dependency injection, JSON serialization, async data access, and distributed systems basics.
  • Expiration, consistency, replication, memory limits, and network security concepts.
  • A .NET 10 SDK; Redis is optional for Development but required for a production-shaped run.

When to use Redis & Distributed Caching

Good fit

  • Use HybridCache when L1 plus distributed L2 and same-process stampede protection fit the workload.
  • Use Redis for shared low-latency disposable data across multiple instances.
  • Use output caching for safe repeatable HTTP responses with explicit vary and invalidation policy.

Choose another approach when

  • Do not cache low-reuse, unbounded, sensitive, or correctness-critical data without a precise policy.
  • Do not make Redis the only durable record for business state.
  • Do not use pub/sub where offline consumers, replay, acknowledgement, or dead-lettering is required.
  • Do not treat a time-limited distributed lock as proof that stale holders cannot write; use fencing or a stronger consistency design.

Key concepts

Cache-aside pattern

The application checks the cache first; on a miss it reads from the source of truth, populates the cache with a TTL, and returns the value. Eviction and expiry keep the cache from growing unbounded.

IDistributedCache and output caching

IDistributedCache is the ASP.NET Core abstraction for distributed string or byte caches. Output caching middleware caches full HTTP responses at the framework level with Redis as the backing store.

Pub/sub and streams

Redis pub/sub broadcasts messages to all subscribers on a channel, powering SignalR backplanes and lightweight event fan-out. Redis Streams provide a durable, consumer-group-aware alternative.

Distributed locks and rate limiting

The Redlock algorithm uses atomic SET NX EX commands to acquire time-bounded locks across processes. Sliding window and token bucket counters built on INCR and EXPIRE enable per-key rate limiting without a dedicated service.

Hybrid L1 and L2

HybridCache combines fast per-process memory with an optional shared distributed cache and coalesces concurrent misses in one process.

Invalidation and versioning

Remove, update, tag, event, and versioned-key strategies trade write complexity, stale windows, and multi-node coherence.

Memory and eviction

Maximum memory, eviction policy, payload size, TTL distribution, hot keys, and headroom determine behavior under pressure.

Failure semantics

Timeouts, circuit behavior, stale serving, source fallback, and recovery load define whether cache outage becomes application outage.

Architecture

Application instances share one Redis cluster; cache hits return data without touching the database, while pub/sub channels and lock keys coordinate distributed behaviour across all nodes.

App instances
Azure Cache for Redis
Pub/sub channels
Primary database

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated product API configures Redis as HybridCache L2 when a connection string exists and a clearly labeled process-local provider only in Development or Testing. It applies bounded payloads, versioned keys, expiration, same-process miss coalescing, explicit invalidation after writes, and tests source-read counts to prove behavior.

  1. 01
    Define the cache contract

    Record source of truth, consumers, consistency window, miss behavior, outage behavior, and ownership.

  2. 02
    Design keys and values

    Namespace by environment, domain, version, tenant, and stable identifier and bound serialized payload size.

  3. 03
    Configure the provider

    Reuse Redis connections, protect credentials, set instance namespace, topology, timeouts, and network access.

  4. 04
    Implement cache-aside

    Use HybridCache GetOrCreateAsync with cancellation and a source loader that remains correct on misses.

  5. 05
    Control freshness

    Set L1 and L2 expiration, jitter or refresh policy, negative caching, and explicit write invalidation.

  6. 06
    Test failure and concurrency

    Prove hit, miss, stampede, invalidation, stale window, corrupt value, timeout, outage, and recovery behavior.

  7. 07
    Operate capacity

    Monitor hit ratio, latency, errors, connections, memory, eviction, hot keys, source fallback, and recovery load.

Code example

A typed cache service wraps IDistributedCache with JSON serialisation, a configurable TTL, and safe cache-aside logic — the database is only called on a miss.

ProductCache.cs
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

public sealed class ProductCache(
    IDistributedCache cache,
    IProductRepository repository)
{
    private static readonly DistributedCacheEntryOptions DefaultOptions = new()
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
        SlidingExpiration = TimeSpan.FromMinutes(2)
    };

    public async Task<ProductDto?> GetAsync(
        Guid productId, CancellationToken ct)
    {
        var key = $"product:{productId}";

        var cached = await cache.GetStringAsync(key, ct);
        if (cached is not null)
            return JsonSerializer.Deserialize<ProductDto>(cached);

        var product = await repository.FindAsync(productId, ct);
        if (product is null) return null;

        await cache.SetStringAsync(
            key,
            JsonSerializer.Serialize(product),
            DefaultOptions,
            ct);

        return product;
    }

    public Task InvalidateAsync(Guid productId, CancellationToken ct) =>
        cache.RemoveAsync($"product:{productId}", ct);
}

// Registration
builder.Services.AddStackExchangeRedisCache(options =>
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis"));

builder.Services.AddScoped<ProductCache>();

Testing strategy

Caching tests assert source-of-truth calls and concurrency, not merely returned values.

  • Count source reads to prove a second request is a cache hit.
  • Issue concurrent same-key misses and prove they are coalesced as designed.
  • Mutate the source and prove invalidation or versioning returns the new value.
  • Test missing, negative-cached, oversized, corrupt, and serialization-incompatible values.
  • Inject Redis timeout or outage and verify the documented fallback and recovery-load behavior.
  • Run multiple app instances against Redis to verify shared L2 and cross-node invalidation assumptions.

Security considerations

Redis contains application data and coordination state and must be treated as a protected network data service.

  • Use private networking, TLS, supported identity or rotated credentials, and least-privilege administration.
  • Tenant-scope keys and never allow caller-controlled raw cache keys.
  • Avoid caching secrets, authorization decisions, or sensitive personal data unless encryption, lifetime, and revocation are designed.
  • Bound key, payload, decompression, deserialization, and command work to prevent resource abuse.
  • Redact values and credentials from logs, traces, diagnostics, and benchmark artifacts.

Performance and scalability

A cache helps only when reuse and saved source work exceed network, serialization, memory, and invalidation cost.

  • Measure hit ratio, miss penalty, Redis latency, serialization, payload bytes, and source load by cache family.
  • Reuse multiplexer or framework-managed connections and avoid synchronous network calls.
  • Use L1 for very hot safe data and account for cross-node invalidation lag.
  • Distribute TTLs and prewarm selectively to avoid synchronized expiry and recovery stampedes.
  • Find hot keys, large values, memory fragmentation, evictions, connection saturation, and slow commands before scaling.

Deployment and operations

Cache topology and application rollout determine compatibility and recovery behavior.

  • Provision managed Redis or equivalent with private access, TLS, identity, capacity, replicas, maintenance, and recovery policy.
  • Use versioned keys when old and new application versions serialize differently.
  • Deploy source-compatible readers before changing writers and avoid fleet-wide cold starts.
  • Verify memory and eviction policy do not mix workloads with incompatible durability needs.
  • Smoke-test hit, miss, invalidation, outage fallback, failover, and restart through the deployed route.

Common problems and fixes

Hit ratio is low.

Likely cause: Keys vary unexpectedly, TTL is too short, reuse is low, values are evicted, or invalidation is excessive.

Fix: Inspect normalized key families, TTL distribution, evictions, access frequency, and invalidation events.

Database load spikes when entries expire.

Likely cause: Many callers or keys rebuild simultaneously.

Fix: Use miss coalescing, TTL jitter, bounded refresh, stale-while-revalidate where safe, and source admission control.

Users receive another tenant's data.

Likely cause: Tenant scope is missing from a key or caller input controls the namespace.

Fix: Build typed server-side tenant-aware keys and add colliding-ID isolation tests.

Redis outage takes down the API.

Likely cause: Cache calls have long waits or no documented source fallback and circuit behavior.

Fix: Set bounded timeouts, degrade deliberately, protect the source, and test recovery.

Memory is full despite TTLs.

Likely cause: Values are large, TTLs are long, traffic exceeds capacity, fragmentation grows, or eviction policy is wrong.

Fix: Inspect memory by key family, payload limits, expiration, eviction, fragmentation, and headroom.

New deployment cannot deserialize old entries.

Likely cause: The value contract changed under the same key version.

Fix: Use versioned keys or backward-compatible serialization and allow old entries to expire.

Best practices

  • Cache only measured high-reuse data with a documented source of truth and stale window.
  • Use versioned collision-safe environment, domain, tenant, and identifier key namespaces.
  • Set bounded L1 and L2 expiration, payload size, negative caching, and serialization policy.
  • Use HybridCache or another proven coalescing strategy to protect the source from stampedes.
  • Invalidate or version entries deliberately when authoritative data changes.
  • Reuse Redis connections and design bounded timeout, outage fallback, and recovery load.
  • Separate cache, durable messaging, locks, sessions, and counters when failure requirements differ.
  • Monitor hit ratio, latency, errors, memory, eviction, hot keys, connections, and source fallback.

Production checklist

  • Source of truth, consistency window, ownership, miss, outage, and recovery behavior are documented.
  • Keys include environment, domain, version, tenant, and stable identifier and cannot collide.
  • Payload, key, TTL, negative cache, L1, L2, invalidation, and serialization policies are bounded.
  • Connections are reused and Redis uses private networking, TLS, identity or rotated credentials.
  • Stampede, hot key, eviction, memory pressure, failover, outage, and cold-start behavior are tested.
  • Cache data is disposable and no business record depends only on Redis.
  • Pub/sub, locks, sessions, counters, and cache workloads have compatible failure and eviction requirements or are separated.
  • Hit ratio, latency, errors, memory, evictions, connections, hot keys, and source fallback have dashboards and alerts.

Common interview questions

What is the cache stampede problem and how do you prevent it?

A stampede happens when many requests simultaneously find a cache miss for the same key and all race to load from the database at once, multiplying load. Prevention strategies include probabilistic early expiry, a short-lived Redis lock so only one request rebuilds the entry while others wait or serve the slightly stale value, or background refresh before expiry.

When should you use Redis pub/sub versus Service Bus or Event Grid?

Redis pub/sub is fire-and-forget with no durability — if a subscriber is offline it misses messages. It suits low-latency fan-out within a trusted environment, such as a SignalR backplane or cache invalidation broadcast. Service Bus and Event Grid provide delivery guarantees, dead-lettering, and durable storage, which are essential for business-critical events.

What is the difference between IDistributedCache and IMemoryCache in ASP.NET Core?

IMemoryCache is in-process, fast, and invisible to other application instances — suitable for single-server or read-heavy non-critical data. IDistributedCache abstracts a shared external store such as Redis, so all instances behind a load balancer share the same data and eviction, at the cost of network latency per cache operation.

What does HybridCache add?

It provides a unified L1 and optional distributed L2 API, serialization, and same-process stampede protection around GetOrCreateAsync.

Why use versioned cache keys?

They prevent new application versions from interpreting incompatible old value shapes and allow safe coexistence during rollout.

Why is Redis pub/sub not a durable event bus?

Messages are delivered only to current subscribers and have no built-in replay, acknowledgement, or dead-lettering.

What should happen when Redis is unavailable?

Follow an explicit bounded policy: fail closed for security state, or bypass and protect the source for disposable cache data, while avoiding a recovery stampede.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Redis Hybrid Products

A .NET 10 API demonstrating HybridCache L1/L2 behavior, Redis integration, stampede protection, bounded versioned keys, explicit invalidation, local development fallback, and source-count integration tests.

ASP.NET Core 10HybridCacheRedisxUnit
dedicated-samplecache-asidestampede-protectioninvalidationintegration-testing
Run
dotnet run --project src/RedisHybridProducts
Test
dotnet test RedisHybridProducts.slnx