Caching in ASP.NET Core: In-Memory, Distributed, and Response Caching

Master caching in ASP.NET Core: IMemoryCache, IDistributedCache with Redis, HybridCache, response vs output caching, invalidation, and stampede protection.

Executive Summary: Caching in ASP.NET Core is three layers plus one boundary rule: IMemoryCache for fast per-instance storage, IDistributedCache (usually Redis) for storage shared across instances, HybridCache for both behind one API with stampede protection built in, and response or output caching for HTTP-level results. Every cache buys speed with two obligations you sign knowingly: invalidation (stale data is the price of every cache you cannot clear) and key correctness (a per-user value under a shared key is a data leak).

The endpoint that brings teams here is the dashboard. Every visitor triggers the same three aggregate queries, each one a few hundred milliseconds. The database is spending most of its evening answering the identical question. The fix is a cache, and the fix after the fix is always the same three bugs: data that was stale, a key that mixed two users’ data, and a thundering reload at the exact moment the cache expired. This page covers the layers and those three bugs.

Caching in ASP.NET Core means the framework’s four mechanisms: IMemoryCache, IDistributedCache, HybridCache, and the two HTTP-level caches, response caching and output caching, which are different things and get a section each. The memory caching guide, output caching guide, and response caching middleware guide are the official references.

The examples assume .NET SDK 10.0 with ASP.NET Core 10 and continue the TaskApi, where the expensive operation is a project-activity summary that several endpoints read. The prerequisite is honest measurement: the EF Core command logging shown in the query efficiency guide tells you which queries deserve caching before any cache is added.

Watching caches both save and sink services taught me this: a cache is a bet that the past predicts the future. Size the bet, decide what happens when you lose it, and never cache your way out of a query you have not yet read.

The layers, in one table

Mechanism Where it lives Shared across instances? Best for
IMemoryCache Process memory No (per instance) Fast, per-node caching of read-heavy lookups
IDistributedCache Redis or SQL Server Yes Shared values, session-like state, cross-instance invalidation
HybridCache Memory plus distributed Both The default choice: one API, both layers, stampede protection
Response caching Client and proxy caches Everywhere that honors headers Public GET responses controlled by Cache-Control headers
Output caching Server memory or distributed Configurable Caching a whole endpoint’s output, keyed and evicted by policy

IMemoryCache: the in-process workhorse

The memory cache is registered once (a singleton, injectable anywhere per the dependency injection guide), and GetOrCreateAsync is the cache-aside pattern in one call:

builder.Services.AddMemoryCache(options =>
{
    options.SizeLimit = 10_000;          // entries, keeping memory bounded
});
public sealed class SummaryService(IMemoryCache cache)
{
    public async Task<ProjectSummary> GetSummaryAsync(
        Guid projectId, CancellationToken ct)
    {
        return await cache.GetOrCreateAsync(
            $"project-summary:{projectId}",
            entry =>
            {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
                return LoadFromDatabaseAsync(projectId, ct);
            }) ?? throw new InvalidOperationException("Summary load returned null");
    }
}

The absolute expiration is the honest part: data that can tolerate five minutes of staleness gets five minutes, no longer. The SizeLimit is the part people skip and then debug memory pressure. Without a size limit the cache grows as far as the key space allows.

IDistributedCache with Redis

One instance’s memory is invisible to every other instance, so a scaled-out deployment needs a shared tier. Redis is the usual backing store:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
});
// values are bytes: serialize explicitly
var cached = await distributedCache.GetAsync(key, ct);
var summary = cached is null
    ? null
    : JsonSerializer.Deserialize<ProjectSummary>(cached);

if (summary is null)
{
    summary = await LoadFromDatabaseAsync(projectId, ct);
    await distributedCache.SetAsync(
        key,
        JsonSerializer.SerializeToUtf8Bytes(summary),
        new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
        },
        ct);
}

The distributed cache’s contract is visible in the shape: byte arrays, explicit serialization, and no automatic stampede protection. It is the right tool when instances must share values. It is also the lower-level tool, which is why the next section exists.

HybridCache: both layers, one API

HybridCache, available since .NET 9 as a first-class part of the caching stack, is the layer most teams should start with: it checks the process-local memory first, falls back to the distributed cache second, and coordinates both behind a single GetOrCreateAsync that includes stampede protection by default (one request loads a key; the others wait) and tag-based invalidation:

dotnet add package Microsoft.Extensions.Caching.Hybrid
builder.Services.AddHybridCache();

public sealed class SummaryService(HybridCache cache)
{
    public async Task<ProjectSummary> GetSummaryAsync(
        Guid projectId, CancellationToken ct)
    {
        return await cache.GetOrCreateAsync(
            $"project-summary:{projectId}",
            token => LoadFromDatabaseAsync(projectId, token),
            tags: [$"project:{projectId}"],           // for targeted invalidation
            cancellationToken: ct);
    }
}

Read that registration carefully: no distributed store is configured here. So the hybrid cache runs memory-only until you add an IDistributedCache, at which point the same code transparently gains the shared tier. That upgrade path, plus the built-in request coalescing, is the argument for making HybridCache the default and reaching for the raw interfaces only when a special case demands them.

Response caching vs output caching: define both

These two are regularly confused, and they work at different layers. Response caching is the HTTP mechanism: your API sets Cache-Control headers, and clients and proxies decide whether to reuse the response. Output caching is server-side: your own server stores the endpoint’s rendered output and serves it to subsequent requests without executing the endpoint again.

Aspect Response caching Output caching
Where the copy lives Client and proxy caches Your server (memory or distributed)
Who honors it Whoever respects HTTP headers You, always
Works for authenticated user data? Risky: shared proxies must not store private responses Yes, with key policies per user
Declared by [ResponseCache] attribute and header configuration AddOutputCache, UseOutputCache, and per-endpoint policies

On the attribute side (full endpoint patterns in the Web API guide):

[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]
public IActionResult GetActivitySummary(Guid projectId) => /* ... */;
builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("activity", policy => policy
        .Expire(TimeSpan.FromMinutes(2))
        .SetVaryByQuery("projectId"));
});

// in the pipeline, placed per the middleware guide's order rules:
app.UseOutputCache();

[OutputCache(PolicyName = "activity")]
public IActionResult GetActivity(Guid projectId) => /* ... */;

The rule of thumb for choosing between them: response caching for public, cacheable GET endpoints where clients and proxies can help you. Output caching for expensive endpoints whose outputs you want to serve without re-executing, including per-user variants via vary-by rules.

Expiration and invalidation: the two levers

Every cached value leaves in one of two ways: it expires, or something evicts it. Expiration is the passive lever, and TTLs should be as long as the data can tolerate being wrong. Invalidation is the active lever, and it belongs to the write path:

// the write path owns the cache's truth
public async Task RenameProjectAsync(Guid projectId, string newName, CancellationToken ct)
{
    await repository.RenameAsync(projectId, newName, ct);

    // tag invalidation: every summary keyed to this project, any layer
    await cache.RemoveByTagAsync($"project:{projectId}", ct);
}

The pairing that works: reads cache with tags, writes invalidate by tag, and the TTL acts as the safety net when a write path is missed. When invalidation is hard (a value derived from many tables), lean on the TTL and keep it short. This is because a cache you cannot clear is a cache that eventually lies.

Stampedes: when the cache expires under load

A stampede is what happens at the worst moment: the hot key expires, fifty concurrent requests all miss, and all fifty execute the expensive load. HybridCache prevents this by coalescing concurrent loads of the same key into one, which is the main reason to prefer it. When using the raw caches, the defenses are manual:

// illustrative: manual lock, one loader, waiters reuse the winner's result
private static readonly SemaphoreSlim _gate = new(1, 1);

await _gate.WaitAsync(ct);
try
{
    if (!cache.TryGetValue(key, out var value))
    {
        value = await LoadFromDatabaseAsync(projectId, ct);
        cache.Set(key, value, TimeSpan.FromMinutes(5));
    }
    // serve value
}
finally
{
    _gate.Release();
}

The second, cheaper defense is jitter. Vary TTLs by a small random amount (TimeSpan.FromMinutes(5) + Random.Shared.Next(0, 60) seconds) so keys do not expire in synchronized waves after a mass warm-up.

How real systems do this

  • Measurement precedes caching. The query log decides what deserves a cache. The EF Core command logging from the query guide is the evidence. A cache is applied to a named, measured hotspot, not to vibes.
  • HybridCache plus Redis is the standard shape. One API in code, memory for speed, Redis for cross-instance sharing and coordinated invalidation, with per-tag eviction wired to the write paths.
  • Cache metrics watched, not hoped for. Hit rates and load durations are visible, so a cache that stopped helping (or one serving mostly misses) is a chart observation, not a hunch.

A bug I remember well was a stale-cache incident: renaming a project left the old name on dashboards for exactly the TTL, because the read path cached but no write path invalidated. Users reported “the rename didn’t save”, support checked the database, saw the new name, and the ticket bounced between teams for an afternoon. The fix was one tag eviction in the rename handler. The takeaway: users read the cache, not the database, so every write path that changes cached data owns the cache’s truth.

Decision framework: which cache, if any

  1. Did measurement show this read hurts? No: no cache; complexity without evidence. Yes: continue.
  2. How stale can the value be? Zero: do not cache, or cache with immediate invalidation and short TTLs. Minutes: TTL-based caching, the sensible default.
  3. Who must see the same value? One instance: memory is enough. Multiple instances: HybridCache over a distributed store so invalidation reaches everyone.
  4. Is the value per-user or per-tenant? The user or tenant id belongs in the key (and vary-by rules). Or the cache becomes a cross-user data leak.
  5. Cache the data or the HTTP response? Data for shared logic and services. Output caching for whole expensive endpoints; response caching only for public GETs where clients and proxies help.

When NOT to cache

  • When the database is already fine. A query at single-digit milliseconds that runs occasionally does not need a cache. Add one only when measurement says the read costs more than the cache’s complexity.
  • Write-heavy data. Values that change with most requests produce cache misses and invalidation storms. The cache becomes expensive bookkeeping in front of the database.
  • Anything correctness-critical with no invalidation story. If serving a stale value is worse than serving it slowly, and you cannot evict on write, the TTL must be so short the cache barely helps; do not ship it.

Common mistakes

  • No invalidation on the write path. Reads cache, writes forget, users see the old value for the whole TTL. Every write path owns the tags it invalidates.
  • Shared keys for per-user data. One user’s summary served to another is a data leak, not a performance bug. User and tenant ids belong in the key.
  • Unbounded memory cache. Without SizeLimit (and per-entry sizes) the cache grows with the key space. Memory pressure looks mysterious until someone remembers the cache.
  • Caching entities and mutating them. In-memory caches return the same object instance to every caller. One caller’s mutation is the next caller’s surprise. Cache immutable snapshots or records.
  • Sliding-only expiration on hot keys. A busy key with sliding expiration never dies; combine sliding with an absolute cap.
  • Response-cache headers on private data. Proxies and browsers store what headers permit; authenticated responses need no-store defaults and deliberate exceptions.

The patterns here sit on top of general caching theory. My guides on caching in system design, distributed caching, and Redis caching patterns go deeper on eviction and invalidation.

Key takeaways

  • ASP.NET Core offers three data layers (IMemoryCache, IDistributedCache, HybridCache) and two HTTP layers (response caching, output caching); response caching sets headers clients honor, output caching stores your server’s rendered output.
  • HybridCache, available since .NET 9, is the default: memory plus optional distributed tier, one GetOrCreateAsync, stampede coalescing, and tag-based invalidation.
  • TTLs are set by the staleness the business tolerates; invalidation belongs to the write path, with tags making eviction precise.
  • Stampedes happen when a hot key expires under load. HybridCache coalesces by default, and manual locks plus TTL jitter are the fix on the raw caches.
  • Per-user and per-tenant values require per-user keys; a shared key is a data leak with extra throughput.
  • Cache what measurement proved expensive, never as a substitute for reading the SQL, and bound the memory cache with a size limit.

FAQ

What is IMemoryCache in ASP.NET Core?

An in-process key-value cache for storing data inside a single application instance, registered once and injected anywhere. Values are live .NET objects, access is near-instant, and entries expire by absolute or sliding time. Because it is per-instance, other servers never see it, which is fine for single-instance apps and the reason distributed caches exist.

What is the difference between response caching and output caching?

Response caching is HTTP: your API sets Cache-Control headers and the browser, proxies, or clients decide whether to reuse the response without calling you again. Output caching is server-side: your server stores the endpoint’s rendered output and serves it to later requests without executing the endpoint. Response caching helps everyone downstream; output caching helps your server’s CPU and dependencies.

What is HybridCache in .NET?

A caching abstraction added to the .NET caching stack that layers an in-process memory cache over an optional distributed cache behind one GetOrCreateAsync call. It coalesces concurrent loads of the same key (built-in stampede protection), serializes values for the distributed tier, and supports tag-based invalidation, making it the practical default over hand-rolling the two layers.

How do I invalidate a cache entry when data changes?

Wire eviction into the write path: when a project is renamed, remove or overwrite the cached entries for that project, preferably by tag with HybridCache so every related key goes at once. The TTL is the safety net for missed paths, not the invalidation strategy itself.

What is a cache stampede?

A thundering reload that happens when a popular cache entry expires under load: many requests miss simultaneously. Each one executes the expensive query behind the cache, hammering the database in a burst. HybridCache prevents it by letting only one request load the key while others wait. Manual locks or TTL jitter are the countermeasures on the lower-level caches.

Cache the reads, own the writes

Caching is a measured trade: milliseconds of latency bought with staleness, invalidation work, and one more moving part. Start with the read the query log proves expensive, put HybridCache in front of it with a realistic TTL and tags. Let every write path own the truth of what it changes. Keep keys honest per user, keep memory bounded, and treat an unexplainable cache as a bug, not a mystery. Next: dockerizing a .NET application moves the series toward deployment, and every guide lives on the .NET series index. The rule of thumb: a cache is correct exactly as long as its invalidation is, so write the eviction before you write the read.

Last updated on 27 November 2026

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *