Skip to content

perf(ext/node): optimize direct ServerResponse string end - #34253

Merged
nathanwhit merged 3 commits into
denoland:mainfrom
nathanwhitbot:codex/aged-4c3d66f0-fcc
May 21, 2026
Merged

nathanwhit merged 3 commits into
denoland:mainfrom
nathanwhitbot:codex/aged-4c3d66f0-fcc

Conversation

@nathanwhitbot

Copy link
Copy Markdown
Contributor

Summary

  • Adds a guarded fast path for ServerResponse.end(string) that writes the response header and body directly when the response shape is safe.
  • Preserves existing behavior for HEAD/no-body responses, trailers, chunked responses, strict content length, queued writes, unsupported encodings, and non-server outgoing messages.
  • Reduces hot-path overhead for common node:http server responses while keeping the change limited to one reviewable runtime optimization.

Validation

  • Ran release-lite formatting, linting, and diff checks for the changed runtime file.
  • Ran focused release-lite node:http and node_compat correctness checks for ServerResponse write/end, HEAD/no-body, empty writes, 304/content-length, standalone responses, and custom ServerResponse cases.
  • Benchmarked on the same target with release-lite builds: GET improved from 15,352.67 req/s to 17,054.93 req/s (+11.09%, 95% CI +8.44% to +13.74%); POST 16 KiB improved from 13,143.39 req/s to 14,215.37 req/s (+8.16%, 95% CI +5.25% to +11.06%).

@nathanwhit

Copy link
Copy Markdown
Member

@fibibot review this pr

@bartlomieju bartlomieju left a comment

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.

Nice optimization — guards are conservative and the benchmark uplift (+11% GET, +8% POST 16 KiB) justifies the added code. A couple of notes below.

The main ask from me is some dedicated test coverage: this is a 156-line new code path with ~14 guard conditions, and a future change could silently bypass it (or break one of the guards) without any test failing. At minimum, one test that exercises the fast path and one that exercises a guarded fallback (e.g. chunkedEncoding or latin1) would make this much more maintainable.

A couple of smaller observations:

  • The fast path calls msg._implicitHeader() before the second guard (!_hasBody || chunkedEncoding || _header === null). If that guard trips we return false after headers are committed, then fall back through end()'s normal write_(..., true) path. That path handles _header !== null fine, so I don't see a bug, but it's a subtle state mutation worth keeping in mind.
  • Writing via socket._handle.writeUtf8String/writeLatin1String directly bypasses the stream's kAfterAsyncWrite / kUpdateTimer bookkeeping on completion. The guards ensure _writableState is clean before the write, but for async completions the socket's idle-timeout timer won't get refreshed when the write finishes (only at the start via _unrefTimer). Probably benign here since the message is ending, but worth a thought.

No blocking concerns from me — leaving as a comment review.

conn.uncork();
}

function tryDirectEnd(

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.

Could you add a focused test for this fast path? Two scenarios would cover the bulk of the surface area: (1) a happy-path test that does res.end("hi") and asserts the response body + Content-Length header, and (2) a test that forces a guarded condition (e.g. res.setHeader("Transfer-Encoding", "chunked"), or res.end("hi", "hex")) and confirms behavior matches the non-fast path. As written, a future change that breaks a guard or silently disables the fast path would not fail any test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added focused coverage in tests/unit_node/http_test.ts for both cases:

  • res.end("hi") via a raw socket assertion for body + Content-Length: 2
  • explicit Transfer-Encoding: chunked fallback, asserting chunked framing and no Content-Length

Validated with release-lite:

  • ./target/release-lite/deno test -A --config tests/config/deno.json --no-lock --no-check --filter "ServerResponse direct end sets content-length" tests/unit_node/http_test.ts
  • ./target/release-lite/deno test -A --config tests/config/deno.json --no-lock --no-check --filter "ServerResponse direct end respects explicit chunked transfer-encoding" tests/unit_node/http_test.ts
  • ./target/release-lite/deno test -A --config tests/config/deno.json --no-lock --no-check --filter "chunked response" tests/unit_node/http_test.ts
  • ./target/release-lite/deno fmt --check tests/unit_node/http_test.ts
  • ./target/release-lite/deno lint tests/unit_node/http_test.ts

msg._contentLength = len;
msg._implicitHeader();

if (!msg._hasBody || msg.chunkedEncoding || msg._header === null) {

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.

msg._implicitHeader() above commits headers before this guard runs. If we return false here, the caller falls back to the normal write_(this, chunk, encoding, null, true) path with _header already set. That path handles _header !== null correctly, so I don't see a bug — but it's a subtle mid-flight state mutation. Worth a one-line comment noting that returning false here is safe specifically because the fallback path is _header-aware.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the one-line clarification here: if _implicitHeader() causes this guard to trip, the normal fallback remains safe because it is _header-aware.

Validated with release-lite:

  • ./target/release-lite/deno test -A --config tests/config/deno.json --no-lock --no-check --filter "ServerResponse direct end" tests/unit_node/http_test.ts
  • ./target/release-lite/deno fmt --check ext/node/polyfills/_http_outgoing.ts tests/unit_node/http_test.ts
  • ./target/release-lite/deno lint ext/node/polyfills/_http_outgoing.ts tests/unit_node/http_test.ts

finish: () => void,
) {
const handle = socket._handle;
socket._unrefTimer?.();

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.

Going directly through handle.writeUtf8String / writeLatin1String bypasses the bookkeeping in internal/stream_base_commons.ts (onWriteComplete → kUpdateTimer, kAfterAsyncWrite). For sync completions that's fine. For async completions, _unrefTimer() is called here at the start but the socket's idle-timeout isn't refreshed when the write actually finishes. Likely benign because the response is ending, but if future keep-alive logic depends on a refreshed timer at write completion, this would silently skip it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a short comment at the direct handle write noting that this terminal response write bypasses stream_base_commons completion bookkeeping and that ServerResponse completion is handled directly by the caller.

Validated with release-lite:

  • ./target/release-lite/deno test -A --config tests/config/deno.json --no-lock --no-check --filter "ServerResponse direct end" tests/unit_node/http_test.ts
  • ./target/release-lite/deno fmt --check ext/node/polyfills/_http_outgoing.ts tests/unit_node/http_test.ts
  • ./target/release-lite/deno lint ext/node/polyfills/_http_outgoing.ts tests/unit_node/http_test.ts

@bartlomieju bartlomieju left a comment

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.

Nice perf win. The fast path is intricate but the guards look thorough, and bypassing the regular _send plumbing for terminal string writes is a solid optimization for a hot path.

A couple of non-blocking observations:

  • _implicitHeader() runs as a side effect before the post-header bail-out (!_hasBody || chunkedEncoding || _header === null). The fallback through write_() is _header-aware so this works, but the ordering is load-bearing — worth a clearer comment than the current one.
  • The fast path skips kAfterAsyncWrite / kUpdateTimer bookkeeping. Fine for a terminal write, but a brief note would help future readers.
  • Test coverage is fairly light — only the two happy-path cases. Could be worth adding a few fallback-path tests (HEAD, 204/304, non-utf8 encoding, end() after write(), user-set Content-Length, callback invocation) so we'd catch a regression if a guard is later loosened.
  • nit: result === 0 / 1 / <0 in writeDirectString could use a one-liner explaining the tri-state.

@nathanwhit
nathanwhit merged commit 3e3430b into denoland:main May 21, 2026
136 checks passed
littledivy pushed a commit to crowlKats/deno that referenced this pull request Jun 10, 2026
…4253)

## Summary
- Adds a guarded fast path for `ServerResponse.end(string)` that writes
the response header and body directly when the response shape is safe.
- Preserves existing behavior for HEAD/no-body responses, trailers,
chunked responses, strict content length, queued writes, unsupported
encodings, and non-server outgoing messages.
- Reduces hot-path overhead for common node:http server responses while
keeping the change limited to one reviewable runtime optimization.

## Validation
- Ran release-lite formatting, linting, and diff checks for the changed
runtime file.
- Ran focused release-lite node:http and node_compat correctness checks
for ServerResponse write/end, HEAD/no-body, empty writes,
304/content-length, standalone responses, and custom ServerResponse
cases.
- Benchmarked on the same target with release-lite builds: GET improved
from 15,352.67 req/s to 17,054.93 req/s (+11.09%, 95% CI +8.44% to
+13.74%); POST 16 KiB improved from 13,143.39 req/s to 14,215.37 req/s
(+8.16%, 95% CI +5.25% to +11.06%).

---------

Co-authored-by: Nathan Whitaker <nathan@deno.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants