LESSON 16 OF 18

16. Caching and HTTP Cache-Control Strategies

This lesson applies output caching, Cache-Control, ETag, conditional requests, and cache invalidation to frequently read Product and Category endpoints in ASP.NET Core .NET 10.

50 dk 80

Introduction

An API’s performance is not determined only by how quickly a database query executes. If the same product or category list is requested hundreds of times within a short period, executing the same query for every request wastes CPU, memory, database connections, and network bandwidth. Caching reduces this cost by reusing a previously generated response for an appropriate period.

In this lesson, we will distinguish two caching approaches in ASP.NET Core and .NET 10. Output caching stores endpoint output on the server and can return the same response without executing the endpoint again. HTTP caching communicates how clients and intermediary proxies may store and validate a response through Cache-Control, ETag, and conditional request headers.

Our examples target public, frequently read endpoints such as GET /api/products and GET /api/categories. We will not apply the same policy to user-specific, authorization-dependent, or highly volatile data.

1. Deciding whether to cache

Before caching an endpoint, answer these questions:

  • Is the response identical for all clients, or does it vary by user?
  • How frequently does the data change?
  • Is a short period of staleness acceptable?
  • Are the response size and possible cache-key count controlled?
  • Must the cache be invalidated immediately when the data changes?

For anonymous catalog data such as products or categories, a lifetime between 30 and 120 seconds may be reasonable. A fixed lifetime is usually inappropriate for inventory, price, promotional, order-status, or user-specific recommendation endpoints. Cache duration is a technical assumption that must be agreed with the business requirements.

2. Enabling output caching

In .NET 10, register AddOutputCache in the service collection and UseOutputCache in the HTTP pipeline. These calls make output caching available, but they do not automatically cache every endpoint. A policy must be applied to an endpoint.

var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddOutputCache(options => {    options.AddPolicy("Catalog", policy => policy        .Expire(TimeSpan.FromSeconds(60))        .Tag("catalog")); }); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.UseOutputCache(); app.MapControllers(); app.Run();

In applications that use authentication and authorization, place UseOutputCache after those middleware components. This reduces the risk of serving content generated for an authenticated user to another client. Even for public catalog endpoints, keeping this order makes the pipeline safer when authorization rules are added later.

3. Applying a policy to controller endpoints

We will preserve the layered design used in previous lessons. Controllers will not access the database directly. They will request DTOs from application services, while output caching will be applied at the endpoint level.

using Microsoft.AspNetCore.OutputCaching; [ApiController] [Route("api/products")] public sealed class ProductsController : ControllerBase {    private readonly IProductService productService;    public ProductsController(IProductService productService)    {        this.productService = productService;    }    [HttpGet]    [OutputCache(PolicyName = "Catalog")]    public async Task<ActionResult<IReadOnlyList<ProductListItemDto>>> GetAll(        CancellationToken cancellationToken)    {        var products = await productService.GetListAsync(cancellationToken);        return Ok(products);    } } [ApiController] [Route("api/categories")] public sealed class CategoriesController : ControllerBase {    private readonly ICategoryService categoryService;    public CategoriesController(ICategoryService categoryService)    {        this.categoryService = categoryService;    }    [HttpGet]    [OutputCache(PolicyName = "Catalog")]    public async Task<ActionResult<IReadOnlyList<CategoryDto>>> GetAll(        CancellationToken cancellationToken)    {        var categories = await categoryService.GetListAsync(cancellationToken);        return Ok(categories);    } }

Default output-caching rules target successful GET and HEAD responses. Responses that set cookies or are associated with authenticated requests are excluded by default. Therefore, do not apply a general public catalog policy to endpoints that return data based on an Authorization header or a user identity.

4. Query strings and cache keys

List endpoints commonly accept pagination, filtering, sorting, and searching parameters. Different queries under the same path must not share the same cache entry. For example, /api/products?categoryId=2 and /api/products?categoryId=5 produce different responses.

builder.Services.AddOutputCache(options => {    options.AddPolicy("CatalogList", policy => policy        .Expire(TimeSpan.FromSeconds(60))        .SetVaryByQuery("page", "pageSize", "categoryId", "sort", "search")        .Tag("catalog")); });

Include only parameters that actually affect the response and are supported by the API. Adding unused or unbounded parameters to the cache key reduces the hit rate and can create excessive cache entries. Enforce a maximum page size so that malformed or hostile requests cannot generate an uncontrolled number of large entries.

5. Cache-Control headers

Output caching controls whether the server can reuse a response. Cache-Control tells clients and intermediary caches how the response may be stored. For example, the following header indicates that a response can be reused by shared caches for 60 seconds:

Cache-Control: public, max-age=60

public allows shared caches to store the response. private limits storage to the client. no-store instructs caches not to store the response, while no-cache means that a stored response must be validated before reuse. When max-age expires, the response is considered stale. However, the data may change before that time, so TTL is an operational window rather than a guarantee of freshness.

Use an explicit policy for sensitive or user-specific responses:

Response.Headers.CacheControl = "no-store";

For public catalog responses, inspect the headers produced by the framework and test them with an HTTP client. Avoid writing conflicting manual Cache-Control values in several layers for the same endpoint, because this makes client and server behavior difficult to reason about.

6. ETag and conditional requests

An ETag identifies a particular version of a representation. After receiving an initial response, a client stores the ETag:

HTTP/1.1 200 OK ETag: "products-v42" Cache-Control: public, max-age=60

On a later request, the client sends that value in If-None-Match. If the representation has not changed, the server can return 304 Not Modified without sending the response body again. The client keeps using its local copy, reducing network traffic.

Generate ETags from deterministic content or a data version rather than from the current time. The following example uses a SHA-256 hash of the JSON representation of the Product DTOs:

using System.Security.Cryptography; using System.Text; using System.Text.Json; private static string CreateEntityTag<T>(T value) {    var json = JsonSerializer.Serialize(value);    var hash = SHA256.HashData(Encoding.UTF8.GetBytes(json));    return $"\"{Convert.ToHexString(hash)}\""; }

Here is a controller example that handles a conditional response:

[HttpGet("{id:int}")] public async Task<ActionResult<ProductDto>> GetById(    int id,    CancellationToken cancellationToken) {    var product = await productService.GetByIdAsync(id, cancellationToken);    if (product is null)        return NotFound();    var entityTag = CreateEntityTag(product);    Response.Headers.ETag = entityTag;    Response.Headers.CacheControl = "public, max-age=60";    if (Request.Headers.IfNoneMatch.Any(value =>        value.Split(',').Select(item => item.Trim()).Contains(entityTag)))    {        return StatusCode(StatusCodes.Status304NotModified);    }    return Ok(product); }

Production code should handle weak and strong ETag comparison rules, multiple values, and the * value more comprehensively. If serializing a large response on every request is expensive, derive the ETag from a database rowversion, last-modified value, or aggregate version instead.

7. Cache invalidation and stale data

Cache invalidation is often the hardest part of caching. A 60-second TTL is simple and safe, but it means that a changed product name or category status may remain visible for a short period. A more controlled design evicts related cache entries by tag after a write operation.

using Microsoft.AspNetCore.OutputCaching; [HttpPut("{id:int}")] public async Task<IActionResult> Update(    int id,    UpdateProductRequest request,    [FromServices] IOutputCacheStore outputCacheStore,    CancellationToken cancellationToken) {    var updated = await productService.UpdateAsync(        id, request, cancellationToken);    if (!updated)        return NotFound();    await outputCacheStore.EvictByTagAsync(        "catalog", cancellationToken);    return NoContent(); }

If Product and Category lists share the same tag, this may evict more entries than necessary. Use separate tags such as products and categories for a more precise design. A product update that does not affect categories should evict only the products tag.

In a distributed deployment, each application instance may have its own memory cache. An invalidation performed by one instance may not reach the others. In that situation, plan for a distributed output-cache store or a centralized invalidation mechanism. Whether a failed invalidation should roll back the write operation is a business and consistency decision.

8. Common mistakes

  • Caching user-specific data publicly: Responses that vary by authorization, tenant, or user identity must not be placed in a shared cache.
  • Ignoring query parameters: If pagination and filtering parameters are excluded from the cache key, different results can be mixed.
  • Using an unlimited lifetime: An effectively permanent cache can make stale data persist indefinitely.
  • Skipping invalidation after writes: POST, PUT, PATCH, and DELETE operations can make related read-cache entries invalid.
  • Generating random ETags: An ETag that changes on every request defeats conditional requests.
  • Treating caching as security: Cache policy does not replace authorization. Access control must still be performed for protected endpoints.
  • Relying only on a browser during testing: Browsers may send Cache-Control: no-cache while refreshing. Test with curl or an HTTP client and make request headers explicit.

9. Practice exercise

Apply the following exercise to the existing Product and Category API:

  1. Register AddOutputCache and UseOutputCache.
  2. Create separate policies with a 60-second lifetime for Product lists and a 120-second lifetime for Category lists.
  3. Include pagination, filtering, and sorting parameters in the cache key.
  4. Inspect the Cache-Control headers returned by GET requests.
  5. Add a deterministic ETag to the Product detail endpoint.
  6. Evict the Product-list cache by tag after a Product update.
  7. Send the same request repeatedly and verify through logs that the first request executes the database query while later requests are served from cache.
  8. Update a Product and verify that the next list request does not return the old representation.

Conclusion

Professional caching is more than adding a cache attribute to an endpoint. You must first determine how the data varies, how long it may remain fresh, and how changes propagate. Output caching reduces server work, while Cache-Control guides clients and proxies. ETag and 304 Not Modified prevent unnecessary response-body transfers when the representation has not changed.

The strategy used in this lesson combines a bounded TTL for anonymous catalog data, correct query variation, deterministic ETags, and tag-based invalidation after writes. These decisions should later be validated through observability, distributed-cache testing, and performance measurements. Producing a fast response is important, but producing a correct response with an acceptable freshness level is equally important in professional API design.

Sources