Skip to content

[Caching] Include response cache keys in size accounting - #69231

Merged
javiercn merged 3 commits into
mainfrom
javiercn/response-cache-key-size
Sep 28, 2026
Merged

javiercn merged 3 commits into
mainfrom
javiercn/response-cache-key-size

Conversation

@javiercn

@javiercn javiercn commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Fixes #69214

Overview

Response Caching previously declared only each cached value's estimated size to the bounded MemoryCache, even though the cache also retains the supplied string key. This change includes retained key content in both response and vary-rule entry sizes and clarifies the ResponseCachingOptions.SizeLimit contract. The accounting model remains an estimate of retained variable content rather than a hard managed-heap ceiling.

Design

Cache keys are charged at the storage boundary, where the actual key and value are both known. The estimate uses the retained in-memory representation: (long)key.Length * sizeof(char), so units are UTF-16 bytes and surrogate pairs count as two code units. This matches the existing estimators' treatment of strings and avoids changing key identity, reconstructing keys from request components, or introducing a separate key limit.

SizeLimit documentation now states that the budget includes estimated cached response data, vary-by rules, and cache keys, and explicitly excludes object headers, cache structures, allocator overhead, and other runtime-dependent costs. Defaults, public signatures, response body limits, expiration, and independent rule/response admission remain unchanged; at the same limit, entries with larger keys can now reach capacity sooner.

Implementation

var keySize = EstimateKeySize(key);

Size = checked(CacheEntryHelpers.EstimateCachedResponseSize(cachedResponse) + keySize);
Size = checked(CacheEntryHelpers.EstimateCachedVaryByRulesySize(entry as CachedVaryByRules) + keySize);

private static long EstimateKeySize(string? key)
    => (long)(key?.Length ?? 0) * sizeof(char);

The multiplication widens to long, and the combined estimate uses checked arithmetic. The original key is still passed unchanged to MemoryCache, preserving existing null-key rejection and cache identity behavior.

Tests

Focused store tests use a real bounded MemoryCache and cover:

  • exact-limit admission and one-byte-under rejection for nonempty cached responses and vary rules;
  • ASCII, BMP, and surrogate-pair keys, proving UTF-16 code-unit accounting;
  • empty and null key compatibility plus the fallback entry path;
  • mixed response/rule aggregate capacity;
  • equal-key replacement and removal by an oversized replacement.

Middleware coverage uses the existing harness in two layers. A TestServer theory proves rejected entries still deliver the originating response and miss later through the synchronous, asynchronous, and send-file delegates. A focused middleware theory inspects the real bounded cache after both writes, proving that an oversized base key rejects only the vary rules while the varied response is stored, and that an oversized varied key rejects only the response while the vary rules remain stored.

Validation

With key charging temporarily removed, 11 of the 13 focused store/middleware cases fail for the expected admission reason; only the empty- and null-key compatibility cases remain green. With the implementation restored, all focused cases pass. The complete Microsoft.AspNetCore.ResponseCaching.Tests suite passes: 293 passed, 0 failed; git diff --check also passes.

The latest CI run passed lint, code check, all build legs, all platform test legs, and the quarantined suite. Its aggregate result is red only because the unrelated Microsoft.AspNetCore.Server.Kestrel.Core.Tests.Http3StreamTests.RequestTrailers_ContainsNewlines Helix work item crashed with BadExit on Ubuntu; Build Analysis reports that test's existing 5.97% failure rate. The earlier local repository wrapper limitation likewise came from missing unrelated src/submodules/googletest; the isolated Response Caching project builds and its full suite passes.

@github-actions github-actions Bot added the area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares label Sep 11, 2026
@javiercn javiercn changed the title Include response cache keys in size accounting [Caching] Include response cache keys in size accounting Sep 11, 2026
@javiercn
javiercn marked this pull request as ready for review September 14, 2026 10:05
Copilot AI lite review requested due to automatic review settings September 14, 2026 10:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Outstanding review comments request additional documentation and coverage for edge cases, aggregate capacity, replacement, and admission verification.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Updates Response Caching size accounting to include retained UTF-16 cache-key content.

Changes:

  • Adds checked key-size estimates to response and vary-rule entries.
  • Clarifies SizeLimit documentation.
  • Extends bounded-cache and middleware test coverage.
File summaries
File Description
src/Middleware/ResponseCaching/test/TestUtils.cs Forwards SizeLimit to hosted middleware tests.
src/Middleware/ResponseCaching/test/ResponseCachingTests.cs Adds bounded middleware scenarios.
src/Middleware/ResponseCaching/test/MemoryResponseCacheTests.cs Tests key-size admission and UTF-16 accounting.
src/Middleware/ResponseCaching/src/ResponseCachingOptions.cs Documents key-inclusive size limits.
src/Middleware/ResponseCaching/src/MemoryResponseCache.cs Includes key size in cache-entry estimates.
Review details

Suppressed comments (2)

src/Middleware/ResponseCaching/src/ResponseCachingOptions.cs:13

  • Please state explicitly that SizeLimit is an estimate of retained variable content, not a hard managed-heap/process-memory cap. “Estimated size” is ambiguous beside “size limit in bytes”; the public contract should also exclude object headers, cache/dictionary structures, allocator overhead, and other runtime costs.
    /// The size limit for the response cache middleware in bytes, including the estimated size of cached response data,
    /// vary-by rules, and cache keys. The default is set to 100 MB.

src/Middleware/ResponseCaching/test/MemoryResponseCacheTests.cs:15

  • These store theories cover only nonempty keys with an empty vary-rule object and a response with empty headers/body. They do not verify that key bytes are added to the existing nonempty rule/response estimates, the fallback path, or the documented empty/null-key behavior, so regressions in those cases could pass. Add exact-limit and one-byte-under cases for those inputs.
    [Theory]
    [InlineData("a", 6)]
    [InlineData("\u00E9", 6)]
    [InlineData("\U0001F600", 8)]
    public void Set_CachedResponse_AccountsForKeySize(string key, long estimatedSize)
  • Files reviewed: 5/5 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@javiercn
javiercn requested a review from rokonec September 14, 2026 10:22
@javiercn

Copy link
Copy Markdown
Member Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
3 pipeline(s) were filtered out due to trigger conditions.

@javiercn

Copy link
Copy Markdown
Member Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 2 pipeline(s).
3 pipeline(s) were filtered out due to trigger conditions.

@javiercn
javiercn merged commit ec7ac23 into main Sep 28, 2026
27 checks passed
@javiercn
javiercn deleted the javiercn/response-cache-key-size branch September 28, 2026 16:17
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Response Caching: include retained cache-key bytes in MemoryCacheEntryOptions.Size

3 participants