A bus timetable API behind ASP.NET Core's response caching middleware returns route 12's timetable for route 31; why, and how does VaryByQueryKeys fix it?
answer
- base key: method, scheme, host, path
- query string not in the key
- VaryByQueryKeys has no HTTP header
- IResponseCachingFeature.VaryByQueryKeys
- throws without UseResponseCaching
basics
~20 sThe middleware's key is method, scheme, host and path only, so /api/timetable?route=12 and ?route=31 share one entry. VaryByQueryKeys = new[] { "route" } adds that query key to the key; it requires UseResponseCaching, or the filter throws.
solid answer
~40 sThe response caching middleware builds its base key from the method, scheme, host and path. The query string is not part of it, so the first stored response for `/api/timetable` (route 12) is replayed for `?route=31` until it expires. Browsers and CDNs do not have this problem because they key on the full URL; this is the server cache's own rule. The fix is `[ResponseCache(Duration = 300, VaryByQueryKeys = new[] { "route" })]`, or `"*"` for every key. `VaryByQueryKeys` is not an HTTP header: the filter hands it to the middleware through `IResponseCachingFeature`, and throws `InvalidOperationException` ("'VaryByQueryKeys' requires the response cache middleware.") when that feature is missing. Outside MVC you set `HttpContext.Features.Get<IResponseCachingFeature>()!.VaryByQueryKeys` yourself. Query key names are compared case-insensitively, values ordinally.
code
csharp · 10 linesbuilder.Services.AddControllers();
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseResponseCaching();
app.MapControllers();
[HttpGet("/api/timetable")]
[ResponseCache(Duration = 300, VaryByQueryKeys = new[] { "route", "day" })]
public Task<Timetable?> Get(string route, string? day) => store.FindAsync(route, day);go deeper
Know that the response caching middleware ignores the query string unless VaryByQueryKeys lists the keys that matter.
Explain how the base key is built, how VaryByQueryKeys reaches the middleware through IResponseCachingFeature, and why the filter throws without the middleware.
Diagnose the wrong-content symptom from Age headers and timing, and fix every query-dependent action, including Minimal API handlers that must set the feature themselves.
Treat cache keys as part of each endpoint's contract and make query-dependent caching opt-in through reviewed cache profiles rather than ad-hoc attributes.
## The symptom A city bus network exposes `GET /api/timetable?route=12&day=sat`. The controller action carries `[ResponseCache(Duration = 300)]` and the app calls `app.UseResponseCaching()`. Riders on route 31 start receiving route 12's timetable for a few minutes at a time, then the right one, then route 12 again. Nothing is wrong in the database or the action. ## Why it happens The middleware stores entries under a **base key** made of: 1. the method, upper-cased; 2. the scheme; 3. the host and port; 4. the path base and path, upper-cased unless `ResponseCachingOptions.UseCaseSensitivePaths` is `true`. The **query string is not in that list**. Unless something declares vary rules, every request to `/api/timetable` maps to the same key. The sequence is: 1. `?route=12` misses, runs the action, and the `public,max-age=300` response is stored under the path key. 2. `?route=31` arrives within five minutes, hits that same key, and receives route 12's body with an `Age` header. 3. When the entry expires, whichever route is requested next becomes the stored one. Browsers and CDNs key on the full URL, including the query, so they behave correctly; the bug is entirely in the in-app cache. ## The fix: VaryByQueryKeys ```csharp [HttpGet("/api/timetable")] [ResponseCache(Duration = 300, VaryByQueryKeys = new[] { "route", "day" })] public Task<Timetable?> Get(string route, string? day) => store.FindAsync(route, day); ``` With vary rules present, the middleware stores two kinds of entries: a record of the vary rules under the base key, and each response under a key that appends the listed query values. Details: - **`"*"`** varies by every query key and value. - Query **key names** are compared case-insensitively; **values** are compared exactly. - Header vary rules come from the response's own `Vary` header (for example via `VaryByHeader`) and combine with the query rules. ## Why it can throw `VaryByQueryKeys` is the one `[ResponseCache]` property with **no HTTP header equivalent**. The filter cannot write it to the response, so it sets `IResponseCachingFeature.VaryByQueryKeys`, a feature that only `ResponseCachingMiddleware` adds to the request. If the middleware is not in the pipeline (or the request did not pass through it), the feature is absent and the filter throws: - `InvalidOperationException`: "'VaryByQueryKeys' requires the response cache middleware." That makes a forgotten `UseResponseCaching()` fail loudly on the first request, which is better than silently caching nothing. ## Outside MVC Minimal API handlers never run MVC filters, so they set the feature directly, along with the header that makes the response cacheable: ```csharp app.MapGet("/api/timetable", (string route, HttpContext ctx, TimetableStore store) => { var feature = ctx.Features.Get<IResponseCachingFeature>(); if (feature is not null) feature.VaryByQueryKeys = ["route", "day"]; ctx.Response.GetTypedHeaders().CacheControl = new() { Public = true, MaxAge = TimeSpan.FromMinutes(5) }; return store.FindAsync(route); }); ``` ## Comparison with output caching The output cache takes the opposite default: its default policy varies by **every** query key, and `SetVaryByQuery` narrows it. Teams moving from response caching to output caching therefore usually see more entries per path, not fewer, which is the safer surprise. ## Diagnosing it in production The bug looks like flaky data, so it is often blamed on the database first. Three signals point at the cache instead: - the wrong body arrives with an **`Age`** header, which only a cache adds; - the wrong content flips at intervals equal to the action's `Duration`; - the problem disappears when a client sends `Cache-Control: no-cache`, which makes the middleware skip its lookup. Restarting the app clears it for a while, since the store lives in process memory, which is another hint that no external system is involved. ## Checklist - Every action whose output depends on the query string declares `VaryByQueryKeys` (or a cache profile that does). - `app.UseResponseCaching()` is present wherever those actions run, or the filter throws. - Query parameters that do not change the output (tracking tags) are left out of the list to keep the hit rate up.
- Does VaryByQueryKeys change anything for browsers or a CDN?No. It is not written as a header; it only sets `IResponseCachingFeature.VaryByQueryKeys` for the in-app middleware. Downstream caches already treat each full URL, query string included, as a separate resource.
- Would VaryByQueryKeys = new[] { "*" } be a safe default for every action?It is correct but can be wasteful: every distinct query string, tracking parameters included, creates its own entry and competes for the 100 MB `SizeLimit`. Listing the keys the action actually reads keeps both correctness and hit rate.
- The response caching middleware keys on the full URL including the query string.
- VaryByQueryKeys is sent to clients as a Vary header.
- VaryByQueryKeys works without UseResponseCaching and is simply ignored.
- Browsers and CDNs will also mix up the two routes' timetables.
- VaryByHeader = "route" makes the cache vary by the route query parameter.