Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 12

    Absolute and Sliding Expiration with Invalidation Races

    A completed Remove followed by a stale hit

    A reader captures 100 and pauses. A writer stores 120 and removes the entry. The reader resumes. Predict separately what that caller returns, what is cached and what a later caller reads; those are three different observations.

    Read with a purpose. Start with the scenarios table and cache lookups, then compare NaiveCatalog.ReadAsync/Write with GenerationCatalog.ReadAsync/Write. The protected check and insertion share the writer’s gate.

    Observation to predictNaiveCatalogGenerationCatalog
    Paused caller’s captured source100100
    Source after the writer120120
    Late publicationUnconditionalChecked under the writer’s gate

    Record the final cache state and next read yourself before viewing the check.

    Commit to a prediction

    In this lesson’s GenerationCatalog schedule, a reader captures 100, the writer stores 120 and removes the key, then the reader resumes. Which pair is expected: paused reader result / next read result?

    A 100 / 120
    B 120 / 120
    C 100 / 100
    D 120 / 100
    Show answer

    Correct answer: A

    GenerationCatalog rejects the stale cache publication but returns the paused caller’s captured 100. Its cache remains empty until the next read loads 120. The PDF’s separate GuardedFill retries after rejection and returns 120; that is a different caller-result policy. Neither example guarantees the latest value at response delivery.

    Runnable companion: assertions for expiration and a controlled late fill

    The following console program is a reproducible exercise. The output below is expected from the stated schedule; the checks throw if a result differs.

    Prerequisites and setup

    Use the .NET 10 SDK and a console project targeting net10.0, with implicit usings enabled (the console template default). These pinned packages make the example's API assumptions explicit; newer patch versions may exist.

    Shell
    dotnet new console --framework net10.0 --name CacheExpirationLab
    cd CacheExpirationLab
    dotnet add package Microsoft.Extensions.Caching.Memory --version 10.0.0
    dotnet add package Microsoft.Extensions.TimeProvider.Testing --version 10.0.0

    Replace Program.cs with the complete C# block below, then run dotnet run. FakeTimeProvider comes from Microsoft.Extensions.TimeProvider.Testing, although its namespace is Microsoft.Extensions.Time.Testing. The adapter connects it to MemoryCacheOptions.Clock; merely creating a fake provider would not change the cache's clock. See Microsoft's fake-time guide and the cache clock API.

    The expiration checks use a separate cache per scenario and inspect each key once per time step. The race checks use gates, not timing guesses. The ten-second wait limits are failure diagnostics, not part of the intended ordering or expiration policy.

    C#
    using Microsoft.Extensions.Caching.Memory;
    using Microsoft.Extensions.Internal;
    using Microsoft.Extensions.Time.Testing;
    
    static void Check(bool condition, string message)
    {
        if (!condition) throw new InvalidOperationException(message);
    }
    
    static string Label(bool hit) => hit ? "hit" : "MISS";
    
    // Each row is (minute, expected absolute, expected sliding, expected combined).
    var scenarios = new (int Minute, bool Absolute, bool Sliding, bool Combined)[][]
    {
        new[] { (3, true, true, true), (6, true, true, true),
                (9, true, true, true), (11, false, true, false) },
        new[] { (5, true, false, false) }
    };
    
    foreach (var scenario in scenarios)
    {
        var time = new FakeTimeProvider(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero));
        using var cache = new MemoryCache(new MemoryCacheOptions { Clock = new ClockAdapter(time) });
        var start = time.GetUtcNow();
        cache.Set("absolute", 1, new MemoryCacheEntryOptions { AbsoluteExpiration = start.AddMinutes(10) });
        cache.Set("sliding", 1, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(4) });
        cache.Set("combined", 1, new MemoryCacheEntryOptions
        {
            AbsoluteExpiration = start.AddMinutes(10),
            SlidingExpiration = TimeSpan.FromMinutes(4)
        });
        foreach (var row in scenario)
        {
            time.SetUtcNow(start.AddMinutes(row.Minute));
            bool absolute = cache.TryGetValue("absolute", out _);
            bool sliding = cache.TryGetValue("sliding", out _);
            bool combined = cache.TryGetValue("combined", out _);
            Check(absolute == row.Absolute, $"absolute mismatch at minute {row.Minute}");
            Check(sliding == row.Sliding, $"sliding mismatch at minute {row.Minute}");
            Check(combined == row.Combined, $"combined mismatch at minute {row.Minute}");
            Console.WriteLine($"minute {row.Minute,2}: absolute={Label(absolute),-4} sliding={Label(sliding),-4} combined={Label(combined)}");
        }
        Console.WriteLine();
    }
    
    // Empty cache -> reader captures 100 -> writer stores 120 and removes -> late fill.
    foreach (var design in new ICatalog[] { new NaiveCatalog(), new GenerationCatalog() })
    {
        using (design)
        {
            var captured = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
            var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
            var timeout = TimeSpan.FromSeconds(10);
            var reader = design.ReadAsync(async () =>
            {
                captured.SetResult();
                await resume.Task.WaitAsync(timeout);
            });
            await captured.Task.WaitAsync(timeout);
            design.Write(120);
            Check(design.SourcePrice == 120, "source write must complete before resuming");
            Check(!design.TryCached(out _), "cache must be empty immediately after removal");
            resume.SetResult();
            int readerResult = await reader.WaitAsync(timeout);
            Check(readerResult == 100, "the paused caller must return its captured value");
    
            bool protectedDesign = design is GenerationCatalog;
            bool hasLateFill = design.TryCached(out int lateValue);
            if (protectedDesign)
            {
                Check(!hasLateFill, "old generation must not publish after the local write");
            }
            else
            {
                Check(hasLateFill && lateValue == 100, "naive late fill must repopulate 100");
            }
            int next = await design.ReadAsync(() => Task.CompletedTask);
            Check(next == (protectedDesign ? 120 : 100), "unexpected subsequent read");
            Check(design.TryCached(out int current) && current == next, "expected cached value");
            Console.WriteLine($"{design.GetType().Name,-18} paused reader returned {readerResult}; next read returns {next}  (source={design.SourcePrice})  stale={next != design.SourcePrice}");
        }
    }
    Console.WriteLine("All exercise assertions passed.");
    
    interface ICatalog : IDisposable
    {
        int SourcePrice { get; }
        Task<int> ReadAsync(Func<Task> onCaptured);
        void Write(int price);
        bool TryCached(out int price);
    }
    
    sealed class NaiveCatalog : ICatalog
    {
        readonly MemoryCache cache = new(new MemoryCacheOptions());
        readonly object sourceGate = new();
        int sourcePrice = 100; // In-memory stand-in, not a database transaction.
        public int SourcePrice { get { lock (sourceGate) return sourcePrice; } }
        public bool TryCached(out int price) => cache.TryGetValue("price", out price);
        public async Task<int> ReadAsync(Func<Task> onCaptured)
        {
            if (TryCached(out int hit)) return hit;
            int value = SourcePrice;
            await onCaptured();
            cache.Set("price", value); // Unconditionally publishes the captured value.
            return value;
        }
        public void Write(int price)
        {
            lock (sourceGate) sourcePrice = price;
            cache.Remove("price");
        }
        public void Dispose() => cache.Dispose();
    }
    
    sealed class GenerationCatalog : ICatalog
    {
        readonly MemoryCache cache = new(new MemoryCacheOptions());
        readonly object gate = new();
        int sourcePrice = 100;
        long generation;
        public int SourcePrice { get { lock (gate) return sourcePrice; } }
        public bool TryCached(out int price)
        {
            lock (gate) return cache.TryGetValue("price", out price);
        }
        public async Task<int> ReadAsync(Func<Task> onCaptured)
        {
            long seen;
            int value;
            lock (gate)
            {
                if (cache.TryGetValue("price", out int hit)) return hit;
                seen = generation;
                value = sourcePrice; // Capture source and generation under the same lock.
            }
            await onCaptured(); // Never await while holding the lock.
            lock (gate)
            {
                if (seen == generation) cache.Set("price", value);
            }
            return value; // An overlapping caller can still return its old snapshot.
        }
        public void Write(int price)
        {
            lock (gate)
            {
                // Fail before changing state rather than silently wrapping the generation.
                long nextGeneration = checked(generation + 1);
                sourcePrice = price;
                generation = nextGeneration;
                cache.Remove("price");
            }
        }
        public void Dispose() => cache.Dispose();
    }
    
    sealed class ClockAdapter(TimeProvider time) : ISystemClock
    {
        public DateTimeOffset UtcNow => time.GetUtcNow();
    }

    Expected output

    Text
    minute  3: absolute=hit  sliding=hit  combined=hit
    minute  6: absolute=hit  sliding=hit  combined=hit
    minute  9: absolute=hit  sliding=hit  combined=hit
    minute 11: absolute=MISS sliding=hit  combined=MISS
    
    minute  5: absolute=hit  sliding=MISS combined=MISS
    
    NaiveCatalog       paused reader returned 100; next read returns 100  (source=120)  stale=True
    GenerationCatalog  paused reader returned 100; next read returns 120  (source=120)  stale=False
    All exercise assertions passed.

    What the assertions are designed to check

    • Expiration: the main table and the first-lookup-at-minute-5 case match the predictions. Each result is checked, not merely printed. This is not an exact-deadline boundary test or a test of physical cleanup timing.
    • Naive late fill: removal leaves the cache empty, but the paused reader subsequently inserts 100. The next read returns 100 even though the source contains 120. Removal did not fail; a later insertion undid it.
    • Protected late fill: the paused reader still returns 100, but the cache remains empty after it finishes. The next read loads and caches 120. Checking the empty cache before that read distinguishes rejected publication from an accidental later repair.

    Why the local generation check works, and where it stops

    In GenerationCatalog, source state, generation capture, source updates, invalidation, cache hits and conditional publication all use the same instance's lock. For an older capture, publication either happens before the writer's critical section and is then removed, or happens afterward and is rejected because the generation changed. The comparison and insertion must stay together; checking and then releasing the lock before insertion reopens the race. Source access is also synchronized rather than relying on unsynchronized reads of a shared field. See Microsoft's lock reference.

    This reasoning assumes all writes use this catalog instance and its private source state, with no disposal during active operations. The harness deliberately selects one schedule with one writer; it is not a stress test or an exhaustive concurrency proof. Its source is an in-memory integer, so “write complete” means completion of Write, not a real database commit. A read overlapping a write can still return the old captured value even when stale cache publication is prevented. The protocol is neither a fresh-read guarantee for every overlapping request nor single-flight coordination for simultaneous misses.

    Do not transplant the lock around asynchronous database I/O. A real source needs a protocol that connects committed data versions and visibility to cache publication, including writes from other processes. A Redis script or conditional cache operation can coordinate cache-side state, but by itself cannot make an independent database commit atomic with that state. Generation-keyed entries likewise need a trustworthy current-generation selection rule. Distributed failure, retries, replica lag and process restarts need separate treatment. Microsoft's cache-aside guidance explains why cache-aside alone does not guarantee source/cache consistency.

    Entry lifetime and data age

    Expiration is a policy for how long a cached value may survive before it is treated as invalid. Absolute expiration says, “stop serving this entry after its deadline.” Sliding expiration says, “keep this item alive while it is being used, but let it die if nobody touches it for a while.”

    That distinction matters because the cache is almost never the authoritative store. In a product catalog, the database still owns the truth about product name, price, and publish state. The cache only reduces read latency. If a product is renamed, the write path must update the source of truth first and then invalidate or refresh the cache. Even then, a concurrent reader may observe a stale entry for a brief moment.

    A simple mental model is this:

    Text
    read path -> cache hit? use value -> cache miss? load from source -> store in cache
    write path -> persist change -> invalidate or replace cache entry

    The problem is that these steps are not atomic across threads, and they are definitely not atomic across multiple app servers or a distributed cache.

    Choose expiration and coordinate writes

    Absolute expiration sets an upper bound on an individual entry's cache lifetime. If a catalog entry must expire within five minutes of being inserted, frequent reads do not extend that deadline. This does not by itself guarantee that the underlying data is at most five minutes stale: a delayed fill, stale replica or older snapshot can insert already stale data. Business freshness requirements may also need version checks or reads from an authoritative store. Sliding expiration is best when you want frequently accessed data to stay warm and cold data to evaporate. It is a throughput optimization, not a freshness guarantee.

    A useful rule of thumb:

    • Use absolute expiration when you need a predictable maximum lifetime.
    • Use sliding expiration when access frequency is a good proxy for usefulness.
    • Often use both together to get a practical cap plus activity-based renewal.

    In practice, the combination is common: sliding keeps hot items alive, while absolute prevents them from surviving forever.

    Why invalidation races happen

    Suppose a product price changes from 100 to 120.

    1. The cache contains the old price.
    2. Request B commits the new price to the database.
    3. Before B deletes the cache key, request C reads the old cached price.
    4. B deletes the key, and a later request D misses and reloads the new price.

    This is an invalidation race: the cache entry is logically stale after the write, but some readers can still see it in the gap between persistence and invalidation, or they can rebuild it from an older snapshot before the new value is fully visible.

    The key idea is that cache invalidation reduces the stale window; it does not magically eliminate it. A cache entry is only as fresh as the coordination around it.

    A successful deletion on the same strongly consistent cache is different from a pending invalidation: a later read cannot hit the deleted entry unless another fill repopulates it. A stale result after a completed deletion needs an explicit cause, such as an in-flight fill that read an older database snapshot before the write, or a separate stale cache replica. Keep these timelines distinct.

    Timeline example

    Imagine a product catalog page with a cached entry for product SKU-42.

    Text
    T0  cache contains price=100
    T1  writer updates DB price to 120
    T2  reader A hits cache and sees 100
    T3  writer invalidates cache
    T4  reader B misses cache and reloads 120

    At T2, the cached value was already stale from a business perspective, even though it was still technically present. That is the stale-data window.

    Choosing the right strategy

    If the data changes rarely and read traffic is heavy, absolute expiration may be enough, especially with explicit invalidation on writes. Sliding expiration removes idle entries, but frequent reads can keep a hot entry eligible indefinitely. Combine it with an absolute expiration when you need a maximum cache lifetime. If a decision requires current authoritative data, a short TTL is not enough. Read the authoritative state or use a consistency protocol whose guarantees meet that decision. Treat any tolerated stale interval as an explicit business choice.

    Be careful with these assumptions:

    • A shorter expiration does not guarantee zero staleness.
    • A sliding timeout can keep very hot stale data around longer than expected if invalidation is delayed.
    • Distributed cache APIs generally provide storage and retrieval, not distributed locking.
    • In-process cache and distributed cache have very different failure and visibility characteristics.

    Interview drill

    MCQ 1: Which expiration strategy best limits the maximum time a value can remain cached, even if it is read constantly?

    • A. Sliding expiration only
    • B. Absolute expiration only
    • C. No expiration
    • D. Random expiration

    Correct answer: B. Absolute expiration sets a fixed lifetime ceiling. Sliding expiration can extend life on every read.

    MCQ 2: A writer has committed a new value to the database but has not yet deleted the old cache entry. Why can a concurrent reader still return the old value?

    • A. Because invalidation is always slower than reads
    • B. Because the reader can hit the old cache entry during the gap before deletion
    • C. Because cache entries cannot be deleted
    • D. Because databases automatically repopulate the cache

    Correct answer: B. The read and write operations are not synchronized as one atomic action.

    MCQ 3: Which statement is most accurate about caching in a backend system?

    • A. The cache should be treated as the source of truth
    • B. Authorization checks can be skipped if the cache is warm
    • C. The cache is an optimization and the authoritative store still matters
    • D. Sliding expiration guarantees fresh data

    Correct answer: C. Caching improves performance, but it does not replace correctness checks or ownership of truth.

    Failure modes

    1. Too-long absolute expiration: stale catalog data survives longer than business tolerates.
    2. Overreliance on sliding expiration: hot but obsolete entries stay alive because they keep getting read.
    3. Write-then-invalidate gap: after the database commit but before cache deletion, a concurrent reader can still hit the old entry.
    4. Read-then-write race: a late cache fill writes old data after the database has already been updated.
    5. Confusing in-process with distributed caching: local memory cache and shared cache have different visibility, eviction, and coordination behavior.

    The practical fix is usually a combination of shorter lifetimes, explicit invalidation, versioned keys, and clear acceptance of a small stale window when absolute freshness is not feasible.

    Worked exercises: deadlines and stale refills

    With IMemoryCache, deadline correctness is different from immediate physical reclamation. Expired entries must not be served on lookup; cache activity can trigger cleanup. Do not test correctness by waiting for an eviction callback. Microsoft: memory-cache behavior.

    1. Predict hit or miss

    Consider three independent entries inserted at minute 0: absolute-only with a deadline at minute 10; sliding-only with a four-minute idle limit; and combined with both limits. Look up each at minutes 3, 6, 9 and 11. Assume no eviction, removal, replacement or refill; a miss leaves the entry absent.

    1. Minutes 3, 6 and 9: all three hit. Each successful access is three minutes after the previous one, so the sliding deadline moves to minutes 7, 10 and 13.
    2. Minute 11: absolute-only and combined miss because their fixed deadline was minute 10. Sliding-only hits because the last successful access was at minute 9.
    3. Practice: instead, suppose the first lookup after insertion is at minute 5. Answer: absolute-only hits; sliding-only and combined miss because they were idle for more than four minutes.

    These are predictions under the stated rules. To test an implementation, control time and assert lookup results; do not infer expiry from callback timing.

    Next, trace the stale-refill case. Reader A captures the old source value and pauses before cache insertion. Writer B commits the new value and removes the old cache entry. A then resumes and inserts its captured old value. A completed removal cannot prevent a later insertion. This is different from the existing timeline, where the stale read happens before removal.

    2. Diagnose the late fill

    Use the existing prices: A captures 100; B commits 120 and removes the cache entry; A then publishes its captured 100. The next cache hit returns 100. Question: did removal fail? Answer: no. The stale value came from a later insertion.

    Design target: no stale generation may become the current cached generation after the corresponding local write completes. A proposed fix must coordinate the generation check and publication; checking a version and then inserting outside the coordinated operation reopens the race. A schema prefix such as v1 is not a data-generation protocol.

    Implementation exercise: assert the hit/miss sequence and force the order of capture, commit, removal and late fill. For a proposed protected design, assert its generation invariant too. Multiple processes, replicas and real database commit visibility require their own protocol; the paper exercise proves no distributed consistency property. Microsoft: cache-aside consistency considerations.

    Optional reading: Cache correctness companion note. The worked exercises above are self-contained.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·