With ASP.NET Core's IDistributedCache, what do DistributedCacheEntryOptions and RefreshAsync control, and what expiration does an entry written without options get?
answer
- absolute, relative-to-now, sliding
- reads refresh sliding too
- RefreshAsync moves no bytes
- Redis: no options means no TTL
- SQL Server: DefaultSlidingExpiration 20 minutes
basics
~20 sDistributedCacheEntryOptions sets an absolute deadline, a relative one, or a sliding window; reads and RefreshAsync reset the sliding window. Without options, Redis sets no expiry at all, while the SQL Server store applies a 20-minute sliding default.
solid answer
~40 s`DistributedCacheEntryOptions` has three properties: `AbsoluteExpiration` (a `DateTimeOffset`), `AbsoluteExpirationRelativeToNow` and `SlidingExpiration` (both `TimeSpan`), set directly or through `SetAbsoluteExpiration` and `SetSlidingExpiration`. Zero or negative spans throw `ArgumentOutOfRangeException`. A sliding window is reset by every `GetAsync` and by `RefreshAsync`, which resets it without transferring the value, but it never runs past the absolute deadline. What happens with **no** options depends on the store: the extension overloads pass an empty options object, `RedisCache` then writes the entry with no TTL, so it stays until removed or evicted by Redis, while `SqlServerCache` substitutes `SqlServerCacheOptions.DefaultSlidingExpiration`, 20 minutes. Always pass options explicitly so behaviour does not change with the store.
code
csharp · 9 linesapp.Use(async (context, next) =>
{
if (context.Request.Cookies.TryGetValue("basket", out var id))
{
var cache = context.RequestServices.GetRequiredService<IDistributedCache>();
await cache.RefreshAsync($"basket:{id}", context.RequestAborted);
}
await next(context);
});go deeper
Recall the three expiration properties, that sliding expiration is reset by reads, and that RefreshAsync exists to reset it without reading the value.
Explain how Redis turns the options into a TTL, why the absolute deadline caps a sliding window, and that the no-options default differs between Redis and SQL Server.
Always pass explicit options, avoid shared options holding a fixed instant, and weigh the extra round trip sliding expiration adds to every read on a remote store.
Set expiration policy from the staleness the business accepts and the store's memory budget, and make it consistent across environments so behaviour does not change with infrastructure.
## The three settings `DistributedCacheEntryOptions` (namespace `Microsoft.Extensions.Caching.Distributed`) carries per-entry expiration for any `IDistributedCache` store: | Property | Type | Meaning | |---|---|---| | `AbsoluteExpiration` | `DateTimeOffset?` | the entry expires at this instant | | `AbsoluteExpirationRelativeToNow` | `TimeSpan?` | the entry expires this long after the write | | `SlidingExpiration` | `TimeSpan?` | the entry expires after this long without being read or refreshed | The fluent helpers in `DistributedCacheEntryExtensions` set the same values: `SetAbsoluteExpiration(TimeSpan)`, `SetAbsoluteExpiration(DateTimeOffset)` and `SetSlidingExpiration(TimeSpan)`. Validation happens in two places: - **The setters** reject zero or negative spans with `ArgumentOutOfRangeException` ("The relative expiration value must be positive." and the sliding equivalent). - **The Redis and SQL Server stores** reject an `AbsoluteExpiration` that is already in the past: `RedisCache` with `ArgumentOutOfRangeException`, `SqlServerCache` with `InvalidOperationException`, both saying the value "must be in the future". The in-memory store simply never keeps such an entry. ## Sliding expiration and RefreshAsync A sliding window is reset whenever the entry is touched: 1. **`GetAsync`** returns the value and, when the entry has a sliding expiration, extends it. In Redis that is a hash read followed by a separate `EXPIRE`; in SQL Server an `UPDATE` of `ExpiresAtTime` followed by the `SELECT`. 2. **`RefreshAsync`** does the same extension **without transferring the value**. It suits the fashion retailer's basket: while a shopper browses product pages, the app refreshes `basket:{id}` on each request without downloading a snapshot it does not need. The window never extends past an absolute deadline. `RedisCache` sets the key's TTL to the smaller of the sliding window and the time left before the absolute expiration; the SQL Server store's refresh query uses the absolute time once fewer seconds remain than the window. `Refresh` on an entry with only an absolute expiration does nothing. ## No options means different things The extension overloads `SetAsync(key, bytes)` and `SetStringAsync(key, text)` pass a shared, frozen, empty `DistributedCacheEntryOptions`. Each store then decides: | Store | Entry written with no options | |---|---| | Redis (`AddStackExchangeRedisCache`) | no TTL; it stays until removed, overwritten or evicted by the Redis server's own memory policy | | SQL Server (`AddDistributedSqlServerCache`) | sliding expiration of `SqlServerCacheOptions.DefaultSlidingExpiration`, **20 minutes** by default | | In-memory (`AddDistributedMemoryCache`) | no expiration; it stays until removed or compacted under the 200 MB size limit | The same line of code therefore caches a basket for 20 idle minutes in a SQL-backed environment and for ever in a Redis-backed one. A Redis instance filling up with abandoned baskets is the usual symptom. ## Choosing options for basket snapshots ```csharp private static readonly DistributedCacheEntryOptions BasketOptions = new() { SlidingExpiration = TimeSpan.FromMinutes(30), AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1) }; await cache.SetAsync($"basket:{id}", bytes, BasketOptions, ct); ``` - **Sliding 30 minutes** drops baskets of shoppers who left. - **Absolute one day** caps baskets that are touched constantly, so prices and stock in a snapshot cannot be older than a day. - **A static options instance is safe** with relative values. A shared instance holding a fixed `AbsoluteExpiration` instant is not, because every later write inherits the same instant, which eventually lies in the past and makes the store throw. ## Cost of sliding expiration Sliding expiration is not free on a remote store: - **Every read is two operations** in Redis (read, then `EXPIRE`) and two statements in SQL Server. - **Refresh traffic scales with page views**, not with basket changes. When the business rule is "a snapshot is valid for N minutes", an absolute expiration alone is cheaper and easier to reason about. ## Mistakes to avoid 1. **Relying on defaults.** Writing without options produces a 20-minute sliding entry on SQL Server and an entry with no TTL on Redis, so the same code behaves differently per environment. 2. **Expecting reads to leave expiry alone.** Every `GetAsync` on a sliding entry also extends it; a monitoring job that polls a key keeps it alive. 3. **Calling `RefreshAsync` on absolute-only entries.** It has nothing to extend and only costs a round trip. 4. **Reusing a fixed instant.** A static options object holding `AbsoluteExpiration = DateTimeOffset.UtcNow.AddHours(1)` starts throwing on Redis an hour after startup. Stating the store-specific default and the absolute cap on sliding windows is what separates a middle-level answer from a list of property names.
- An entry has a 30-minute sliding and a 2-hour absolute expiration in Redis and is read every 10 minutes; when does it expire?Two hours after it was written. Each read resets the TTL to the smaller of 30 minutes and the time left before the absolute deadline, so steady reads keep it alive only until the absolute expiration, which reads cannot move.
- Why might the same SetStringAsync call behave differently in development and production?Without options the expiration is chosen by the store. If development uses SQL Server, entries get the 20-minute `DefaultSlidingExpiration`; on Redis in production they get no TTL and pile up. Passing explicit `DistributedCacheEntryOptions` removes the difference.
- Redis entries written with SetStringAsync and no options expire after 20 minutes
- RefreshAsync reloads the value from its source and writes it again
- A steadily read sliding entry can outlive its absolute expiration
- GetAsync never changes an entry's expiration; only RefreshAsync does
- With RedisCache, an AbsoluteExpiration in the past just stores an already-expired entry