In ASP.NET Core, what is IDistributedCache, why does it deal in byte arrays, and how do you back it with Redis?
answer
- one copy outside every web process
- Task<byte[]?> GetAsync, null on a miss
- SetStringAsync is a UTF-8 extension
- the caller serializes; no typed API
- Microsoft.Extensions.Caching.StackExchangeRedis
basics
~20 sIDistributedCache is ASP.NET Core's abstraction over a cache that lives outside the web process, so every instance reads the same entry. It stores byte arrays under string keys; you serialize objects yourself and register Redis with AddStackExchangeRedisCache.
solid answer
~40 s`IDistributedCache` (namespace `Microsoft.Extensions.Caching.Distributed`) has four operations, each sync and async: `GetAsync` returns `Task<byte[]?>` (null on a miss), `SetAsync` takes a `byte[]` and `DistributedCacheEntryOptions`, `RefreshAsync` resets a sliding expiration, and `RemoveAsync` deletes. Values are bytes because they leave the process: the store is Redis, SQL Server or another server, so there is no object reference to hand back. You serialize, usually to JSON with `JsonSerializer.SerializeToUtf8Bytes`, or use the `SetStringAsync` / `GetStringAsync` extensions, which only convert UTF-8 text. For Redis, add the `Microsoft.Extensions.Caching.StackExchangeRedis` package and call `builder.Services.AddStackExchangeRedisCache(o => { o.Configuration = ...; o.InstanceName = "shop:"; })`. All four instances behind the load balancer then read and write one shared copy of each entry, and it survives an app restart.
code
csharp · 22 linesusing System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(o =>
{
o.Configuration = builder.Configuration.GetConnectionString("redis");
o.InstanceName = "shop:";
});
var app = builder.Build();
app.MapGet("/baskets/{id:guid}", async (Guid id, IDistributedCache cache, CancellationToken ct) =>
{
byte[]? bytes = await cache.GetAsync($"basket:{id}", ct);
return bytes is null
? Results.NotFound()
: Results.Ok(JsonSerializer.Deserialize<BasketSnapshot>(bytes));
});
app.Run();
public sealed record BasketSnapshot(Guid Id, string[] Skus, decimal Total);go deeper
Recall that IDistributedCache stores byte arrays under string keys outside the process, that you serialize values yourself, and that AddStackExchangeRedisCache registers a Redis-backed implementation.
Explain the four operations and the string extensions, why bytes are the honest contract for an out-of-process store, and how a shared store fixes per-instance misses behind a load balancer.
Treat the serialized shape as a stored contract that outlives a deploy, version keys when it changes, and plan for a store outage turning cache calls into exceptions.
Decide when a network hop per read is worth one shared copy, and when a two-tier design that adds a local cache in front pays for its extra staleness.
## What the abstraction is for `IMemoryCache` keeps objects inside one process, so a fashion retailer running four instances of its storefront API behind a load balancer has four separate caches. A shopper whose basket snapshot was cached by instance 1 and whose next request lands on instance 3 gets a miss there. `IDistributedCache` solves exactly that: it is the ASP.NET Core abstraction over a cache that lives **outside** the web processes, so every instance sees the same entry, and the entry survives a deploy or a crash of any one instance. ## The interface The interface is deliberately small: | Member | Returns | Purpose | |---|---|---| | `Get(key)` / `GetAsync(key, token)` | `byte[]?` / `Task<byte[]?>` | the value, or `null` on a miss | | `Set(key, value, options)` / `SetAsync(...)` | `void` / `Task` | store bytes with expiration options | | `Refresh(key)` / `RefreshAsync(...)` | `void` / `Task` | reset a sliding expiration without reading the value | | `Remove(key)` / `RemoveAsync(...)` | `void` / `Task` | delete the entry | The static `DistributedCacheExtensions` class adds `SetAsync(key, value)` without options, and `SetString` / `SetStringAsync` / `GetString` / `GetStringAsync`, which encode and decode text as UTF-8 and nothing more. There is **no** generic `GetAsync<T>`, no `GetOrCreateAsync` and no tagging. ## Why bytes A value in Redis or a SQL Server table is a sequence of bytes on another machine. There is no object reference to return, so the abstraction does not pretend there is one: the caller chooses the serialization format and owns its compatibility. A basket snapshot round-trip looks like this: ```csharp public sealed class BasketSnapshots(IDistributedCache cache) { public async Task<BasketSnapshot?> GetAsync(Guid basketId, CancellationToken ct) { byte[]? bytes = await cache.GetAsync($"basket:{basketId}", ct); return bytes is null ? null : JsonSerializer.Deserialize<BasketSnapshot>(bytes); } public Task SaveAsync(BasketSnapshot snapshot, CancellationToken ct) => cache.SetAsync($"basket:{snapshot.Id}", JsonSerializer.SerializeToUtf8Bytes(snapshot), new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(30) }, ct); } ``` Two consequences follow: - **Every read deserializes a fresh object.** Mutating it cannot corrupt the cached copy, unlike an `IMemoryCache` reference. - **The type's shape is now a stored contract.** Rename a property of `BasketSnapshot` and entries written by the previous deploy deserialize with that property missing. Put a version in the key (`basket:v2:{id}`) when the shape changes incompatibly. ## Backing it with Redis ```csharp builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = builder.Configuration.GetConnectionString("redis"); options.InstanceName = "shop:"; }); ``` - **Package:** `Microsoft.Extensions.Caching.StackExchangeRedis`, which registers `IDistributedCache` as a singleton. - **Connection:** `Configuration` takes a StackExchange.Redis connection string; `ConfigurationOptions` takes a parsed object and wins when both are set; `ConnectionMultiplexerFactory` lets you reuse a multiplexer the app already owns. - **`InstanceName`:** a prefix written in front of every key so several apps can share one Redis. Other stores plug in the same way: `AddDistributedSqlServerCache` for a SQL Server table and `AddDistributedMemoryCache` for an in-process stand-in used in development and tests. Application code depends only on `IDistributedCache`, so switching stores is a `Program.cs` change. ## What it does not do 1. **Coordinate concurrent misses.** Two instances that miss the same key both load and both write. 2. **Hide outages.** A Redis call that fails throws; nothing falls back to a miss for you. 3. **Keep a local copy.** Every read is a network round trip. Those gaps are why ASP.NET Core also offers `HybridCache`, which layers an in-process tier and miss coordination on top of a registered `IDistributedCache`. ## Mistakes interviewers listen for - **Treating it like `IMemoryCache`.** Expecting a stored object back, or mutating a deserialized basket and assuming the cache changed, shows the out-of-process model has not landed. - **Assuming `SetStringAsync` serializes objects.** It only encodes a `string` as UTF-8; turning a `BasketSnapshot` into that string is still the caller's job. - **Omitting expiration options.** The overloads without `DistributedCacheEntryOptions` leave the choice to the store, and on Redis that means no expiry at all. - **Using `AddDistributedMemoryCache` in a farm.** It implements the interface inside each process, so four instances still hold four caches. A strong answer names the interface, says why it is byte-based, shows one serialize-and-store round trip with explicit options, and registers Redis with a prefixed `InstanceName`.
- Why does IDistributedCache have no GetOrCreateAsync?The interface stops at get, set, refresh and remove, and the extensions only add byte and UTF-8 string overloads. A get-or-create needs a serializer and a policy for concurrent misses, which the abstraction leaves to the caller. `HybridCache` is the library that adds `GetOrCreateAsync` on top of a registered `IDistributedCache`.
- What happens to cached basket snapshots when a deploy renames a property of BasketSnapshot?Entries written by the old build still hold the old JSON. `System.Text.Json` ignores unknown properties by default and leaves the renamed one at its default, so the new build silently reads incomplete baskets until they expire. Change the key prefix, for example `basket:v2:`, when the stored shape changes.
- Is IDistributedCache registered as scoped, transient or singleton?All three built-in stores register it as a singleton: `AddStackExchangeRedisCache` and `AddDistributedSqlServerCache` with `Add`, `AddDistributedMemoryCache` with `TryAdd`. The Redis implementation holds one lazily created connection for the whole app, so it is safe to inject anywhere.
- IDistributedCache returns the same object reference that was stored, like IMemoryCache
- IDistributedCache has a generic GetAsync<T> that deserializes values for you
- SetStringAsync serializes any object to JSON before storing it
- With AddStackExchangeRedisCache each instance keeps its own copy and Redis syncs them
- A Redis outage makes GetAsync return null so callers fall back automatically