.NET › Caching (In-Memory, Distributed & Redis)
What is the difference between absolute expiration and sliding expiration when configuring a cache entry?
IntermediateAnswer
Absolute expiration removes an entry at a fixed point in time regardless of how recently it was accessed, 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-used entries expire -- the two can be combined to set both a 'refresh on access' behavior and a hard maximum lifetime.
_cache.Set("key", value, new MemoryCacheEntryOptions {
SlidingExpiration = TimeSpan.FromMinutes(5), // resets on each access
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) // hard cap regardless
});Real-world example A frequently-accessed user 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.