Skip to content

Reuse RenderBatchWriter across render batches in RemoteRenderer - #70246

Merged
pavelsavara merged 6 commits into
mainfrom
perf/components-reuse-renderbatchwriter
Nov 3, 2026
Merged

pavelsavara merged 6 commits into
mainfrom
perf/components-reuse-renderbatchwriter

Conversation

@davidfowl

@davidfowl davidfowl commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Reuse RenderBatchWriter across render batches in RemoteRenderer

Stop allocating a new batch writer and stream for every Blazor Server render batch.

Description

Follow-up to @pavelsavara's suggestion on #70125. RemoteRenderer.UpdateDisplayAsync created a new ArrayBuilderMemoryStream, RenderBatchWriter, BinaryWriter, string ArrayBuilder and dedup Dictionary for every render batch. This PR keeps one writer per renderer and points its stream at each batch's own output buffer.

On the real RemoteRenderer.UpdateDisplayAsync + ack path, this halves allocations for a small interactive update (776 → 392 B) and cuts time by about 8%.

Why this is safe

  • Each batch still gets its own ArrayBuilder<byte> output buffer. That buffer is kept in the unacknowledged-batch queue until the client acks it, so it is never shared or reused.
  • UpdateDisplayAsync runs on the renderer's dispatcher, and Renderer guards it with _isBatchInProgress, so a renderer never writes two batches at once. The writer belongs to one renderer, so nothing is shared across circuits.
  • RenderBatchWriter.Write now resets its string table in a finally, including when a write throws. Between batches the writer holds no strings, and its string ArrayBuilder has returned its array to the pool. So the renderer never needs to dispose it, and a dispose racing a render can't return a buffer that is still in use.
  • If a batch used more than 128 deduplicated strings, the dictionary is replaced instead of cleared, so one large render doesn't leave a big table alive for the rest of the circuit.
  • The wire format and the WebAssembly/WebView callers are unchanged, and there are no public API changes.

Tests: two new RenderBatchWriterTest cases reuse one writer for two batches, one of them after a failed write. Both fail on main, where the second batch's string table still holds the first batch's strings, and pass here. Server (396), WebView (16) and WebAssembly (56) unit tests pass locally.

Benchmark

BenchmarkDotNet, in-process. The benchmark drives the real path: RemoteRenderer.UpdateDisplayAsync(batch) followed by OnRenderCompletedAsync(batchId), with an offline client so no SignalR send. The batches are the same as in #70125's RenderBatchWriterBenchmark (a 5-edit counter-style update, and a 200-row table initial render). I ran 3 interleaved rounds (main, PR, main, PR, main, PR) on a 2-core Linux VM.

Method main R1 / R2 / R3 PR R1 / R2 / R3 Δ time Allocated main → PR
Small batch 829.6 / 864.6 / 819.8 ns 778.2 / 792.1 / 750.5 ns −7.7% 776 B → 392 B (−49%)
Large batch 97.9 / 96.4 / 96.4 µs 93.6 / 94.8 / 93.4 µs −3.1% 5,032 B → 4,401 B (−13%)
Benchmark harness (throwaway; not part of this PR)

A console project inside the repo with AssemblyName=Microsoft.AspNetCore.Components.Server.Tests (for internals access), referencing Server and SignalR.Core, and using InProcessEmitToolchain + MemoryDiagnoser:

[GlobalSetup] // options = new CircuitOptions(); jsRuntime = new RemoteJSRuntime(...); services registers IJSRuntime
_renderer = new BenchRenderer(services, options, jsRuntime); // RemoteRenderer subclass, offline CircuitClientProxy
_nextBatchId = 2; // RemoteRenderer pre-increments _nextRenderId = 1

private Task RenderAndAck(in RenderBatch batch)
{
    var task = _renderer.Update(in batch);              // => UpdateDisplayAsync(in batch)
    _renderer.OnRenderCompletedAsync(_nextBatchId++, null); // dequeues + disposes the batch buffer
    if (!task.IsCompleted) { throw new InvalidOperationException("Batch was not acknowledged."); }
    return task;
}

This is independent of #70125 (which changes how frames and edits are encoded); both touch RenderBatchWriter.cs but in different methods.

Follow-up: IpcSender (WebView) and WebAssemblyRenderer (7e0ca87)

At reviewer request, the same reuse is applied to the other two RenderBatchWriter call sites:

  • IpcSender.ApplyRenderBatch (WebView): the writer and stream are cached in a private field. Each batch takes them with Interlocked.Exchange and puts them back in finally, so two concurrent callers can never share them; if the cache is empty, a new writer is created. The per-batch ArrayBuilder<byte> is now also disposed (returned to the pool) in finally, once the base64 message string has copied its contents. On main it was never disposed.
  • WebAssemblyRenderer.UpdateDisplayOutOfProcess: the writer and stream are cached in fields (the renderer is single-threaded) and retargeted at each batch's own ArrayBuilder. The existing finally { arrayBuilder.Dispose(); } is unchanged.

WebView IpcSender.ApplyRenderBatch: real path. BenchmarkDotNet, 3 interleaved rounds, mean of each round:

Batch main R1/R2/R3 PR R1/R2/R3 Allocated
Small 1.860* / 1.252 / 1.288 µs 1.048 / 1.041 / 1.061 µs 5 KB → 3 KB
Large 438.2 / 404.1 / 412.5 µs 420.8 / 424.1 / 396.6 µs (noise) 509 KB → 445 KB

*R1 main small had high variance (median 1.273 µs).

WebAssembly out-of-process sequence: the real UpdateDisplayOutOfProcess needs browser JS interop, so this benchmark reproduces its exact serialize + ToArray steps (UTF-16 string table) on CoreCLR, main pattern vs PR pattern:

Batch main R1/R2/R3 PR R1/R2/R3 Allocated
Small 567.4 / 558.7 / 552.0 ns 490.5 / 496.8 / 485.1 ns (−12%) 880 B → 496 B
Large 102.6 / 101.7 / 102.7 µs 99.4 / 120.3* / 99.0 µs (noise) 70,457 B → 69,825 B

*outlier round.

Tests: Components.Server 396, Components.WebView 16 and Components.WebAssembly 56 all pass.

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

RemoteRenderer allocated a new ArrayBuilderMemoryStream, RenderBatchWriter,
BinaryWriter, string ArrayBuilder and dedup Dictionary for every render batch.
Keep one writer per renderer and point its stream at each batch's own output
buffer. RenderBatchWriter.Write now resets its string table in a finally block,
so it holds no strings or pooled buffers between batches, including after a
failed write. Dictionaries that grew past 128 entries are replaced rather than
retained.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 2, 2026 12:09
@davidfowl
davidfowl requested a review from a team as a code owner November 2, 2026 12:09
@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label Nov 2, 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.

🟢 Approval recommended

No active review issues remain for the render-batch writer and stream reuse changes.

No open issues 🎉

What changed in this PR

Reduces per-batch allocations in Blazor Server by reusing a RenderBatchWriter and stream within each RemoteRenderer, while preserving separate output buffers until client acknowledgment.

Changes:

  • Reuses the writer and redirects its stream to each batch’s output buffer.
  • Resets string-table state after every write, including failures, and replaces oversized deduplication dictionaries.
  • Adds regression tests for writer reuse after successful and failed writes.
File Description
src/​Components/​Shared/​src/​RenderBatchWriter.cs Clears per-batch string state and limits retained dictionary size.
src/​Components/​Shared/​src/​ArrayBuilderMemoryStream.cs Allows switching the stream’s backing buffer.
src/​Components/​Server/​test/​Circuits/​RenderBatchWriterTest.cs Tests string-table isolation when reusing a writer.
src/​Components/​Server/​src/​Circuits/​RemoteRenderer.cs Retains a writer and stream across render batches.

Review effort: Balanced

@pavelsavara

Copy link
Copy Markdown
Member

Could we improve IpcSender and WebAssemblyRenderer too ?

@PureWeen

PureWeen commented Nov 2, 2026

Copy link
Copy Markdown
Member

/review

Copy link
Copy Markdown
Member Author

Thanks @pavelsavara, good call. Done in 7e0ca87:

  • IpcSender (WebView): the writer and stream are cached and taken exclusively per batch (Interlocked.Exchange, put back in finally), so concurrent callers can never share them. The per-batch output ArrayBuilder is now returned to the pool once the base64 message has copied it; on main it was never disposed.
  • WebAssemblyRenderer.UpdateDisplayOutOfProcess: the writer and stream are cached in fields and retargeted to each batch's own buffer. The existing finally { arrayBuilder.Dispose(); } is unchanged.

BenchmarkDotNet, 3 interleaved rounds:

Path Batch main PR Allocated
WebView IpcSender.ApplyRenderBatch (real path) small ~1.25–1.29 µs ~1.04–1.06 µs 5 KB → 3 KB
large 404–438 µs 397–424 µs (noise) 509 KB → 445 KB
WASM out-of-process serialize sequence* small 552–567 ns 485–497 ns (−12%) 880 B → 496 B
large ~102 µs ~99 µs (noise) −632 B

*The real WASM path needs browser JS interop, so the benchmark reproduces its serialize + ToArray steps (UTF-16 string table) on CoreCLR.

Server/WebView/WebAssembly Components tests pass (396/16/56). Details are in the PR description.

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

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (98dbe8d; the diff is unchanged, same 6 files). Build Analysis for 7e0ca87 reported only known-flaky failures, none on a path this PR changes:

Test Config Historical failure rate Why unrelated
ServerRoutingTest.NavigationLock_CanBlockExternalNavigation Mono server only (passed on CoreCLR) 30.62% External navigation / beforeunload behavior; the URL assertion timed out
VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements CoreCLR only (passed on Mono) 13.44% WebAssembly in-process rendering, which doesn't use RenderBatchWriter; scroll-timing NotEmpty assertion
DojoClient.E2E...PredictiveStateUpdatesScenarioTests.DocumentEditor_StreamsPredictionAndSupportsAcceptAndReject Windows Helix 5.14% Unrelated streaming-text scenario outside Components

Locally, Components.Server (396), Components.WebView (16) and Components.WebAssembly (56) tests pass.

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

Copy link
Copy Markdown
Member Author

Retriggered CI again with an empty commit (d0e7924; the diff is unchanged, same 6 files). On 98dbe8d, all other checks passed, including aspnetcore-ci and the template tests. Only the same two Blazor E2E flakes failed, and they are failing across unrelated open PRs right now:

Test Failure rate (Build Analysis) Also failing on
ServerRoutingTest.NavigationLock_CanBlockExternalNavigation (Mono server) 30.91% #70243, #70248, #70240 (a dependency-update-only PR)
VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements 13.48% #70248 (QuickGrid change, Mono client leg)

Neither test's path changes in this PR: external-navigation beforeunload handling, and in-process WebAssembly rendering, which doesn't use RenderBatchWriter.

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

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (c60432a; the diff is unchanged, same 6 files). On d0e7924, every check passed except one test on the CoreCLR E2E leg:

  • Tests.VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements (13.72% failure rate in Build Analysis). Open PR Use End in the variable-height table test #70243 fixes this test's known scroll-bounce race: window.scrollTo uses the estimated height before variable-height rows load, and that PR reports 9/10 local failures with the old approach.
  • This variant runs WebAssembly with in-process rendering (SharedMemoryRenderBatch), which doesn't go through RenderBatchWriter; the CoreCLR leg doesn't set __BLAZOR_WEBASSEMBLY_OUT_OF_PROCESS_RENDERER.
  • The Server variant of the same test (ServerExecutionTests.ServerVirtualizationTest), which does serialize through the reused RemoteRenderer writer, passed on both the CoreCLR and Mono server legs. WebAssemblyOutOfProcessRendererTest, which covers the changed WASM path, also passed.

If this test fails again, it should clear once #70243 merges.

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

Copy link
Copy Markdown
Member Author

Retriggered CI with an empty commit (40b9298; the diff is unchanged, same 6 files). On c60432a, every check passed, including aspnetcore-ci, CoreCLR E2E and Mono server E2E, except Tests.VirtualizationTest.VariableHeight_HtmlTable_DoesNotProduceNestedTrElements. This time it failed on the Mono client leg, which passed it on the earlier runs, while the CoreCLR leg that failed it before passed. It's the known scroll-race flake that #70243 fixes, and it runs in-process WebAssembly rendering, which doesn't use RenderBatchWriter. Every E2E leg has now passed at least once on this PR's code.

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

@pavelsavara
pavelsavara merged commit 8625bd7 into main Nov 3, 2026
32 checks passed
@pavelsavara
pavelsavara deleted the perf/components-reuse-renderbatchwriter branch November 3, 2026 11:52
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 3%

No docs needed (confident): internal refactor reusing RenderBatchWriter per RemoteRenderer, with tests. No signals detected.

Documentation surfaces considered

  • Conceptual article: Not required — Internal allocation optimization; no public API or observable behavior change; wire format unchanged.
  • Migration guidance: Not required — No user action needed when upgrading.
  • Breaking change: Not required — No compatibility impact; no API or default changes.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 40b92984 Deployed Nov 3, 2026 by pavelsavara via conclusion #166
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants