📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do IDistributedCache and Redis work in ASP.NET Core? Explain serialisation, the latency you should expect, what Redis is good at beyond key-value caching, and which Azure Redis offering you would choose today.

IDistributedCache over Redis: the byte-array API, serialisation cost, network latency, Redis data structures and features, connection management, and Azure Managed Redis versus the retiring Azure Cache for Redis.

Intermediate Theory Intermediate azure-managed-redis caching idistributedcache performance redis serialisation

🎯 Key points

  • IDistributedCache stores byte[] with absolute or sliding expiration; you choose the serialiser
  • AddStackExchangeRedisCache; one multiplexed ConnectionMultiplexer per process
  • Expect ~0.5-2 ms per round trip in-region plus serialisation; batch or use L1 for hot keys
  • Keep values small (KB, not MB); large values block Redis's single command thread
  • Redis also offers atomic counters, sorted sets, pub/sub, streams, Lua and TTLs
  • Azure Managed Redis is the current offering; Azure Cache for Redis Enterprise retires 31 Mar 2027, Basic/Standard/Premium 30 Sep 2028
  • Cache is not durable storage: design for misses, timeouts and failover

⏱ 30-second answer

IDistributedCache is a minimal, byte-array cache API: GetAsync, SetAsync, RefreshAsync, RemoveAsync with absolute or sliding expiration. With AddStackExchangeRedisCache the values live in Redis, so every instance shares them and they survive deployments.

  • You own serialisation (System.Text.Json, ideally source-generated, or MessagePack), and its CPU and size cost.
  • Each read is a network round trip, roughly 0.5-2 ms in the same Azure region, so hot keys still benefit from an in-memory L1.
  • Redis is more than a cache: atomic counters, sorted sets, pub/sub, streams.

For new Azure work I'd pick Azure Managed Redis, because Azure Cache for Redis is retiring. The trade-off is shared consistency versus a network hop and another dependency.

🗣 Full answer (senior)

How I would answer this in an interview

"IDistributedCache is deliberately minimal: get, set, refresh and remove a byte[] by string key, with absolute or sliding expiration. That means it works over Redis, SQL Server or Cosmos DB, but it also means serialisation is my job. In ASP.NET Core I register it with AddStackExchangeRedisCache, which uses StackExchange.Redis underneath with a single multiplexed connection per process.

The thing I keep in mind is that every call is a network round trip. In the same Azure region, Redis usually answers in well under a millisecond on the server, so you see roughly half a millisecond to two milliseconds end to end, plus the time to serialise and deserialise. That's great compared with a 40 ms SQL query, but if a request reads the same key twenty times it adds up, so for hot keys I put an in-memory layer in front, which is exactly what HybridCache does. I also keep values small: Redis runs commands on a single main thread, so one 5 MB value slows every other client on that node.

Redis is good at much more than caching: INCR for rate limits and counters, sorted sets for leaderboards, pub/sub for invalidation messages, streams, and distributed locks with care. On Azure today I'd choose Azure Managed Redis. Microsoft has announced Azure Cache for Redis is retiring, the Enterprise tiers on 31 March 2027 and Basic, Standard and Premium on 30 September 2028, so new caches should not go there. The mistake I see is treating the cache as a database: it can fail over, evict or be flushed, so the app must work, slower, on a miss."


IDistributedCache at a glance

Member Notes
GetAsync(key) Returns byte[]?; null on miss
SetAsync(key, value, options) DistributedCacheEntryOptions: absolute, relative or sliding expiration
RefreshAsync(key) Resets sliding expiration without reading the value
RemoveAsync(key) Explicit invalidation
Extension methods GetStringAsync/SetStringAsync (UTF-8)

Serialisation choices

Serialiser Size Speed Notes
System.Text.Json (source-generated) Medium Fast, no reflection Good default; readable in redis-cli
MessagePack Small Very fast Binary; version contracts carefully
Protobuf Small Fast Needs schema
BinaryFormatter n/a n/a Removed and insecure; never

Azure options (as of November 2026)

Offering Status Notes
Azure Managed Redis Current, recommended Built on Redis Enterprise; Memory/Balanced/Compute Optimised tiers; available in Australia East
Azure Cache for Redis Enterprise / Enterprise Flash Retiring 31 March 2027; new creation blocked since April 2026 Migrate to Azure Managed Redis
Azure Cache for Redis Basic/Standard/Premium Retiring 30 September 2028 Migration tooling available; plan the move now

Production example

A quoting service moved product prices from per-pod IMemoryCache to Redis so all 8 pods agreed after a price change. Reads went from ~100 ns to ~0.9 ms p50 and 2.5 ms p99, which was fine for one read per request. Switching from reflection-based JSON to source-generated System.Text.Json cut serialisation CPU on that path by about 40%.

🔍 What the interviewer is checking

Checks that the candidate understands what a distributed cache costs (network, serialisation, an extra dependency), uses Redis correctly from .NET and knows the current Azure landscape.

Green flags

  • Mentions serialisation choice and value size
  • Gives realistic latency numbers and suggests an L1 for hot keys
  • Knows one multiplexer per process and designs for Redis failure
  • Knows Azure Managed Redis is the current offering

Red flags

  • Treats Redis as durable storage
  • Uses BinaryFormatter or creates a connection per call
  • Thinks a distributed cache read is as cheap as a memory read

📚 Learn in depth

1. The request path

request -> serialise key/value -> StackExchange.Redis multiplexer -> TCP/TLS (port 6380/10000)
        -> Redis main thread executes GET/SET -> response -> deserialise

StackExchange.Redis pipelines all commands from a process over a small number of connections. Creating a ConnectionMultiplexer per request is a classic bug: it's expensive and leaks sockets. AddStackExchangeRedisCache manages one for you.

2. Why Redis is fast, and its limits

Redis keeps everything in RAM and executes commands on a single main thread (I/O threads help with networking), so each command is atomic and there are no locks. The flip side: an O(n) command (KEYS *, a huge HGETALL) or a large value blocks everyone. Keep values in the KB range and use SCAN instead of KEYS.

3. How the Redis IDistributedCache stores entries

The Redis provider stores each entry as a hash with the data, absolute expiration and sliding expiration fields, and sets a Redis TTL. Sliding expiration therefore needs an extra round trip on read to refresh the TTL. Use absolute expiration where you can.

4. Failure modes

Failure Effect Mitigation
Failover or patching Seconds of timeouts Short timeouts, retry once, fall back to source
Eviction (maxmemory-policy) Unexpected misses Monitor evicted keys; size the cache
Large values Latency spikes for all clients Compress or split; keep < 100 KB
ThreadPool starvation in client RedisTimeoutException with busy worker counts Fix sync-over-async; read the timeout message's WORKER/IOCP numbers

5. Beyond caching

  • INCR + EXPIRE: fixed-window rate limiting across instances.
  • Sorted sets: leaderboards, time-ordered queues.
  • Pub/sub: broadcast invalidation to L1 caches (fire-and-forget; missed if disconnected).
  • Streams: durable-ish event logs with consumer groups.
  • Locks (SET key value NX PX): fine for efficiency, not for correctness without fencing tokens.

Try it yourself

  1. Run Redis in Docker, register AddStackExchangeRedisCache, and time 1,000 GetAsync calls; compare with IMemoryCache.
  2. Benchmark System.Text.Json reflection versus a JsonSerializerContext for your DTO with [MemoryDiagnoser].
  3. Store a 5 MB value and run redis-cli --latency from another terminal while reading it in a loop.
  4. Stop the Redis container mid-load and check your endpoint still answers (slower) from the database.
  5. Use INCR with EXPIRE to build a per-client counter and test it from two app instances.

💻 Code

A typed wrapper over IDistributedCache with source-generated JSON, short timeouts and a fallback to the source when Redis is unavailable.

using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace Pricing.Caching;

public sealed record ProductPrice(string Sku, decimal Amount, DateTimeOffset AsOf);

[JsonSerializable(typeof(ProductPrice))]
internal sealed partial class PricingJsonContext : JsonSerializerContext;

public interface IPriceRepository
{
    Task<ProductPrice?> GetAsync(string sku, CancellationToken ct);
}

public sealed class PriceCache(IDistributedCache cache, IPriceRepository repository, ILogger<PriceCache> logger)
{
    private static readonly DistributedCacheEntryOptions Options = new()
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) // absolute: no refresh round trip
    };

    public async Task<ProductPrice?> GetAsync(string sku, CancellationToken ct)
    {
        var key = $"price:v1:{sku}";
        try
        {
            var bytes = await cache.GetAsync(key, ct);
            if (bytes is not null)
            {
                return JsonSerializer.Deserialize(bytes, PricingJsonContext.Default.ProductPrice);
            }
        }
        catch (Exception ex) when (ex is not OperationCanceledException)
        {
            // The cache is an optimisation: degrade to the database, don't fail the request.
            logger.LogWarning(ex, "Redis read failed for {CacheKey}", key);
        }

        var price = await repository.GetAsync(sku, ct);
        if (price is not null)
        {
            var payload = JsonSerializer.SerializeToUtf8Bytes(price, PricingJsonContext.Default.ProductPrice);
            try { await cache.SetAsync(key, payload, Options, ct); }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                logger.LogWarning(ex, "Redis write failed for {CacheKey}", key);
            }
        }
        return price;
    }
}
// Program.cs
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "pricing:"; // key prefix so services sharing a cache don't collide
});
builder.Services.AddSingleton<PriceCache>();

⚠ Common mistakes

  • Mistake: Adding Redis without measuring the source first. Why it is wrong: If the query is 3 ms, a 1 ms Redis hop plus serialisation saves little and adds a dependency. Instead: Measure source latency and hit ratio, then decide.
  • Mistake: Micro-optimising cold paths by putting rarely read data in Redis. Why it is wrong: The network hop and memory are wasted on keys nobody re-reads. Instead: Cache hot, shared data only.
  • Mistake: Creating a ConnectionMultiplexer per request. Why it is wrong: Slow handshakes and socket exhaustion. Instead: One shared multiplexer per process (the DI registration handles it).
  • Mistake: Storing multi-megabyte values. Why it is wrong: Redis's main thread is blocked while it sends them, raising latency for every client. Instead: Keep values small, compress, or cache a projection.
  • Mistake: Letting a Redis outage fail requests. Why it is wrong: The cache becomes a single point of failure. Instead: Short timeouts, log, and fall back to the source.
  • Mistake: Using sliding expiration by default with Redis. Why it is wrong: Every read costs an extra round trip to refresh the TTL, and hot keys never refresh. Instead: Prefer absolute expiration.
  • Mistake: Choosing Azure Cache for Redis for a new system. Why it is wrong: It is retiring (Enterprise tiers 31 March 2027, Basic/Standard/Premium 30 September 2028). Instead: Use Azure Managed Redis.
  • Mistake: Using KEYS * to find keys to delete. Why it is wrong: O(n) and blocks the server. Instead: Versioned keys, tags (HybridCache) or SCAN.

🏛 Senior insight: trade-offs

A senior answer treats the distributed cache as an optimisation that can disappear at any moment: failover, eviction, a flush during patching. The app must stay correct (and acceptably fast) on a miss, with timeouts tuned well below the request budget, and the database must be sized to survive a cold cache. It also recognises that IDistributedCache alone has no L1 and no stampede protection; in .NET 9+ HybridCache layers those on top of the same IDistributedCache registration.

Store behind IDistributedCache When it fits Cost When not to
Redis (Azure Managed Redis) Low latency, high throughput, shared Another managed service; memory-priced Tiny workloads where a single pod is enough
SQL Server distributed cache No extra infrastructure; small scale Adds load to the database you are protecting High read rates
Cosmos DB Already on Cosmos; global distribution RU cost per read Latency-critical hot paths

Monitoring is part of the design. I track and alert on:

Signal Where Alert when
Hit ratio (your own hit/miss counters) OpenTelemetry metrics Drops sharply (keys changed, cache flushed)
Redis dependency p95 and failures Application Insights p95 above a few ms or failure rate rises
Server load, used memory, evicted keys, connected clients Azure Monitor metrics for the Redis resource Memory near the limit, evictions climbing, server load > 80%
RedisTimeoutException count Logs Any sustained rate (often client ThreadPool starvation)
Source (SQL) load during cache incidents Query Store / Azure SQL metrics Spikes that track cache misses

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Redis counters or INCR Why: Checks they can apply Redis to a cross-instance rate limit
    How to answer

    The built-in middleware keeps counters in each process, so 10 instances allow roughly 10x the limit. Options: divide the limit by the instance count (cheap, approximate, and wrong as soon as autoscaling changes the count); enforce at a shared edge such as Azure API Management rate-limit-by-key / quota-by-key; or use a Redis-backed limiter (sliding window or token bucket in an atomic Lua script) for exact limits, at the cost of a network hop per request. Decide up front what happens when Redis is unreachable: fail open with a per-instance local limiter as a fallback, or fail closed for abuse-sensitive endpoints such as login.

  2. When: Candidate mentions invalidating cached data across instances Why: Checks they can invalidate across instances and a CDN
    How to answer

    Use a shared output cache store (Redis) so EvictByTagAsync clears every instance, not just the one that handled the write. At the CDN, keep s-maxage short or purge by path through the CDN API (an Azure Front Door purge can take minutes). For data that must change quickly, avoid purging altogether: content-hash or versioned URLs (/catalogue?v=42) make the new version a new cache key, and ETags let clients revalidate cheaply with If-None-Match and get 304 when nothing changed. Decide the acceptable staleness per endpoint; stale-while-revalidate keeps responses fast while the edge refreshes, and the client should re-read after its own write so users see their change.

  3. When: Candidate mentions HybridCache or wrapping a repository with a cache Why: Checks they can build a caching decorator with HybridCache
    How to answer

    The decorator implements IProductRepository and reads through HybridCache.GetOrCreateAsync, sending misses to the inner repository. HybridCache gives an in-memory L1 cache, an optional distributed L2, and stampede protection: 500 concurrent misses for a key make one database call.

    • Keys include everything that changes the result: product:v1:{tenant}:{id}.
    • Writes go through the decorator and invalidate after the inner write succeeds.
    • Exceptions aren't cached. Caching null is a deliberate choice with a short TTL.

    Register it with a factory delegate or a keyed inner service, or use Scrutor's Decorate<,>(). The trade-off is staleness: choose the TTL from how stale the business can tolerate.

↩ Usually asked after

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me