Repository navigation
Description
What version of Bun is running?
1.3.14 (also reproduced on 1.3.13). Tag bun-v1.3.14 = commit 0d9b296af33f2b851fcbf4df3e9ec89751734ba4.
What platform is your computer?
Linux x64.
What steps can reproduce the bug?
A node:http keep-alive server discards an already-received next request on a reused connection — the handler never runs for it — when the previous response satisfied its fixed Content-Length via res.write() and was finalized by a deferred res.end() (the canonical case: fs.createReadStream(file).pipe(res), whose 'end' fires on a later event-loop iteration). Bun closes with a graceful FIN and no Connection: close, so a proxy that legitimately reuses the connection gets EOF → 502. Node.js serves 100%; Bun.serve is unaffected.
The window is tiny in the wild (~0.1% loss). This repro makes it deterministic by deferring end() to a timer — no proxy, no special transport, just node:http + a raw TCP keep-alive client:
// repro.mjs — run with `bun repro.mjs` (BUG) and `node repro.mjs` (ok)
import http from "node:http";
import net from "node:net";
const BODY = Buffer.alloc(64, "a");
let handled = 0;
const server = http.createServer((req, res) => {
handled++;
res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": String(BODY.length) });
res.write(BODY); // body is now complete on the wire...
setTimeout(() => res.end(), 100); // ...but end() is deferred to a later loop iteration
});
function reuse(port, count) { // strict sequential keep-alive client
return new Promise(resolve => {
let sent = 0, got = 0, buf = Buffer.alloc(0);
const s = net.connect(port, "127.0.0.1");
const send = () => { sent++; s.write(`GET /r${sent} HTTP/1.1\r\nHost: x\r\nConnection: keep-alive\r\n\r\n`); };
s.on("connect", send);
s.on("data", c => {
buf = Buffer.concat([buf, c]);
for (;;) {
const h = buf.indexOf("\r\n\r\n"); if (h < 0) break;
const m = /content-length:\s*(\d+)/i.exec(buf.toString("latin1", 0, h));
const total = h + 4 + (m ? +m[1] : 0); if (buf.length < total) break;
buf = buf.subarray(total); got++;
if (got >= count) { s.end(); return resolve({ sent, got }); }
send();
}
});
const done = () => resolve({ sent, got });
s.on("end", done); s.on("close", done); s.on("error", done);
});
}
server.listen(0, "127.0.0.1", async () => {
const port = server.address().port;
let sent = 0, got = 0;
for (let i = 0; i < 10; i++) { const r = await reuse(port, 4); sent += r.sent; got += r.got; }
console.log(`sent=${sent} got=${got} handled=${handled} => ${got < sent ? "BUG: reused requests dropped" : "ok"}`);
server.close();
});$ bun repro.mjs
sent=40 got=10 handled=10 => BUG: reused requests dropped
$ node repro.mjs
sent=80 got=80 handled=80 => ok
handled < sent is the signature: dropped requests are ACKed by the TCP stack but never reach the handler. Only this write()-then-deferred-end() + Content-Length pattern is affected — res.end(buffer), chunked (no Content-Length), Readable.from([buf]).pipe(res), and res.write() + process.nextTick(() => res.end()) are all fine.
What is the expected behavior?
A complete HTTP/1.1 response without Connection: close must leave the connection usable for the next request (RFC 9112 §9.6). Node does; Bun should too.
Root cause
node:http writes a Content-Length body with uWS HttpResponse::write() and finalizes with a separate end(). Plain write() never advances httpResponseData->offset, so it never calls markDone() — only end()/endStream() does. So after res.write(body) the response is complete on the wire but uWS stays HTTP_RESPONSE_PENDING until the deferred end(). fs.ReadStream opens that window because its 'end' fires a loop iteration later (after a socket poll). A keep-alive client reuses the connection in the window; uWS reads + ACKs the next request, then the anti-pipelining guard fires:
// packages/bun-uws/src/HttpContext.h (onData request callback)
if (httpResponseData->state & HttpResponseData<SSL>::HTTP_RESPONSE_PENDING) {
us_socket_close((us_socket_t *) s, 0, nullptr); // code 0, no SO_LINGER -> plain close() -> FIN
return nullptr; // request dropped before routing
}uWS has already drained the request into userspace, so close() emits a FIN (not RST) and the request is discarded — matching the fingerprint (FIN, no Connection: close, request ACKed but never handled). The non-fs / res.end(buffer) / chunked variants don't reproduce because they finalize in the same loop iteration (or the client can't reuse early). Bun.serve is immune — it streams Content-Length bodies via uWS tryEnd() (src/runtime/server/RequestContext.zig), which markDone()s the instant offset == totalSize. The bug is specific to node:http — src/js/node/_http_server.ts, ServerResponse.prototype.write.
Proposed fix
Finalize a Content-Length response as soon as write() has delivered the whole body (mirroring tryEnd()), instead of waiting for a deferred end(). Call this at the end of ServerResponse.prototype.write's success path:
function maybeAutoFinishContentLength(res, handle) {
if (res.finished || res.writableEnded || !res._hasBody || res.chunkedEncoding) return;
if (res.hasHeader("transfer-encoding")) return;
let contentLength = res._contentLength ?? res.getHeader("content-length");
if (contentLength == null) return;
if (typeof contentLength !== "number") contentLength = parseInt(contentLength, 10);
if (!(contentLength >= 0)) return;
if ((handle.getBytesWritten?.() ?? 0) >= contentLength) res.end(); // native body-byte total
}Only fires when write() alone satisfies the full declared Content-Length (the pattern that opens the window); res.end(...), chunked, and res.end(buffer) are unaffected.
Validation
Applied as a runtime monkeypatch (identical logic) on unmodified bun:1.3.14: the deterministic repro above goes from 20→0 dropped; under realistic keep-alive connection-pool load, 0 dropped across 14,256 requests (vs 9 and 7 in two unpatched baselines of 4,752 each); buffer/chunked/readable/writeend modes unaffected. A deterministic regression test (also passing on Node) is ready.
Behaviorally validated via the monkeypatch only — not yet compiled into a build and run against Bun's
test/js/node/httpsuite (no build toolchain on hand); that's the remaining step before merge.
Activity
github-actions commentedon Jun 5, 2026
Found 1 possible duplicate issue:
This issue will be automatically closed as a duplicate in 3 days.
🤖 Generated with Claude Code
robobun commentedon Jul 24, 2026
Fixed by #32488.
Verified on main at df84f8d: a
node:httpkeep-alive server withContent-Lengthbody viares.write()+ deferredres.end()no longer drops the next reused request — all 40/40 sequential keep-alive requests are handled, matching Node.