skip to content

In ASP.NET Core's HybridCache, how do Expiration and LocalCacheExpiration differ, and why can RemoveAsync leave other instances serving the old value?

level: middleimportance: should knowfreq 38%

answer

  1. Expiration: overall and distributed tier
  2. LocalCacheExpiration: in-process tier only
  3. local capped at overall, defaults to it
  4. absolute only, no sliding window
  5. RemoveAsync clears this L1 and L2

basics

~10 s

Expiration is the overall and distributed-tier lifetime; LocalCacheExpiration is how long each process keeps its memory copy, defaulting to Expiration and never longer. RemoveAsync clears only the caller's memory and the shared store.

solid answer

~40 s

`HybridCacheEntryOptions` has `Expiration`, `LocalCacheExpiration` and `Flags`, set per call or as `HybridCacheOptions.DefaultEntryOptions`. `Expiration` is written to the `IDistributedCache` as an absolute, relative-to-now expiration and is the default for L1; `LocalCacheExpiration` applies only to the `IMemoryCache` copy, defaults to `Expiration`, is capped at it, and an L1 copy filled from L2 is also capped at the time L2 has left. There is no sliding expiration. `RemoveAsync(key)` removes the key from **this** process's `IMemoryCache` and from the distributed store, but other instances' L1 copies stay until their `LocalCacheExpiration` runs out. That is why a common setting pairs a long `Expiration`, such as 10 minutes, with a short `LocalCacheExpiration`, such as 30 seconds: the database is protected by L2, and the staleness after a change is bounded by L1.

code

csharp · 16 lines
csharp
private static readonly HybridCacheEntryOptions CardOptions = new()
{
    Expiration = TimeSpan.FromMinutes(10),
    LocalCacheExpiration = TimeSpan.FromSeconds(30)
};

public ValueTask<ProductCard> GetCardAsync(string sku, CancellationToken ct) =>
    cache.GetOrCreateAsync($"card:{sku}",
        async token => await db.LoadCardAsync(sku, token),
        CardOptions, cancellationToken: ct);

public async Task UpdatePriceAsync(string sku, decimal price, CancellationToken ct)
{
    await db.SetPriceAsync(sku, price, ct);
    await cache.RemoveAsync($"card:{sku}", ct);
}

go deeper

for a junior

Recall that Expiration is the overall lifetime and LocalCacheExpiration is how long each server keeps its in-memory copy.

for a middle

Explain the fallback and capping rules, that both are absolute with no sliding, and that RemoveAsync clears the local tier of the calling instance and the distributed tier.

for a senior

Use LocalCacheExpiration as the bound on cross-instance staleness after a change, and bypass L1 with flags where any stale read is unacceptable.

for a principal

Set expiration policy per data class from the business's staleness tolerance and the backend's capacity, and make the cross-instance staleness window an explicit, documented number.

## Two lifetimes for two tiers `HybridCacheEntryOptions` is a small sealed class with `init` properties: | Property | Applies to | Default | |---|---|---| | `Expiration` | the distributed tier, and L1 when nothing more specific is set | 5 minutes | | `LocalCacheExpiration` | the in-process `IMemoryCache` copy only | the effective `Expiration` | | `Flags` | which tiers to read and write, as `HybridCacheEntryFlags` | none | Both expirations are **absolute and relative to the write**. `Expiration` becomes `AbsoluteExpirationRelativeToNow` on the `DistributedCacheEntryOptions` passed to the store, and the L1 entry gets `AbsoluteExpirationRelativeToNow` as well. Neither tier uses a sliding window, so a frequently read entry still expires on time. Three rules connect the two values: 1. **`LocalCacheExpiration` falls back to `Expiration`.** Set only `Expiration` and both tiers use it. 2. **`LocalCacheExpiration` cannot exceed `Expiration`.** A longer value is cut down to the overall lifetime. 3. **An L1 copy loaded from L2 never outlives the L2 entry.** When an instance fills L1 from Redis, it caps the local lifetime at the time the distributed entry has left. ## Defaults and per-call options `HybridCacheOptions.DefaultEntryOptions` sets the defaults for every call. A call that passes its own `HybridCacheEntryOptions` overrides them for the expirations it sets, and a per-call `Expiration` given alone also becomes that call's local lifetime; anything left `null` comes from the defaults, and with no defaults at all the built-in 5 minutes applies. ```csharp builder.Services.AddHybridCache(o => o.DefaultEntryOptions = new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(10), LocalCacheExpiration = TimeSpan.FromSeconds(30) }); ``` ## What RemoveAsync reaches `RemoveAsync(key)` does two things in `DefaultHybridCache`: - removes the key from the calling process's `IMemoryCache`; - calls `RemoveAsync` on the `IDistributedCache`, when one is registered. It sends nothing to other processes. Suppose the sports retailer runs four storefront instances and a merchandiser changes the price on `card:boot-123`: 1. The admin API, running on instance 2, updates the database and calls `RemoveAsync("card:boot-123")`. 2. Instance 2's L1 and the Redis entry are gone; its next read reloads the new price. 3. Instances 1, 3 and 4 still hold the old card in their own L1 and keep serving it until their local copies expire. 4. When they expire, those instances miss L1, miss L2, run the factory and get the new price. The ASP.NET Core docs state the same limit: invalidation by key or tag affects the current server and the out-of-process store, not the in-memory caches of other servers. ## Choosing the numbers The two settings answer two different questions: - **`Expiration`: how often may the database be asked?** Long values protect the backend, because a fresh instance or an expired L1 copy can refill from Redis. - **`LocalCacheExpiration`: how stale may one instance be after a change?** That is the window during which another instance can serve the old value after `RemoveAsync`. For catalogue cards, 10 minutes and 30 seconds is a typical pairing. For data where any instance serving an old value is unacceptable, skip L1 for that call with `HybridCacheEntryFlags.DisableLocalCache`, accepting a Redis round trip per read. ## Flags in brief `HybridCacheEntryFlags` disables parts of the flow per call: `DisableLocalCacheRead`, `DisableLocalCacheWrite`, `DisableDistributedCacheRead`, `DisableDistributedCacheWrite`, the combined `DisableLocalCache` and `DisableDistributedCache`, and `DisableUnderlyingData`, which skips the factory. With no `IDistributedCache` registered, the distributed flags are always on. ## Common mistakes - **Expecting sliding behaviour.** Popular entries expire on schedule; reads do not extend them. - **Assuming `RemoveAsync` is farm-wide.** It is not; the local lifetime is the real bound on staleness across instances. - **Setting `LocalCacheExpiration` longer than `Expiration`.** It is silently capped, so the longer value has no effect. ## A worked timeline With `Expiration` of 10 minutes and `LocalCacheExpiration` of 30 seconds, a card first loaded at 12:00:00 behaves as follows: 1. **12:00:00** instance 1 runs the factory, writes Redis (expires 12:10:00) and its L1 (expires 12:00:30). 2. **12:00:20** instance 3 misses L1, reads Redis, and writes its own L1, capped to 30 seconds. 3. **12:00:30** instance 1's L1 copy expires; its next read comes from Redis, not the database. 4. **12:10:00** Redis expires; the next reader on any instance runs the factory again. The database sees roughly one query per 10 minutes, while no instance holds a local copy older than 30 seconds.

  • Can you give a HybridCache entry a sliding expiration?
    No. `HybridCacheEntryOptions` has only `Expiration` and `LocalCacheExpiration`, both absolute and relative to the write, and the distributed tier receives an `AbsoluteExpirationRelativeToNow`. If idle-based expiry is essential, `IMemoryCache` or `IDistributedCache` with sliding options is the tool.
  • How do you make sure no instance serves a value after it changes, using HybridCache?
    Bypass L1 for that data with `HybridCacheEntryFlags.DisableLocalCache`, so every read goes to the shared distributed tier, which `RemoveAsync` does clear. You pay a network round trip per read; alternatively accept staleness up to a short `LocalCacheExpiration`.

  • RemoveAsync clears the key from every instance's in-memory cache
  • LocalCacheExpiration can be longer than Expiration to keep hot items local
  • Each read of a HybridCache entry slides its expiration forward
  • Expiration controls only the in-memory tier
  • Without per-call options HybridCache entries never expire