ASP.NET Core Output Caching: Faster APIs with Safe Cache Policies

ASP.NET Core Output Caching: Faster APIs with Safe Cache Policies

When an ASP.NET Core application generates the same response repeatedly, every request may trigger unnecessary database queries, remote service calls, and server-side processing. Public catalogs, documentation pages, news feeds, and other mostly read-only resources are often good candidates for caching. Instead of rebuilding the response for every request, the application can reuse a previously generated result for a controlled period.

Output Caching, introduced in ASP.NET Core 7, provides server-controlled caching for HTTP responses. Unlike response caching, which follows client and intermediary cache instructions, output caching lets the application define policies for expiration, variation, storage, locking, and invalidation.

Output caching versus response caching

Response caching is based on HTTP caching semantics and headers such as Cache-Control. This is useful when the client, browser, or proxy should participate in caching decisions. However, a client can send Cache-Control: no-cache, which may require the server to generate a fresh response.

Output caching is configured by the server. The client cannot override the server policy in the same way, which makes it more suitable when the primary goal is to reduce origin-server work. It also supports extensible storage, programmatic eviction, and resource locking. Locking helps prevent many concurrent requests from rebuilding the same missing cache entry at once.

Register the output cache services

Start by registering the service and adding the middleware to the request pipeline:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache();

var app = builder.Build();

app.UseOutputCache();

app.MapGet("/catalog", () =>
{
    return Results.Ok(new
    {
        GeneratedAt = DateTimeOffset.UtcNow,
        Items = new[] { "Keyboard", "Monitor", "Mouse" }
    });
}).CacheOutput();

app.Run();

AddOutputCache registers the required services, while UseOutputCache adds the middleware. These calls do not automatically cache every endpoint. You must opt an endpoint into caching with CacheOutput, apply the OutputCache attribute to a controller action or Razor Page, or select a named policy.

Define expiration and variation rules

A single expiration value rarely fits an entire application. A product catalog may tolerate several minutes of staleness, while inventory, account information, or rapidly changing prices may require a shorter lifetime or no output caching at all.

builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("PublicCatalog", policy => policy
        .Expire(TimeSpan.FromMinutes(2))
        .SetVaryByQuery("category", "pageSize"));
});

Apply the policy to an endpoint:

app.MapGet("/catalog", (string? category, int pageSize = 20) =>
{
    return Results.Ok(new { category, pageSize });
})
.CacheOutput("PublicCatalog");

Cache-key design is one of the most important parts of the configuration. By default, the scheme, host, port, path, and query string contribute to the cache key. If only specific query parameters change the response, explicitly selecting those parameters can prevent unnecessary cache fragmentation.

For example, if culture is the only query value that affects a localized response, a policy can vary by culture rather than by unrelated tracking parameters. Do not remove a query parameter from the variation rules unless you have verified that it cannot affect the response. Otherwise, a response generated for one request may be served to another request incorrectly.

Protect personalized and confidential responses

The most important safety rule is simple: do not treat personalized or authorization-dependent data as public content. User profiles, account balances, order history, administration screens, and responses affected by authentication state should normally remain outside output caching.

builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("PublicOnly", policy => policy
        .Expire(TimeSpan.FromSeconds(60))
        .With(context =>
        {
            var request = context.HttpContext.Request;
            return HttpMethods.IsGet(request.Method)
                && !request.Headers.ContainsKey("Authorization");
        }));
});

This example is only one layer of protection. Review cookies, tenant identifiers, custom headers, authentication middleware, and endpoint behavior as well. A safer architecture is to group public, cacheable endpoints under a clearly defined route area and apply policies only there.

If a default policy is used, add tests proving that private actions are not cached. A cache bug involving user-specific data is not merely a performance issue; it can become a data disclosure incident.

Invalidate related entries with tags

Waiting for the expiration time is not always acceptable. After an administrator updates a product, the application may need to remove catalog responses immediately. Tags allow related cache entries to be grouped:

builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("Catalog", policy => policy
        .Expire(TimeSpan.FromMinutes(5))
        .Tag("catalog"));
});

app.MapGet("/catalog", () => Results.Ok(GetCatalog()))
    .CacheOutput("Catalog");

Tagged entries can be evicted through the registered IOutputCacheStore implementation. Keep in mind that cache eviction is not automatically part of the same database transaction as the data update. The application must therefore be correct even if eviction is delayed or temporarily unavailable. The TTL should remain a safety net that eventually returns the system to fresh data.

Choose storage for the deployment model

The default store uses process-local memory. In a multi-server deployment, each application instance has its own cache, and entries disappear when that process restarts. This may be acceptable for a single server or for endpoints where duplicate warming is harmless.

When several nodes need to share cached responses, a distributed store such as Redis can be evaluated. Microsoft provides an output-cache integration package for StackExchange.Redis. Before choosing it, test network latency, serialization cost, capacity limits, eviction behavior, access control, and the application’s fallback behavior when the cache is unavailable.

A shared cache does not replace database transactions, consistency rules, or invalidation design. It only changes where cached output is stored and how it is shared between application instances.

Production checklist

  • Cache only safe, repeatable, publicly shareable responses.
  • Review whether authorization, cookies, tenant context, headers, or query values affect the output.
  • Choose expiration based on how quickly the underlying data changes.
  • Provide an operational path for removing incorrect or obsolete entries.
  • Test both single-instance and multi-instance deployments.
  • Monitor cache hits, misses, response latency, memory or Redis usage, and eviction events.
  • Add automated tests for endpoints that must never be cached.

Conclusion

ASP.NET Core Output Caching can substantially reduce the cost of repeatedly generating the same response. The feature is most effective when performance and correctness are designed together. Select suitable endpoints, define a precise cache key, choose a realistic lifetime, protect private data, and plan invalidation before deploying the policy.

In other words, caching is not simply a switch that makes an API faster. It is a contract describing when a response may be reused, for which request variations, and for how long. Treat that contract as part of the application’s behavior and verify it with tests and production metrics.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published