Repository navigation
perf(ext/node): optimize direct ServerResponse string end - #34253
Conversation
|
@fibibot review this pr |
bartlomieju
left a comment
There was a problem hiding this comment.
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 returnfalseafter headers are committed, then fall back throughend()'s normalwrite_(..., true)path. That path handles_header !== nullfine, so I don't see a bug, but it's a subtle state mutation worth keeping in mind. - Writing via
socket._handle.writeUtf8String/writeLatin1Stringdirectly bypasses the stream'skAfterAsyncWrite/kUpdateTimerbookkeeping on completion. The guards ensure_writableStateis 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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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: chunkedfallback, asserting chunked framing and noContent-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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?.(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 throughwrite_()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/kUpdateTimerbookkeeping. 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()afterwrite(), user-set Content-Length, callback invocation) so we'd catch a regression if a guard is later loosened. - nit:
result === 0 / 1 / <0inwriteDirectStringcould use a one-liner explaining the tri-state.
…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>
Summary
ServerResponse.end(string)that writes the response header and body directly when the response shape is safe.Validation