Skip to content

Reduce per-request allocations in W3CLoggingMiddleware - #70176

Open
davidfowl wants to merge 4 commits into
mainfrom
perf/w3clogging-middleware
Open

davidfowl wants to merge 4 commits into
mainfrom
perf/w3clogging-middleware

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Reduce per-request allocations in W3CLoggingMiddleware

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making.

Cut CPU and allocations on the UseW3CLogging request path.

Description

The log output is unchanged.

W3CLoggingMiddleware.Invoke runs for every request when W3C logging is on. It did several pieces of work that repeat the same result from request to request:

Before After
now.ToString("yyyy-MM-dd") and now.ToString("HH:mm:ss") per request Formatted once per second. The (second, date, time) triple is cached in an immutable holder that is swapped atomically.
LocalPort.ToString() per request The last (port, string) pair is cached the same way.
_additionalRequestHeaders.ToList() per request (a List and its array) The header names are snapshotted into a string[] in the constructor. The set was already cloned and fixed there, and enumeration order is the same.
new string[0] when no additional headers are configured [] (Array.Empty)
ReplaceWhitespace: char-by-char scan, then ToCharArray() + new string when whitespace is found (e.g. any normal User-Agent) IndexOfAnyInRange('\0', ' '), then one string.Create

The cached values are immutable strings, so nothing mutable is shared between requests. #69108 also touches W3C logging; this PR doesn't touch any of its files, and it doesn't pool the elements arrays, so their lifetime is unchanged.

Benchmark

I used a local BenchmarkDotNet harness (not included). It builds the real pipeline (AddW3CLogging + UseW3CLogging) with the logger's background queue completed, so each request still formats the full log line but nothing is written to disk. The request has a typical User-Agent, Host, Referer and query. Timings are on 2 cores, 3 runs each.

Case Before (main) After Δ
Default fields 1166–1230 ns ±11–24, 2528 B 1001–1035 ns ±9–13, 2272 B −15% time, −256 B
Default + 3 additional request headers 1353–1368 ns ±20–25, 2808 B 1103–1136 ns ±22, 2376 B −18% time, −432 B
ContextOnly (creating the HttpContext) 397–402 ns, 1592 B 395–405 ns, 1592 B —

Without the HttpContext cost, the middleware's own allocations drop by 27% with default fields (936 → 680 B) and by 37% with additional headers (1216 → 784 B).

Tests

  • Microsoft.AspNetCore.HttpLogging.Tests: 145/145.
  • New test LogsFormattedValuesAcrossRequests sends several requests with alternating local ports, User-Agent values containing spaces, tabs and control characters, and missing or present additional headers. It checks the exact log lines, the date/time format and that the column order follows the sorted header names. It passes against both the original and the new implementation.

Benchmark (3 interleaved rounds)

The benchmark is committed in src/Middleware/HttpLogging/perf/Microbenchmarks/W3CLoggingMiddlewareBenchmark.cs. It builds the real AddW3CLogging + UseW3CLogging pipeline with the logger's background queue completed, so each request still formats the full log line in W3CLogger but nothing is written to disk. The request has a typical User-Agent (with spaces), Host, Referer and query. The second case adds 3 AdditionalRequestHeaders.

Result: a consistent win in every round. With default fields, time drops 11% and allocations drop 392 B per request (3,208 → 2,816 B). With 3 additional request headers, time drops 19% and allocations drop 568 B (3,528 → 2,960 B). ContextOnly drifts −3.6% between builds, well below these deltas.

Benchmark Round main Mean PR Mean Δ time main Allocated PR Allocated
ContextOnly 1 486.1 ns ±18.9 463.4 ns ±8.2 -4.7% 1,672 B 1,672 B
ContextOnly 2 505.9 ns ±25.3 483.2 ns ±5.7 -4.5% 1,672 B 1,672 B
ContextOnly 3 478.5 ns ±18.3 470.8 ns ±8.8 -1.6% 1,672 B 1,672 B
DefaultFields 1 1,477.0 ns ±41.0 1,364.0 ns ±140.0 -7.7% 3,208 B 2,816 B
DefaultFields 2 1,429.0 ns ±29.0 1,269.0 ns ±36.0 -11.2% 3,208 B 2,816 B
DefaultFields 3 1,465.0 ns ±26.0 1,270.0 ns ±25.0 -13.3% 3,208 B 2,816 B
DefaultFieldsWithAdditionalRequestHeaders 1 1,747.0 ns ±52.0 1,378.0 ns ±21.0 -21.1% 3,528 B 2,960 B
DefaultFieldsWithAdditionalRequestHeaders 2 1,695.0 ns ±30.0 1,405.0 ns ±39.0 -17.1% 3,528 B 2,960 B
DefaultFieldsWithAdditionalRequestHeaders 3 1,722.0 ns ±61.0 1,416.0 ns ±43.0 -17.8% 3,528 B 2,960 B

BenchmarkDotNet v0.13.0, InProcess, 5 warmup + 15 measured iterations, Server GC. Rounds ran in the order main, PR, main, PR, main, PR. Both builds use the same benchmark source; "main" is this PR's merge base (4f556f7). Allocated is exact bytes per op from the GC counters. Machine: AMD EPYC 9V74, 2 cores, Ubuntu 24.04 (container), .NET SDK 12.0.100-alpha.1.26521.103, runtime 12.0.0 (12.0.26.52911).

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

- Cache the formatted date/time strings per second and the local port string.
- Snapshot the additional request header names once instead of calling ToList per request.
- Reuse an empty array when there are no additional headers.
- Replace whitespace with a vectorized scan and a single string allocation.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 08:16
@github-actions github-actions Bot added the area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares label Oct 31, 2026

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.

🔵 Needs a closer look

The required frozen head/base source-and-guidance bundle and existing-feedback snapshot were missing, preventing validation of revision provenance and feedback deduplication.

No open issues 🎉

What changed in this PR

Reduces per-request CPU work and allocations in W3C logging middleware while preserving log output and field-array lifetimes.

Changes:

  • Caches formatted date/time and port values, snapshots additional header names, and avoids empty-array allocations.
  • Reworks whitespace replacement to avoid an intermediate character array.
  • Adds output-equivalence coverage across requests with changing ports, whitespace, and optional headers.
File Description
src/​Middleware/​HttpLogging/​test/​W3CLoggingMiddlewareTests.cs Adds checks for formatted values, timestamps, and additional-header ordering across requests.
src/​Middleware/​HttpLogging/​src/​W3CLoggingMiddleware.cs Caches repeated formatting and reduces header-handling and whitespace-replacement allocations.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-components-e2e

The Blazor E2E tests on Linux (Mono client and WebAssembly) job failed on a WaitAssert browser assertion in the Components E2E suite. That's unrelated to this change, which only touches W3CLoggingMiddleware; it isn't used by the Components E2E test apps. The Blazor E2E jobs failed on 2 of the ~25 most recent PRs that ran them (#70144, #70173), both unrelated.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

Copy link
Copy Markdown
Member Author

Pushed empty commit ce26859 to retrigger CI. The only failure was aspnetcore-components-e2e (Blazor E2E). This PR only touches src/Middleware/HttpLogging (W3C logging), which Blazor E2E tests don't exercise. The same E2E flake, RoutingTest.NavigationLock_CanBlockExternalNavigation, also failed on unrelated PRs (~2/25 recent runs).

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

Adds a Microsoft.AspNetCore.HttpLogging.Microbenchmarks project that runs
the UseW3CLogging pipeline with default fields and with additional request
headers. The logger's queue is completed so each request still formats the
full log line but nothing is written to disk.

Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Member Author

CI on head 6e98cce has one failing test: ServerExecutionTests.ServerRoutingTest.NavigationLock_CanBlockExternalNavigation on aspnetcore-components-e2e / Blazor E2E tests on Linux (Mono server) (build 1660778). Build Analysis and Build Insights are red only because of that failure; every other leg is green.

It's unrelated to this PR. The diff touches only HttpLogging files (W3CLoggingMiddleware.cs, its tests and a new microbenchmark project) plus solution entries, and nothing in Components. Build Analysis reports a 30.66% failure rate for this test. Main has the same flake: the same Mono server leg failed on main commit 480401c (build 1660600), and components-e2e was also red on main for f570eec, b7d01de, 23ab95b and fe077f0.

I'm rerunning components-e2e once.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-components-e2e

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (new head db4f5e0fdba51022ba1969134d2249a0e6c43446). The only failure was the known flaky ServerRoutingTest.NavigationLock_CanBlockExternalNavigation in the Blazor E2E Mono server leg; evidence: #70176 (comment). No code changes.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copy link
Copy Markdown
Member Author

The only failure on db4f5e0 is aspnetcore-components-e2e (Blazor E2E tests on Linux, Mono server leg). One test failed: Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests.ServerRoutingTest.NavigationLock_CanBlockExternalNavigation. The browser URL stayed at /subdir/ instead of navigating to the external path. Build Analysis reports a 31.41% failure rate for this test. Build Analysis and Build Insights are just the rollups of that failure.

This failure is unrelated to the PR. The diff only changes HttpLogging's W3CLoggingMiddleware plus its tests and a new microbenchmark project (with the matching solution/slnf entries). It doesn't touch Components or Blazor. The same pipeline is also flaky on main: aspnetcore-components-e2e failed in 3 of the last 5 completed main runs (480401c on the same Mono server leg, f570eec on the CoreCLR leg, and cd23690).

This PR's single retrigger was already used, so no further retrigger is planned. Apart from this known flake, the PR is ready for review.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 6, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Nov 13, 2026

davidfowl commented Nov 17, 2026 •

Copy link
Copy Markdown
Member Author

Merge assessment

Verdict: Hold until the aspnetcore-components-e2e Mono server leg passes on a rerun and the open field-order thread is addressed. halter73 approved the current head on Nov 25; the win is 11–19% per request with log output unchanged, but the current head still has a red E2E leg.

Size S: +54/−25 production lines, +57 test, +146 benchmark (+2 slnx/slnf lines); 7 files, 1 production assembly (3 projects incl. new HttpLogging.Microbenchmarks)
Impact Medium: default fields 1,429–1,477 → 1,269–1,364 ns, 3,208 → 2,816 B; with 3 additional headers 1,695–1,747 → 1,378–1,416 ns, 3,528 → 2,960 B; ContextOnly control neutral
Risk High by rubric: HttpLogging (Medium) raised one tier for per-instance date/time and port string caches that live across requests; they hold immutable records swapped by reference
Tests LogsFormattedValuesAcrossRequests checks exact lines across alternating ports, spaces/tabs/control chars in User-Agent and header order; passes on main too (parity test)
Review halter73 APPROVED the current head on 2026-11-25; field-order thread remains open
CI Red on db4f5e0: only aspnetcore-components-e2e (Mono server), ServerRoutingTest.NavigationLock_CanBlockExternalNavigation, previously reported as a flake; Build Analysis/Insights remain red as rollups; no conflicts
Complexity Low to moderate: two small cache helpers and a string.Create rewrite of ReplaceWhitespace
Reversibility Easy; one production file
Security sensitivity Not assessed (repo review guidance excludes security assessments)
Encoding/escaping parity Holds on the current head: ReplaceWhitespace used ch <= '\u0020', the new fast path is IndexOfAnyInRange('\^@', '\u0020') and the replace loop uses the same <= '\u0020'; empty strings still return the input; covered by the new test
Behavior / public API change None

Reasons to merge

  • Consistent gain in all 3 rounds on the full UseW3CLogging pipeline, not an isolated method.
  • Additional header names are snapshotted once with the same enumeration order as the old per-request ToList().
  • The escaping fast-path predicate matches the replacement set exactly.

Reasons not to merge yet

  • CI is not green on the head, and the one allowed retrigger was already used. The approved review also has an open field-order nit.
  • The PR body has two benchmark sections with different numbers (an earlier "harness not included" table and the committed 3-round table); the 3-round table is the one to trust.
  • Write W3C log entries directly to StreamWriter #69108 rewrites W3C log writing and may change where this time goes.

What would change this verdict: a green Mono server rerun and resolution of the field-order thread.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

// Snapshot of the additional request headers in the same order the W3CLogger writes them.
private readonly string[] _additionalRequestHeaderNames;
private DateTimeStrings? _dateTimeStrings;
private PortString? _portString;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: This class is weird and already had static fields in the middle of readonly fields, but lets move all these up top with the other instance fields.

This branch has not been deployed

No deployments
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 pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants