📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Why do we cache in a .NET service, and what are the main caching layers: in-memory, distributed and HTTP/CDN? How does IMemoryCache work, and why should you set a size limit on it?

The purpose of caching, the in-process, distributed and HTTP/CDN layers, IMemoryCache basics (expiration, eviction, GetOrCreateAsync) and why SizeLimit matters.

Junior Theory Beginner aspnet-core caching cdn http-caching imemorycache performance

🎯 Key points

  • Caching trades freshness and memory for latency and less load on the source of truth
  • Layers: in-process (IMemoryCache, ~nanoseconds), distributed (Redis, ~0.5-2 ms), HTTP/CDN (Cache-Control, edge)
  • IMemoryCache is per instance: pods hold different copies, so it suits data where brief inconsistency is acceptable
  • IMemoryCache stores references: cache immutable objects or every caller sees mutations
  • Absolute vs sliding expiration; use absolute (or both) so hot entries still refresh
  • SizeLimit plus Size per entry bounds memory; without it the cache can grow until OOM
  • Measure hit ratio and source latency before and after; only cache what is read often and changes rarely

⏱ 30-second answer

We cache to avoid repeating expensive work: a database query, a remote call or a computation whose result is read far more often than it changes. There are three common layers:

  • In-process (IMemoryCache): lowest latency, but per instance, so pods can disagree, and lost on restart.
  • Distributed (IDistributedCache over Redis): shared by all instances, a network hop away.
  • HTTP/CDN: Cache-Control headers let browsers, proxies and edge nodes serve responses without hitting the app.

IMemoryCache holds references to the cached objects (so mutating one changes it for every caller), with absolute or sliding expiration. By default it is unbounded, so I set SizeLimit, give every entry a Size, and watch the hit ratio. The trade-off is always freshness and memory versus latency and load.

🗣 Full answer (senior)

How I would answer this in an interview

"Caching means keeping a copy of a result closer to where it's needed so you don't pay to produce it again. It's worth it when data is read much more often than it changes and producing it is slow or expensive: a 40 ms database query, a call to a partner API with a rate limit, or a price calculation. What you give up is freshness, because the copy can be out of date, and memory.

In .NET I think in layers. The closest is in-process memory with IMemoryCache: a lookup is a dictionary read, so it's nanoseconds, but each instance has its own copy, so three pods can hold three different versions and it all disappears on a restart. Next is a distributed cache such as Redis behind IDistributedCache: every instance sees the same value and it survives deployments, but each read is a network round trip of roughly half a millisecond to a couple of milliseconds plus serialisation. Furthest out is HTTP caching: Cache-Control headers let the browser or a CDN like Azure Front Door answer without the request reaching us at all.

The mistake I see is treating IMemoryCache as free. It's unbounded by default, so a cache keyed by user or search term just grows until the process runs out of memory. I set SizeLimit and a Size on every entry, always use an absolute expiration, and watch the hit ratio. A cache with a 10% hit ratio is just a memory leak with extra steps."


The layers compared

Layer Typical latency Shared across instances Survives restart Good for
IMemoryCache ~50-100 ns No No Reference data, config, hot lookups
Distributed (Redis) ~0.5-2 ms in the same region Yes Yes Session-like data, shared results, rate limits
HTTP/CDN 0 ms to the app (served at the edge) Yes (per edge node) Yes Public, cacheable GET responses, static assets
HybridCache (.NET 9+ library) L1 hit = memory, miss = L2 L2 yes L2 yes Most new code: both layers plus stampede protection

IMemoryCache essentials

Option What it does Watch out for
AbsoluteExpirationRelativeToNow Entry expires a fixed time after it was set Pick from how stale the data may be
SlidingExpiration Expires if not read for the period Hot entries never refresh on their own; combine with absolute
Size + SizeLimit Bounds the total "units" in the cache Once SizeLimit is set, every entry must have a Size or Set throws
Priority Order of eviction during compaction NeverRemove entries are never evicted by compaction
GetOrCreateAsync Read-through helper Not stampede-safe: concurrent misses all run the factory

When not to cache

  • Data that must be exactly current (account balances, stock you are about to sell).
  • Data per user that is rarely re-read (the hit ratio will be low).
  • Anything sensitive in a shared layer without the user in the key (see the stale or other users' data question).

Production example

A product-catalogue API read the same 2,000 category rows on every request at about 35 ms each. Caching them in IMemoryCache for 5 minutes with a SizeLimit brought the endpoint's p95 from 120 ms to 70 ms and cut database CPU by about 30%, with a measured hit ratio of 99.6%.

🔍 What the interviewer is checking

Checks that the candidate understands what caching buys and costs, knows the layers and their latency, and can use IMemoryCache safely.

Green flags

  • Explains the freshness versus latency trade-off and the read/write ratio
  • Knows IMemoryCache is per instance and unbounded by default
  • Mentions SizeLimit, Size, absolute versus sliding expiration
  • Talks about measuring hit ratio

Red flags

  • "Cache everything" with no expiration
  • Thinks in-memory cache is shared across servers
  • No idea how stale data or memory growth would show up

📚 Learn in depth

1. Why caching works

Caching exploits locality: a small set of keys gets most of the reads (often an 80/20 or steeper distribution). If a read costs C_source and a cache hit costs C_cache, the average cost is:

avg = hitRatio * C_cache + (1 - hitRatio) * (C_cache + C_source)

With a 95% hit ratio, a 1 ms Redis read and a 40 ms query, the average falls from 40 ms to about 3 ms. With a 30% hit ratio it barely moves, and you have added a moving part.

2. Where each layer sits

Browser cache -> CDN / Front Door -> Load balancer -> App instance
                                                   |-> IMemoryCache (L1, per pod)
                                                   |-> Redis (L2, shared)
                                                   \-> SQL Server (source of truth)

The closer the layer is to the user, the faster and cheaper the hit, and the harder it is to invalidate. Choosing a per-instance layer is an architecture decision: it is only safe for data where two pods briefly returning different values is acceptable.

3. How MemoryCache is implemented

MemoryCache (in Microsoft.Extensions.Caching.Memory) is built on a ConcurrentDictionary<object, CacheEntry>, so concurrent reads and writes from many request threads are thread-safe without a global lock. That safety covers the dictionary, not your objects: it stores references, so a cached object is shared by every caller, and if one caller mutates it everyone sees the change (and may see it half-done). Cache immutable records. Note also that GetOrCreate/GetOrCreateAsync are not atomic: two threads that miss at the same time both run the factory.

Expired entries are removed lazily on access and by a periodic scan (ExpirationScanFrequency, default 1 minute). There is no automatic eviction just because the process is short of memory: compaction happens when SizeLimit would be exceeded or when you call Compact(percentage).

4. Size limits

SizeLimit has no unit; you decide what a unit means (one entry, approximate KB). When adding an entry would exceed the limit, the cache refuses the new entry and schedules a compaction that removes expired entries, then by priority, then least recently used. Register a dedicated, bounded instance for large or user-driven data instead of sharing the framework's default one.

5. Expiration choices

  • Absolute: predictable staleness bound.
  • Sliding: keeps hot entries forever unless combined with absolute.
  • Change tokens: expire when a file, CancellationTokenSource or config changes.

6. Measuring it

Turn on TrackStatistics and publish hits, misses and entry count as metrics. If the hit ratio is low, shorten the key space or stop caching; if memory climbs, lower SizeLimit or expiry.

Try it yourself

  1. Cache a slow (50 ms) lookup with GetOrCreateAsync and measure with BenchmarkDotNet or a simple k6 run before and after.
  2. Set SizeLimit = 100 and add 200 entries with Size = 1; observe which survive after compaction.
  3. Use MemoryCacheStatistics (TrackStatistics = true, GetCurrentStatistics()) to log hit ratio and entry count.
  4. Mutate a cached object from one request and read it in another to see the shared-reference problem.
  5. Add Cache-Control: public, max-age=60 to a GET endpoint and watch the browser serve it from disk cache.

💻 Code

A bounded IMemoryCache for a reference-data lookup, with statistics so you can measure the hit ratio.

using Microsoft.Extensions.Caching.Memory;

namespace Catalogue.Caching;

public sealed record Category(int Id, string Name);

public interface ICategoryRepository
{
    Task<IReadOnlyList<Category>> GetAllAsync(CancellationToken ct);
}

public sealed class CategoryCache(IMemoryCache cache, ICategoryRepository repository)
{
    private const string Key = "categories:all:v1";

    public async Task<IReadOnlyList<Category>> GetAllAsync(CancellationToken ct)
    {
        // GetOrCreateAsync is fine for cheap, low-contention data;
        // concurrent misses may each call the repository (no stampede protection).
        var categories = await cache.GetOrCreateAsync(Key, async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); // staleness bound
            entry.Size = 1;                                                   // required once SizeLimit is set
            return await repository.GetAllAsync(ct);
        });

        return categories ?? [];
    }
}
// Program.cs
builder.Services.AddMemoryCache(options =>
{
    options.SizeLimit = 10_000;        // units are yours: here, one per entry
    options.TrackStatistics = true;    // enables GetCurrentStatistics() for hit-ratio metrics
});
builder.Services.AddSingleton<CategoryCache>();

⚠ Common mistakes

  • Mistake: Adding a cache without measuring first. Why it is wrong: If the source is already fast or the hit ratio will be low, you add staleness and complexity for nothing. Instead: Measure source latency and read/write ratio, then verify the hit ratio after.
  • Mistake: Micro-optimising cold paths by caching rarely called endpoints. Why it is wrong: The entries expire before they are reused, so you pay memory and get no benefit. Instead: Cache the hot keys a profile or Application Insights shows.
  • Mistake: Leaving IMemoryCache unbounded with user-driven keys. Why it is wrong: Memory grows until the pod is OOM-killed. Instead: Set SizeLimit, give each entry a Size, and always set an absolute expiration.
  • Mistake: Using only sliding expiration. Why it is wrong: A key read every few seconds never expires, so it never refreshes. Instead: Combine sliding with an absolute cap.
  • Mistake: Mutating an object after reading it from IMemoryCache. Why it is wrong: The cache holds a reference, so every caller sees the change. Instead: Cache immutable records or copies.
  • Mistake: Assuming IMemoryCache is consistent across instances. Why it is wrong: Each pod has its own copy; users can see different values depending on the pod. Instead: Use a distributed cache or HybridCache when consistency across instances matters.
  • Mistake: Caching personal data in a shared layer without the user in the key, or for longer than needed. Why it is wrong: One user can be served another user's data, which is a likely eligible data breach under the Privacy Act 1988's Notifiable Data Breaches scheme, and APP 11 requires reasonable steps to protect personal information wherever it is stored, caches included. Instead: Scope keys to the user or tenant, keep lifetimes short, or don't cache it.

🏛 Senior insight: trade-offs

Even at junior level, the strong answer is about when to cache: the read/write ratio, how stale the data may be, and how you'll know it's working (hit ratio, source latency, memory). For new code in .NET 9 and 10, Microsoft recommends HybridCache (Microsoft.Extensions.Caching.Hybrid, GA March 2025): one GetOrCreateAsync call that uses an in-process cache first and a distributed cache (such as Redis) second, and makes concurrent misses for the same key share one call to the source. That removes the hand-written "check memory, check Redis, query, write both" code and its stampede bug, so I'd start there rather than combining IMemoryCache and IDistributedCache by hand.

Option When it fits Cost When not to
IMemoryCache Small, per-instance reference data Memory per pod, inconsistency between pods Data that must agree across instances
Redis via IDistributedCache Shared data, survives deploys Network hop, serialisation, another service to run Tiny hot lookups called thousands of times per request
HybridCache Most new application caching A NuGet package and configuration When you need raw Redis structures (sorted sets, streams)
HTTP/CDN Public GET responses Hard to invalidate; must vary correctly Personalised or authenticated responses

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions HTTP or output caching Why: Checks they can separate response caching, output caching and compression in ASP.NET Core
    How to answer

    They solve different problems:

    • Response compression makes responses smaller (Brotli or Gzip). It helps large text payloads on slow networks but costs CPU per response. Over HTTPS it's off by default because of BREACH-style attacks, and is often better done at a proxy or CDN.
    • Output caching (AddOutputCache, .NET 7+) stores the whole response on the server and replays it without running the endpoint. The app controls the policy: expiry, vary-by, tags for eviction, and stampede-preventing locking.
    • Response caching middleware follows HTTP Cache-Control rules, so clients can bypass it; its headers mainly matter for browser and CDN caching.

    For server-side caching of API responses I choose output caching. The trade-off is freshness: anything cached can be stale until it expires or is evicted.

  2. When: Candidate mentions eviction or least recently used Why: Checks they understand how an LRU cache is built from a dictionary and a linked list
    How to answer

    LinkedList<T> is a doubly linked list of LinkedListNode<T> objects, each with Value, Next, Previous and List. Given a node, AddBefore, AddAfter, Remove(node), AddFirst and AddLast are O(1). But finding a node by value (Find, Remove(value), Contains) is O(n), there is no indexer, every element is a separate heap object (about 48 bytes for an int on 64-bit), and walking it misses the CPU cache. So List<T> is faster for almost everything. Use LinkedList<T> when you already hold node references and need O(1) reordering, the classic case being an LRU cache: Dictionary<TKey, LinkedListNode<Entry>> plus a LinkedList<Entry> ordered by recent use.

  3. When: Candidate registers a cache service in DI Why: Checks they choose the right lifetime for a cache and its dependencies
    How to answer

    I choose by state and thread safety, then check dependencies:

    1. Does it hold per-unit-of-work state (a change tracker, the current user)? → scoped.
    2. Is it shared, thread-safe and worth building once (a cache, a client pool, compiled config)? → singleton.
    3. Stateless and cheap? → transient (or singleton if every dependency is a singleton).
    4. A service can't outlive its shortest-lived dependency.

    So: DbContext is scoped (not thread-safe, one unit of work), or created per operation with IDbContextFactory<T> outside requests. HttpClient comes from IHttpClientFactory (pooled handlers, DNS refresh) or is one singleton with PooledConnectionLifetime. IMemoryCache is a singleton. The trade-off is sharing versus safety: wider lifetimes save allocations but demand thread safety and stricter dependencies.

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me