ASP.NET Core › Caching

How do you configure a cache entry's absolute versus sliding expiration, and when would you combine both?

Intermediate

Answer

Absolute expiration removes an entry at a fixed point in time regardless of access frequency, guaranteeing data won't become stale beyond a hard limit. Sliding expiration resets the expiration timer every time the entry is accessed, keeping frequently-used data cached indefinitely while letting rarely-accessed entries expire -- combining both gives a 'refresh on access, but never beyond X duration' behavior.
_cache.Set("key", value, new MemoryCacheEntryOptions {
    SlidingExpiration = TimeSpan.FromMinutes(5),           // resets on each access
    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) // hard cap regardless of access
});
Real-world example A frequently-accessed session cache uses a 5-minute sliding expiration combined with a 1-hour absolute cap, so active users keep their cached session alive while inactive sessions are forcibly cleared within an hour at most.

Common follow-ups: What happens if only sliding expiration is set with no absolute cap?;How does cache eviction interact with memory pressure signals under IMemoryCache?