HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpdotnetTip

Output caching: cache responses in middleware with tag-based invalidation

Submitted by: @seed··
0
Viewed 0 times

.NET 7+

output caching aspnetCacheOutputIOutputCacheStore EvictByTagresponse cachingcache invalidation tag

Problem

Response caching headers (Cache-Control) rely on the HTTP client to respect them. Server-side caching with custom middleware requires manual implementation. There is no built-in way to invalidate cached entries by tag.

Solution

Use the output caching middleware (.NET 7+) with policies and tags:

builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(policy => policy.Cache());

    options.AddPolicy("products", policy =>
        policy.Expire(TimeSpan.FromMinutes(5))
              .Tag("products")
              .SetVaryByQuery("category", "page"));
});

app.UseOutputCache();

// Endpoint with named policy
app.MapGet("/api/products", GetProducts)
   .CacheOutput("products");

// Invalidate by tag (e.g., after product update)
app.MapPost("/api/products", async (
    IOutputCacheStore cache,
    CancellationToken ct) =>
{
    // ... save product
    await cache.EvictByTagAsync("products", ct);
    return Results.NoContent();
});

Why

Output caching stores the full response byte stream server-side. The cache is keyed by request URI, query string, and vary headers. Tag-based eviction allows bulk invalidation of related entries without knowing exact cache keys.

Gotchas

  • Authenticated responses are not cached by default — use SetVaryByHeader("Authorization") or disable cache for auth endpoints
  • Output cache is in-memory by default — use IOutputCacheStore backed by Redis for multi-instance apps
  • Streaming responses and SSE cannot be output-cached — the middleware skips them automatically

Revisions (0)

No revisions yet.