Skip to content

http: add native single-shot response builder - #64393

Open
anonrig wants to merge 12 commits into
nodejs:mainfrom
anonrig:http-native-single-shot-response
Open

anonrig wants to merge 12 commits into
nodejs:mainfrom
anonrig:http-native-single-shot-response

Conversation

@anonrig

@anonrig anonrig commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Speed up the common HTTP/1.1 ServerResponse writeHead() + end() path in JavaScript. An earlier C++ buildHttpMessage helper was slower for small messages and has been removed. src/node_http_parser.cc matches main again.

  • Fast header block: plain string writeHead() headers are built in JS (tryFastStoreHeaderObject) and cached. The cache key includes header names in enumeration order, so { a, b } and { b, a } miss; sorting would allocate on the hot path.
  • ServerResponse.end() fast path: tryFastEnd / tryFastFlushEnd flush a prebuilt header and a small body without the full write_() path (the benchmark/http/simple.js case).
  • Cached header blocks stay Buffers until write time. ClientRequest still materializes a string for _header.
  • Trailers, strictContentLength, encodings other than utf8/latin1, and sockets that are corked or not a real libuv handle stay on the legacy JS path. A test-only switch (setOutgoingFastPathForTests) re-runs the framing checks on that path.

Public API and on-the-wire format are unchanged.

Benchmarks

Earlier local benchmark/http/simple.js runs on this branch (bytes, len=4, chunks=1, c=50, chunkedEnc=0, duration=5) were about 120–123k RPS versus a ~80k baseline. Those numbers were not re-measured after dropping the C++ builder.

Test plan

  • tools/test.py --mode=release test/parallel/test-http-outgoing-fast-path-regressions.js
  • tools/test.py --mode=release test/parallel/test-http-outgoing*.js test/parallel/test-http-server*.js (81 passed)
  • eslint on lib/internal/http/outgoing.js, lib/internal/http/server.js, and the new test
  • CI on this PR
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/http
  • @nodejs/net
@nodejs-github-bot nodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. http Issues and PRs related to the http subsystem. http_parser Issues and PRs related to the HTTP parser implementation or http_parser binding. needs-ci PRs that need a full CI run. labels Jul 9, 2026
@anonrig
anonrig requested review from Qard, mcollina, panva and ronag July 9, 2026 15:10
@anonrig
anonrig force-pushed the http-native-single-shot-response branch from 6e25748 to 8a0057a Compare July 9, 2026 15:37

@mcollina mcollina 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.

Amazing results!

Comment thread src/node_http_parser.cc Resolved
Comment thread lib/_http_outgoing.js Resolved
Comment thread lib/_http_outgoing.js Resolved
Comment thread lib/_http_outgoing.js Resolved
@anonrig
anonrig requested a review from mcollina July 9, 2026 16:15

@mcollina mcollina 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.

lgtm

This needs a CITGM run and some validation it doesn't break express, fastify, koa, etc before shipping.

@mcollina mcollina added the notable-change PRs with changes that should be highlighted in changelogs. label Jul 9, 2026
@github-actions

github-actions Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

The notable-change PRs with changes that should be highlighted in changelogs. label has been added by @mcollina.

Please suggest a text for the release notes if you'd like to include a more detailed summary, then proceed to update the PR description with the text or a link to the notable change suggested text comment. Otherwise, the commit will be placed in the Other Notable Changes section.

@mcollina mcollina added the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Jul 9, 2026
@mcollina

mcollina commented Jul 9, 2026

Copy link
Copy Markdown
Member

Also a benchmark CI run would be interesting.

@anonrig

anonrig commented Jul 9, 2026

Copy link
Copy Markdown
Member Author
@mcollina mcollina added the baking-for-lts PRs whose changes need more time before an LTS backport. label Jul 9, 2026
@github-actions github-actions Bot removed the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Jul 9, 2026
@codecov

codecov Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.20074% with 170 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.50%. Comparing base (c58ccfa) to head (3acaa4d).

Files with missing lines Patch % Lines
lib/internal/http/outgoing.js 82.65% 153 Missing and 13 partials ⚠️
lib/internal/http/server.js 96.63% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #64393      +/-   ##
==========================================
- Coverage   90.52%   90.50%   -0.03%     
==========================================
  Files         805      805              
  Lines      285669   286631     +962     
  Branches    55151    55429     +278     
==========================================
+ Hits       258616   259429     +813     
- Misses      17173    17330     +157     
+ Partials     9880     9872       -8     
Files with missing lines Coverage Δ
lib/internal/http/server.js 96.66% <96.63%> (+<0.01%) ⬆️
lib/internal/http/outgoing.js 91.91% <82.65%> (-6.12%) ⬇️

... and 37 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mcollina mcollina 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.

I think this needs a few regression tests before landing. The risky area is not just performance; the native path must preserve the exact HTTP/1 framing behavior of the existing JS path.

Main cases I’d like covered:

  • res.end() with chunked framing but no body must still emit the terminating 0\r\n\r\n.
  • strictContentLength must still throw on the single res.end(chunk) fast path.
  • Trailer must keep the response chunked and must not be rewritten to Content-Length.
  • Transfer-Encoding: chunked;... must still be recognized as chunked framing.
  • Large Content-Length bookkeeping must not be truncated through native out-params.

Implementation note: native buffer bounds checks should avoid off + n <= est because that can overflow before the comparison; prefer subtraction-style checks like off <= est && n <= est - off or checked arithmetic.

Suggested regression file: test/parallel/test-http-outgoing-native-builder-regressions.js

'use strict';

const common = require('../common');
const assert = require('assert');
const http = require('http');
const net = require('net');

function rawRequest(handler, callback) {
  const server = http.createServer(common.mustCall(handler));

  server.listen(0, common.mustCall(() => {
    const socket = net.connect(server.address().port, common.mustCall(() => {
      socket.end('GET / HTTP/1.1\r\n' +
                 'Host: localhost\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    }));

    socket.setEncoding('latin1');
    let raw = '';
    socket.on('data', (chunk) => raw += chunk);
    socket.on('end', common.mustCall(() => {
      server.close(common.mustCall(() => callback(raw)));
    }));
  }));
}

// Empty chunked responses must still terminate the chunked body.
rawRequest((req, res) => {
  res.setHeader('Transfer-Encoding', 'chunked');
  res.end();
}, common.mustCall((raw) => {
  assert.match(raw, /\r\nTransfer-Encoding: chunked\r\n/i);
  assert.match(raw, /\r\n0\r\n\r\n$/);
}));

// Advertising trailers requires chunked framing; do not rewrite to Content-Length.
rawRequest((req, res) => {
  res.setHeader('Trailer', 'X-Checksum');
  res.end('ok');
}, common.mustCall((raw) => {
  assert.match(raw, /\r\nTrailer: X-Checksum\r\n/i);
  assert.match(raw, /\r\nTransfer-Encoding: chunked\r\n/i);
  assert.doesNotMatch(raw, /\r\nContent-Length:/i);
  assert.match(raw, /\r\n2\r\nok\r\n0\r\n\r\n$/);
}));

// Transfer-Encoding parameters are valid transfer-coding parameters and must
// still be recognized as chunked framing.
rawRequest((req, res) => {
  res.setHeader('Transfer-Encoding', 'chunked;foo=bar');
  res.end('ok');
}, common.mustCall((raw) => {
  assert.match(raw, /\r\nTransfer-Encoding: chunked;foo=bar\r\n/i);
  assert.doesNotMatch(raw, /\r\nContent-Length:/i);
  assert.match(raw, /\r\n2\r\nok\r\n0\r\n\r\n$/);
}));

// strictContentLength must be enforced for the single res.end(chunk) path too.
{
  const server = http.createServer(common.mustCall((req, res) => {
    res.strictContentLength = true;
    res.setHeader('Content-Length', '4');

    assert.throws(() => res.end('hello'), {
      code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'
    });

    res.destroy();
    server.close(common.mustCall());
  }));

  server.listen(0, common.mustCall(() => {
    const socket = net.connect(server.address().port, common.mustCall(() => {
      socket.end('GET / HTTP/1.1\r\n' +
                 'Host: localhost\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    }));

    socket.resume();
    socket.on('close', common.mustCall());
  }));
}

// Do not truncate Content-Length bookkeeping through native out-params.
{
  const server = http.createServer(common.mustCall((req, res) => {
    res.setHeader('Content-Length', '4294967296');
    res.writeHead(200);

    assert.strictEqual(res._contentLength, 4294967296);

    res.destroy();
    server.close(common.mustCall());
  }));

  server.listen(0, common.mustCall(() => {
    const socket = net.connect(server.address().port, common.mustCall(() => {
      socket.end('GET / HTTP/1.1\r\n' +
                 'Host: localhost\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    }));

    socket.resume();
    socket.on('close', common.mustCall());
  }));
}

Run with:

tools/test.py test/parallel/test-http-outgoing-native-builder-regressions.js
@pimterry

Copy link
Copy Markdown
Member

+1 on the test concerns, notably we do already have a bunch of existing tests around all this stuff, so it would be really interesting to know which of those are now using the fast path or still on the old path after this change, because either:

  • The existing tests aren't covering this change, and we need lots more testing here because this PR has none.
  • Or the existing tests all now use the fast path (great!) but this means we no longer have any tests covering the existing slow path - we should add some back.

A setup covering a bunch of the important cases structured such that they can run in fast path or slow path mode, to verify both paths against the same set of tests would be fantastic, if that's doable (or at least for some subset of the test cases). My biggest concern here is that these paths will diverge and create very confusing issues, so any way to bind them closer together would be great.

@anonrig
anonrig requested a review from mcollina July 10, 2026 14:06
@mcollina

Copy link
Copy Markdown
Member

CI is red

@anonrig

anonrig commented Jul 10, 2026

Copy link
Copy Markdown
Member Author

CI is red

Applying your suggestion caused a regression in performance. Trying to fix.

@anonrig

anonrig commented Jul 10, 2026

Copy link
Copy Markdown
Member Author

Review feedback status (@mcollina CHANGES_REQUESTED)

The items from the CHANGES_REQUESTED review look fully addressed on the current branch. Asking for a re-review when convenient.

Where it landed

Commit: fb89800e836 — http: fix native builder framing edge cases

Introduces both:

  • test/parallel/test-http-outgoing-native-builder-regressions.js
  • subtraction-style bounds CHECKs in src/node_http_parser.cc

Requested case → coverage mapping

Requested case How it is tested
1. Empty chunked end() still emits 0\r\n\r\n res.setHeader('Transfer-Encoding', 'chunked'); res.end() — asserts Transfer-Encoding: chunked and trailing 0\r\n\r\n
2. strictContentLength on single res.end(chunk) strictContentLength = true, Content-Length: 4, res.end('hello') — asserts ERR_HTTP_CONTENT_LENGTH_MISMATCH
3. Trailer keeps chunked (no Content-Length rewrite) Trailer: X-Checksum + end('ok') — asserts TE chunked, no Content-Length, body 2\r\nok\r\n0\r\n\r\n
4. TE: chunked;params still chunked Transfer-Encoding: chunked;foo=bar — asserts TE preserved, no CL, chunked body
5. Large Content-Length not truncated via native out-params Content-Length: 4294967296 (2^32) — asserts res._contentLength === 4294967296 on the native path
6. Bounds checks use subtraction style src/node_http_parser.cc: CHECK(off <= est && n <= est - off) (and the sn / body_len variants)

Dual-path note

The regression file re-execs itself with --legacy-path (stubbing buildHttpMessage) so framing assertions run against both the native builder and the JS path with the same expectations (also relevant to @pimterry's dual-path concern).

@mcollina — could you take another look when you have a moment? Thanks!

Comment thread lib/_http_server.js Resolved

@mcollina mcollina 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.

lgtm

a final benchmark-ci and citgm run would be useful

@mcollina mcollina 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.

Took another look. There are a few things to fix.

I asked the AI write an analysis of a few points.


1. implicit UTF-8 bodies are emitted as Latin-1

prepareFastBody() correctly computes the UTF-8 byte length (lib/_http_outgoing.js:1689-1708), but the string-header branches concatenate the original string body and always pass the result to writeResponseDirect() as latin1 (lib/_http_outgoing.js:1876-1921). The two branches at lines 1891-1897 are identical, including the branch specifically reached for non-ASCII UTF-8.

A normal implicit response such as:

res.end('€');

keeps _header as a string, advertises Content-Length: 3, and writes the body as the single Latin-1 byte 0xac. The chunked variant similarly emits a chunk size of 3 followed by one byte. On keep-alive connections this can desynchronize all subsequent responses, not merely corrupt one character.

Please add raw-wire tests for non-ASCII res.end(string) with both auto Content-Length and explicit chunked framing. The body must equal Buffer.from(string, 'utf8') byte-for-byte.

2. Caching combined responses by mutable Buffer identity leaks stale bodies

getCombinedResponse() caches the complete wire Buffer in a Map keyed only by body identity (lib/_http_outgoing.js:1777-1830). The Buffer's contents are copied into out, but a later lookup returns that snapshot without checking whether the source Buffer changed. The cache is reused by the small Buffer-body paths at lines 1967-1969 and 1999-2002.

This produces stale cross-response data and can disclose a previous request's payload:

  1. Set res.sendDate = false and use the same cached header block, for example writeHead(200, { 'Content-Length': '3' }).
  2. Send a shared Buffer containing one.
  3. Mutate that same Buffer to contain two.
  4. Send it on the next response.

The second response reuses the cached combined Buffer and sends one. Mutable ArrayBufferViews must not be used as value-cache keys; either do not cache them or cache only immutable string bodies.

3. the global header cache bypasses strict validation

tryFastStoreHeaderObject() computes lenient, but no validation mode is included in any cache key (lib/_http_outgoing.js:609-681). A hit returns at lines 684-700, before validateHeaderName() and validateHeaderValue() at lines 718-719.

Consequently, a relaxed server can seed a cached header containing a control character, and a strict server using the same writeHead() object shape can emit that cached header instead of throwing ERR_INVALID_CHAR.

A deterministic regression test can disable Date, first call:

res.writeHead(200, { 'X-Test': 'a\x01b' });

on a server configured with httpValidation: 'relaxed', and then repeat it on a strict server in the same process. The strict call must throw. Cache hits must never skip validation unless the cache key includes every validation input and the cached entry is known to have been validated under the same policy.

4. High: compact header-cache keys omit state that changes the wire output

The one-header key at lib/_http_outgoing.js:645-652 omits _removedConnection, _removedContLen, _removedTE, and _maxRequestsPerSocket. The two-header key at lines 634-644 also omits _maxRequestsPerSocket. A hit then overwrites the current response's state with the cached entry at lines 689-698.

For example, seed the one-header cache with { 'X-Test': 'same' }, then on an otherwise identical response call:

res.removeHeader('Transfer-Encoding');
res.writeHead(200, { 'X-Test': 'same' });
res.end('ok');

The second response can replay the first response's chunked header and reset _removedTE to false, ignoring the explicit removal. Servers with different maxRequestsPerSocket values can likewise share a cached Keep-Alive: ... max=... line.

Please remove the compact keys or include every input used by header generation and every replayed side effect. Add parity tests for all three removeHeader() framing flags and for servers with different maxRequestsPerSocket values.

5. direct handle-write failures are converted into successful finish

writeResponseDirect() passes a callback to writeGeneric(), but onDirectWrite() ignores its error argument and unconditionally calls onFinish() (lib/_http_outgoing.js:1742-1770). In lib/internal/stream_base_commons.js, both synchronous dispatch errors and negative asynchronous completion statuses are delivered to that callback. Because a callback is present, the asynchronous error path does not destroy the stream itself.

An EPIPE/ECONNRESET can therefore run the response's finish event and end() callback as if the write succeeded while leaving the socket lifecycle inconsistent. The direct path must propagate the error through the same Writable/socket machinery as socket.write(), including destruction and callback/error ordering; it cannot discard the callback argument.

6. High: direct writes can overtake data already queued on the socket

The fast-path guard checks the response's own queue and cork state, but not socket.writableLength or socket.writableCorked (lib/_http_outgoing.js:1837-1849). writeResponseDirect() then bypasses stream.Writable.write() and writes directly to the libuv handle.

A deterministic case is:

res.socket.cork();
res.writeContinue();
res.end('ok');

The 100 Continue response remains in the socket's Writable queue while the final response is sent directly to the handle. The client can observe 200 before 100, and the fast return also skips the normal end() uncork block. The direct path must fall back whenever the socket is corked or has queued/in-flight Writable data.

7. request dispatch bypasses EventEmitter semantics and primordials

parserOnIncoming() reads server._events.request and invokes handler.call(...) directly when there is one listener (lib/_http_server.js:1448-1459). This bypasses an overridden server.emit, domain-aware EventEmitter.prototype.emit, and EventEmitter's rejection handling. It also invokes a user-controlled .call property rather than using a primordial.

A valid listener can demonstrate the immediate compatibility break:

function listener(req, res) {
  res.end('ok');
}
listener.call = null;
http.createServer(listener);

EventEmitter dispatch invokes this callable normally via ReflectApply; the new path throws because handler.call is null. Request delivery should continue through server.emit('request', req, res).

Comment thread src/node_http_parser.cc Outdated
#include "stream_base-inl.h"
#include "v8.h"

#include <cstdio> // snprintf

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.

I think the changes to this file are not used anymore, am I wrong?

Comment thread src/node_http_parser.cc Outdated
// args[7] maxRequests int32 max requests per socket (0 = omit)
// args[8] knownLength int32 content-length if already known, else -1
// args[9] out Float64Array(kOutCount) optional result flags
void BuildHttpMessage(const FunctionCallbackInfo<Value>& args) {

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.

This function and the code around it is a large part of the diff and PR description, but I don't think anything calls it here any more, none of this is used. The last commit replaced the reference to it with:

// The C++ buildHttpMessage path was slower for small messages

That's especially bad because the legacy/fast-path test coverage switch works by stubbing this out, so currently that's not actually doing anything at all 😬

Comment thread lib/_http_outgoing.js Outdated
const d = utcDate();
if (d !== cachedDateValue) {
cachedDateValue = d;
cachedDateHeader = 'Date: ' + d + '\r\n';

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.

Suggested change
cachedDateHeader = 'Date: ' + d + '\r\n';
cachedDateHeader = `Date: ${d}\r\n`;
Comment thread lib/_http_outgoing.js Outdated
Comment on lines +484 to +488
} else if (isUint8Array(data) && data.byteLength > 0) {
queueHeaderWrite(this, header, 'buffer');
} else {
queueHeaderWrite(this, header, 'buffer');
}

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.

The else if (isUint8Array... branch is redundant here.

Comment thread lib/_http_outgoing.js Outdated
queueHeaderWrite(this, header, 'buffer');
}
} else if (typeof data === 'string' && data.length > 0 &&
(encoding === 'latin1' || encoding === 'binary')) {

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.

These checks are repeated often enough to be deduplicated into a utility function.

Comment thread lib/_http_outgoing.js Outdated
const lenient = self._isLenientHeaderValidation();

// Build a cache key. Hot path: two string headers (simple.js) uses a
// short key without a full flags dump when defaults are intact.

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.

hmm... not a correctness problem on it's own, but it's worth noting that this ends up creating different cache keys for semantically equivalent headers whose only difference is the iteration order

e.g. {a: 'foo', b: 'bar'} produces a different cache key than {b: 'bar', a: 'foo'}

Comment thread lib/_http_outgoing.js Outdated
header += key + ': ' + value + '\r\n';

const len = key.length;
if (len !== 4 && len !== 6 && len !== 7 && len !== 10 &&

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.

A code comment here explaining these values would be worthwhile.

Comment thread lib/_http_outgoing.js Outdated
} else if (!this._removedTE) {
!self._removedContLen &&
typeof (contentLength = self._contentLength) === 'number') {
header += 'Content-Length: ' + contentLength + '\r\n';

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.

Use of template literals and concats seems to be inconsistent in several places here. It's worth being consistent.

Suggested change
header += 'Content-Length: ' + contentLength + '\r\n';
header += `Content-Length: ${contentLength}\r\n`;
Comment thread lib/_http_server.js Outdated
const kFinishReq = Symbol('kFinishReq');
const kFinishState = Symbol('kFinishState');
const kFinishServer = Symbol('kFinishServer');
const kPendingSocket = Symbol('kPendingSocket');

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: these aren't following the established naming convention used for the other symbols.

Comment thread lib/_http_server.js Outdated
}

// Symbol flag: socket already has the permanent ServerResponse close hook.
const kHasResCloseListener = Symbol('kHasResCloseListener');

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.

Same... should follow existing naming convention.

Comment thread lib/_http_server.js Outdated
// The following callback is issued after the headers have been read on a
// new message. In this callback we setup the response object and pass it
// to the user.

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.

Suggested change
Serialize the common HTTP/1.1 header block (and optional body) in C++ so
_storeHeader and ServerResponse.end avoid repeated JS string
concatenation and multi-write path overhead. The public API and wire
format are unchanged; complex cases fall back to the existing JS path.

On benchmark/http/simple.js (bytes/4/1, 50 connections, 5s) this raised
throughput from ~80k to ~118-126k req/s (~+48% to +58%) on the same
machine.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Revert incidental ConnectionsList reformatting in node_http_parser.cc,
document the buildHttpMessage flag and out-param slots in JS, and avoid
Buffer.concat when pairing headers with a body by queueing a separate
latin1 header write instead.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Hot writeHead()+end() now flushes via tryFastFlushEnd instead of the
full write_()/extra empty write path. Server-side native headers stay as
Buffers (no latin1 string copy) until write time; the C++ builder writes
into a single malloc transferred to Buffer (no std::string + Copy).
Reuse a scratch flat-header array and a prebuilt 200 status line.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Address review feedback: keep Trailer/TE-with-params on the chunked
path, emit the empty chunked terminator from the single-shot fast path,
enforce strictContentLength on res.end(chunk), avoid truncating large
Content-Length values via Float64 out-params, and use overflow-safe
buffer bounds checks. Add dual-path regression coverage.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Keep writeHead()/_storeHeader() on the legacy JS path: the C++ builder
was a net regression for small-header (simple.js) and many-header
(headers.js) workloads. Reserve buildHttpMessage for tryFastEnd()
single-shot end(body) with bodies up to 16KiB, and never concatenate
larger payloads into a combined headers+body write.

Also type buildHttpMessage on the http_parser binding.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Avoid cork/uncork on single-write flushes, combine small Buffer bodies
with the header into one write for the simple.js type=buffer path, and
use corked dual writes (not uncorked queued writes) for large string
bodies so end-vs-write-end stays competitive without O(n) copies.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Cache complete wire-format responses for repeated writeHead+end,
write small responses through the stream handle, and cut keep-alive
overhead with a permanent socket close hook and deferred idle
timeouts. Also fix binary Content-Disposition framing under the
latin1 flush path and several finish/request edge cases.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
@cursor
cursor Bot force-pushed the http-native-single-shot-response branch from 0a0b3cf to 0307984 Compare November 28, 2026 01:56
anonrig and others added 5 commits November 28, 2026 02:11
The JS fast path replaced the C++ builder, but the binding, its
includes, and the http_parser typings were still in the diff. Drop
them so src/node_http_parser.cc matches main.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Assisted-by: Cursor
Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
Use a template for the cached Date header and for Content-Length
lines, share the repeated encoding checks, and drop the redundant
Uint8Array branch in _send(). Document the framing-header length
filter and that header-cache keys follow enumeration order.

Rename the new server symbols to the http.server.* description style
used beside them, and drop the extra blank line before
parserOnIncoming.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Assisted-by: Cursor
Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
Run the chunked terminator, trailer, transfer-encoding parameter,
strictContentLength, and large Content-Length cases on both the fast
path and the legacy store/write path.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Assisted-by: Cursor
Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
The cached Date line is built locally, so the import is unused.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Assisted-by: Cursor
Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
tryFastEnd builds the message in JS.

Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com>
Assisted-by: Cursor
Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
@mcollina

Copy link
Copy Markdown
Member

can you add benchmarks?

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

Labels

baking-for-lts PRs whose changes need more time before an LTS backport. c++ Issues and PRs that require attention from people who are familiar with C++. http_parser Issues and PRs related to the HTTP parser implementation or http_parser binding. http Issues and PRs related to the http subsystem. needs-ci PRs that need a full CI run. notable-change PRs with changes that should be highlighted in changelogs.

6 participants