With AddStackExchangeRedisCache in ASP.NET Core, what does InstanceName do to keys, how is an entry stored, and what happens when Redis is unreachable?
answer
- prefix bytes, no separator added
- hash fields absexp, sldexp, data
- AbortOnConnectFail forced to false
- lazy connect on first call
- failures throw; no fallback to a miss
basics
~20 sInstanceName is prepended to every key exactly as written, with no separator. Each entry is a Redis hash holding absexp, sldexp and data plus a key TTL. An unreachable Redis does not stop startup, but cache calls then throw.
solid answer
~40 s`RedisCache` turns `InstanceName` into a byte prefix and appends each key to it, so `InstanceName = "shop"` and key `basket:42` become `shopbasket:42`; include your own separator (`"shop:"`). The prefix partitions one Redis between apps but isolates nothing else: they share memory, eviction and credentials. Each entry is stored as a **hash** with fields `absexp`, `sldexp` and `data`, and the key's TTL is set with `EXPIRE`, so a plain string `GET` on it fails. The connection is created lazily on the first cache call, and `GetConfiguredOptions` forces `AbortOnConnectFail = false`, so a Redis that is down at startup does not break DI. Once running, a failed call is **rethrown** to the caller (`RedisConnectionException`, `RedisTimeoutException`); `IDistributedCache` never turns an outage into a miss, so wrap reads if a cache outage must not fail the request.
code
csharp · 11 linesvar redisOptions = ConfigurationOptions.Parse(
builder.Configuration.GetConnectionString("redis")!);
redisOptions.AbortOnConnectFail = false;
var redis = await ConnectionMultiplexer.ConnectAsync(redisOptions);
builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
builder.Services.AddStackExchangeRedisCache(o =>
{
o.InstanceName = "storefront:";
o.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(redis);
});go deeper
Recall that InstanceName is a prefix added to every key so several apps can share one Redis.
Explain that the prefix is appended with no separator, that entries are hashes with absexp, sldexp and data, and that the TTL is set from the options.
Explain lazy connection and the forced AbortOnConnectFail = false, show that outages throw RedisConnectionException or RedisTimeoutException, and decide where a cache outage should degrade to a miss.
Judge whether apps should share one Redis by prefix or get separate instances, given shared memory, eviction and access, and how much a cache outage may cost.
## InstanceName is a raw prefix `RedisCacheOptions.InstanceName` lets several applications share one Redis. In the `RedisCache` constructor a non-empty `InstanceName` is UTF-8 encoded into a `RedisKey`, and every operation calls `_instancePrefix.Append(key)`. Nothing is inserted between the two: | `InstanceName` | Key passed to `SetAsync` | Key in Redis | |---|---|---| | `"shop"` | `basket:42` | `shopbasket:42` | | `"shop:"` | `basket:42` | `shop:basket:42` | | not set | `basket:42` | `basket:42` | The fashion retailer's storefront and its back-office app can therefore use `"storefront:"` and `"backoffice:"` against the same server without key collisions. What the prefix does **not** do: - **Isolate memory.** Both apps' keys compete under one server memory limit and eviction policy. - **Isolate access.** Any client with the connection string can read any prefix. - **Enable bulk removal.** `IDistributedCache` has no remove-by-prefix; clearing one app's keys needs Redis tooling. ## How an entry is stored `RedisCache` writes each entry as a Redis **hash** with three fields: - `absexp`: the absolute expiration in ticks, or -1 when absent; - `sldexp`: the sliding window in ticks, or -1 when absent; - `data`: the value bytes. When the options carry an expiration, the hash write and an `EXPIRE` are pipelined together, with the TTL set to the smaller of the sliding window and the time left before the absolute deadline. Reads fetch the hash fields and, when `sldexp` is present, issue another `EXPIRE` to slide the window. Two practical effects: 1. **Inspecting a key with a string command fails**, because the key holds a hash; read the `data` field of the hash instead. 2. **Other clients cannot share the entries casually.** A worker written in another language must understand the hash layout and the ticks encoding to read or write compatible entries. ## Connecting The multiplexer is not created when the service is constructed. The first cache call enters `ConnectAsync`, which takes a `SemaphoreSlim` so only one caller connects, then either calls `ConnectionMultiplexer.ConnectAsync` with the configured options or invokes your `ConnectionMultiplexerFactory`. `GetConfiguredOptions` always sets `AbortOnConnectFail = false`, with a source comment saying an initially unavailable server should not prevent DI from creating the service. So: - **Redis down at startup:** the app starts; the multiplexer keeps retrying in the background. - **Shared multiplexer:** set `ConnectionMultiplexerFactory` to return the `IConnectionMultiplexer` the app already registered, instead of opening a second set of connections. The forced flag then no longer applies: your multiplexer uses the options you gave it. - **Stuck connections:** an app-context switch, `Microsoft.AspNetCore.Caching.StackExchangeRedis.UseForceReconnect`, lets the cache replace its connection after connection or socket errors have persisted for at least 30 seconds, at most once a minute; it is off by default. ## When Redis is unreachable Every Redis call sits in a `try` whose `catch` calls `OnRedisError`, which only feeds the optional force-reconnect logic, and then rethrows. `RedisCache` does not log the failure itself. `GetAsync` does **not** return `null` during an outage; the caller sees a `RedisConnectionException`, or a `RedisTimeoutException` when commands time out. For basket snapshots, which can be rebuilt from the order database, that is the wrong failure mode: ```csharp try { bytes = await cache.GetAsync(key, ct); } catch (RedisException ex) { logger.LogWarning(ex, "Basket cache unavailable; reading from the database"); bytes = null; } ``` Decide per use: data the cache can lose should degrade to a miss; data that exists only in the cache, such as a session, should fail loudly. Catch `RedisTimeoutException` as well if timeouts must also degrade: it derives from `TimeoutException`, not from `RedisException`. ## Interview checklist 1. Put a separator in `InstanceName` yourself. 2. Know that entries are hashes with `absexp`, `sldexp` and `data`. 3. Explain lazy connection and the forced `AbortOnConnectFail = false`. 4. Say that outages surface as exceptions, and choose deliberately where to swallow them. ## Seeing it in production Two signals tell you how the Redis cache is behaving: - **Your own logs.** `RedisCache` rethrows failed operations without logging them, so they appear as unhandled request exceptions, or as your fallback's warnings if you catch them; log at the fallback, or the outage is invisible once you swallow it. - **Key inspection.** Listing keys by the `InstanceName` prefix shows how many basket snapshots exist; checking their TTLs shows whether some were written without options and will never expire. Both checks belong in the runbook for any app that shares a Redis by prefix, because a neighbour's keys and a neighbour's outage affect you too.
- If you supply ConnectionMultiplexerFactory, does the forced AbortOnConnectFail = false still protect startup?No. `GetConfiguredOptions`, which forces the flag, is only used when the factory is null. Your factory's multiplexer uses whatever options you built, and StackExchange.Redis defaults `AbortOnConnectFail` to true, so an eager connect to an unreachable server throws. Set it to false yourself, or `abortConnect=false` in the connection string.
- Two apps share a Redis with InstanceName values "shop" and "shopadmin"; what can go wrong?Because the prefix is appended without a separator, the key `admin:7` in the first app becomes `shopadmin:7`, which is the same key as `:7` written by the second app. Prefixes that are not prefix-free can collide; ending every `InstanceName` with a separator such as `:` avoids it.
- InstanceName "shop" makes keys like shop:basket:42 because a colon is added
- InstanceName gives each app its own isolated Redis memory and eviction
- RedisCache stores each value as a plain Redis string set with SET and EX
- If Redis is down at startup, AddStackExchangeRedisCache makes the app fail to start
- RedisCache swallows connection errors and reports them as cache misses