Skip to content

Avoid a StreamReader per multipart form value in ReadAsStringAsync - #70198

Closed
davidfowl wants to merge 2 commits into
mainfrom
perf/http-multipart-read-string
Closed

davidfowl wants to merge 2 commits into
mainfrom
perf/http-multipart-read-string

Conversation

@davidfowl

Copy link
Copy Markdown
Member

MultipartSectionStreamExtensions.ReadAsStringAsync creates a new StreamReader for every section: a 1 KB byte buffer, a ~2 KB char buffer, a decoder and a StringBuilder in ReadToEndAsync, about 3.5 KB in total. FormFeature calls it for every multipart text field, so a form with a few fields allocates more on these readers than on anything else.

With this change, when section.Body is our own internal MultipartReaderStream (the case for MultipartReader/FormFeature), the value is read into an ArrayPool buffer of 1 KB, the same size as the old StreamReader buffer:

  • Value fits, encoding is UTF-8, and the first byte can't start a BOM (EF/FE/FF/00): returns Encoding.UTF8.GetString. This is exactly what StreamReader produces, including U+FFFD replacement for invalid or truncated sequences, because StreamReader flushes the decoder at EOF.
  • Value fits but another encoding or a possible BOM is involved: decodes with a StreamReader over a MemoryStream of the same bytes, so the result is unchanged by construction.
  • Value is larger than the buffer: continues with a StreamReader over a small private stream that replays the already-read bytes and then the rest of the section.

The pooled buffer is only passed to MultipartReaderStream, which copies into it from its own buffer and does not keep it. The buffer is returned in finally. Any other Body stream type takes the existing code path unchanged.

Benchmark

FormFeatureReadFormBenchmarks (added): DefaultHttpContext + ReadFormAsync, BenchmarkDotNet InProcess, 3 interleaved rounds:

Case main PR main alloc PR alloc
1 text field 3.534 / 3.385 / 3.787 us 3.003 / 3.199 / 3.127 us 13,192 B 9,736 B (−26%)
3 text fields 6.656 / 6.322 / 6.380 us 5.050 / 5.543 / 4.905 us 24,960 B 14,336 B (−43%)
1 × 8 KB field (fallback path) 8.42 / 8.16 us 8.03 / 8.03 us 45,592 B 45,640 B

Tests

Added MultipartSectionStreamExtensionsTests, which compares ReadAsStringAsync with the previous StreamReader implementation on the same bytes. Inputs are read through a MultipartReader (seekable and non-seekable) and also as a plain Body stream. Cases cover:

  • empty, ASCII and non-ASCII values
  • UTF-8, UTF-16 LE/BE and UTF-32 LE/BE BOMs, partial BOMs, and a leading NUL
  • invalid and truncated UTF-8
  • charset=utf-16, iso-8859-1 and utf-8
  • 1023, 1024, 1025, 2048 and 5000 bytes, with multi-byte characters and truncated sequences straddling the buffer boundary
  • reading several consecutive sections

These tests pass on main and on this branch. When the BOM guard is mutated, 6 cases fail. WebUtilities (581) and Http (258) tests pass.

ReadAsStringAsync allocated a StreamReader (1 KB byte buffer, ~2 KB char
buffer, decoder and StringBuilder) for every section, which FormFeature
calls for every multipart text field. When the body is our own
MultipartReaderStream, read into a pooled 1 KB buffer and, if the value
fits, decode it directly. Plain UTF-8 without a possible BOM uses
Encoding.UTF8.GetString, which is exactly what StreamReader produces;
anything else is decoded by a StreamReader over the same bytes. Values
larger than the buffer continue through a StreamReader that first replays
the consumed bytes, so results are unchanged.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 16:58
@github-actions github-actions Bot added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions 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.

🟡 Changes recommended

The buffered fast path can ignore an already-canceled token and consume the section, regressing cancellation behavior unless cancellation is explicitly checked before reading.

1 open issue
What changed in this PR

Reduces allocations when reading small multipart form values by avoiding a StreamReader on the common UTF-8 path used by MultipartReader and FormFeature.

Changes:

  • Adds pooled-buffer decoding with StreamReader fallbacks for possible byte-order marks, other encodings, and larger values.
  • Adds compatibility tests covering encodings, buffer boundaries, and consecutive sections.
  • Adds form-reading benchmarks for URL-encoded and multipart requests.
File Description
src/​Http/​WebUtilities/​test/​MultipartSectionStreamExtensionsTests.cs Tests decoding compatibility and consecutive-section reads.
src/​Http/​WebUtilities/​src/​MultipartSectionStreamExtensions.cs Adds the pooled-buffer fast path and fallback stream wrapper.
src/​Http/​Http/​perf/​Microbenchmarks/​FormFeatureReadFormBenchmarks.cs Benchmarks form-reading performance and allocations.

Review effort: Balanced

var length = 0;
while (length < buffer.Length)
{
var read = await section.Body.ReadAsync(buffer.AsMemory(length), cancellationToken);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I checked this against main, and the current implementation does not reject an already-canceled token for a buffered section either.

I added this test temporarily and ran it with main's MultipartSectionStreamExtensions.cs:

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReadAsStringAsync_CanceledToken_Throws(bool seekable)
{
    var section = await ReadSingleSectionAsync("value"u8.ToArray(), contentType: null, seekable);
    await Assert.ThrowsAsync<OperationCanceledException>(async () => await section.ReadAsStringAsync(new CancellationToken(canceled: true)));
}

On main, both cases fail with Assert.Throws() Failure: No exception was thrown. StreamReader.ReadToEndAsync(cancellationToken) only passes the token through to Stream.ReadAsync, and MultipartReaderStream.ReadAsync returns already-buffered data without checking it. This PR has the same result: the value is returned. Adding ThrowIfCancellationRequested() would therefore be a behavior change, which this PR intends to avoid, so I'm leaving the code as is. I'm leaving this thread open for a maintainer to decide.

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

Copy link
Copy Markdown
Member Author

Heads-up for reviewers: this PR overlaps with #70164, which was opened earlier from the same account and targets the same MultipartSectionStreamExtensions.ReadAsStringAsync path. Both use a pooled read for MultipartReaderStream bodies, with BOM-safe fallback to StreamReader via a prefixed stream. Differences: #70164 grows the pooled buffer up to 64 KB for UTF-8 only. This PR uses a single 1 KB buffer and also covers non-UTF-8 encodings by decoding through a StreamReader over the buffered bytes. They are not meant to be merged together; please pick one and the other can be closed.

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

@davidfowl
davidfowl requested review from a team, SamMonoRT and wtgodbe as code owners October 31, 2026 18:14
@davidfowl
davidfowl force-pushed the perf/http-multipart-read-string branch from 4e349cf to fd7b512 Compare October 31, 2026 18:15

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (fd17e7e). The previous run failed only the Blazor E2E test ServerRoutingTest.NavigationLock_CanBlockExternalNavigation (Build Analysis reports a 27.2%% failure rate), a Selenium navigation assertion in Components. This PR only changes multipart section string reading in WebUtilities.

Note: a malformed retrigger commit (4e349cf) was pushed by mistake for under a minute and force-reverted to fd7b512 before the empty commit was added. The PR diff is unchanged (3 files).

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

Copy link
Copy Markdown
Member Author

CI update: aspnetcore-ci passed. Only aspnetcore-components-e2e failed, on Blazor Selenium tests unrelated to this WebUtilities change:

  • ServerRoutingTest.NavigationLock_CanBlockExternalNavigation (~27% failure rate)
  • VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements

The same pipeline is failing on main in 4 of the last 5 commits (b7d01de, 23ab95b, fe077f0, f00e4eb), so I'm not pushing another empty commit; that would mostly add CI load. I'm happy to retrigger once the pipeline is stable again.

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

Copy link
Copy Markdown
Member Author

Superseded by #70164

The owner is keeping the earlier PR #70164, which covers the same change. Closing this duplicate is left to the maintainers. I will not push or retrigger anything further on this PR.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants