From 1c4f3fb8cbbd323d1118176bd1c04a0e4060ba09 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 11:01:52 -0500 Subject: [PATCH] perf(http): skip the request-budget bookkeeping when no budget is set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every request registered a `close` listener and set an acquire flag, including in the apps — most of them — that never set `maxConcurrentRequests`. `acquire()` returns `true` unconditionally when the limit is unset and `release()` early-returns for the same reason, so both the closure and the EventEmitter registration were pure overhead: a per-request cost, on the hot path, for a feature that is off. The gate exposes `limited` rather than each adapter re-deriving it from `opts`, because the gate is what knows. `acquire()` cannot say it — its `true` means "admitted" and "not counting" alike, which is exactly why a caller reading only the result pays either way. With a budget configured nothing changes: the listener is what releases a slot when a client disconnects mid-handler, and it comes back. The guard is about the unset case, not about dropping the feature, and the test asserts both halves so a fix for one cannot quietly become a regression in the other. Verified non-vacuous: reverting `src/` fails the assertion with the listener it counts. Closes #74. Signed-off-by: Diego Resendez --- src/http/request-gate.ts | 13 +++++++++++++ src/http/server.ts | 18 +++++++++++------ src/http/web.ts | 2 +- test/http.test.ts | 42 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 68 insertions(+), 7 deletions(-) diff --git a/src/http/request-gate.ts b/src/http/request-gate.ts index e6e815c..96ac7ec 100644 --- a/src/http/request-gate.ts +++ b/src/http/request-gate.ts @@ -5,6 +5,16 @@ * handler execution finishes; a returned stream does not hold the slot for the stream's lifetime. */ export interface RequestGate { + /** + * Whether a budget is actually configured. + * + * Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what + * knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading + * only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either + * way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every + * per-request cost behind it should be skipped entirely. + */ + limited: boolean; acquire(): boolean; release(): void; } @@ -12,8 +22,11 @@ export interface RequestGate { /** Creates an unlimited gate when `limit` is undefined or non-positive. */ export function createRequestGate(limit: number | undefined): RequestGate { let active = 0; + const limited = limit !== undefined && limit > 0; return { + limited, + acquire(): boolean { if (limit === undefined || limit <= 0) return true; if (active >= limit) return false; diff --git a/src/http/server.ts b/src/http/server.ts index 38adf16..a07e50c 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -136,12 +136,18 @@ function createRequestHandler(cfg: HandlerConfig) { return; } - acquired = true; - res.once('close', () => { - if (!acquired) return; - acquired = false; - gate.release(); - }); + // Both the flag and the listener are skipped when no budget is configured, which is most + // applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an + // EventEmitter registration per request, on the hot path, for a feature that is off is a cost + // with nothing on the other side of it. + if (gate.limited) { + acquired = true; + res.once('close', () => { + if (!acquired) return; + acquired = false; + gate.release(); + }); + } result = await handle( routes, diff --git a/src/http/web.ts b/src/http/web.ts index dd4497e..ab09644 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -180,7 +180,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { }); } - acquired = true; + acquired = gate.limited; result = await handle( routes, diff --git a/test/http.test.ts b/test/http.test.ts index ff92d89..ebe1804 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, test, vi } from 'vitest'; import * as net from 'node:net'; +import { ServerResponse } from 'node:http'; import { once } from 'node:events'; import { Bus } from '../src/bus'; import { matchRoute, parseQuery, createHttpServer } from '../src/http'; @@ -419,4 +420,45 @@ describe('request hardening', () => { server.close(); }); + + // `maxConcurrentRequests` is opt-in and unlimited by default, so the overwhelming majority of + // apps used to pay a closure and an EventEmitter registration per request for a feature that is + // off. Small in absolute terms, and on the hot path, which is why it is asserted rather than + // trusted: a `res.once('close')` is exactly the kind of line that comes back. + it('registers no per-request close listener when no request budget is configured', async () => { + const closeListeners: string[] = []; + // Typed loosely on purpose: `once` is an overloaded EventEmitter signature and the spy only + // needs to see the event name before handing the call straight back to the real one. + const proto = ServerResponse.prototype as unknown as { + once(event: string | symbol, listener: (...args: unknown[]) => void): unknown; + }; + const realOnce = proto.once; + const spy = vi.spyOn(proto, 'once').mockImplementation(function (this: unknown, event, listener) { + if (event === 'close') closeListeners.push('close'); + return realOnce.call(this, event, listener); + }); + + try { + const unlimited = createHttpServer([{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }]); + await new Promise((r) => unlimited.listen(0, r)); + expect((await fetch(`${getUrl(unlimited)}/ping`)).status).toBe(200); + expect(closeListeners).toHaveLength(0); + unlimited.close(); + + // With a budget set, the listener is what releases the slot on a client disconnect, so it + // has to come back — the guard is about the unset case, not about dropping the feature. + const limited = createHttpServer( + [{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }], + [], undefined, undefined, + { limits: { maxConcurrentRequests: 4 } }, + ); + await new Promise((r) => limited.listen(0, r)); + expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200); + expect(closeListeners.length).toBeGreaterThan(0); + limited.close(); + } finally { + spy.mockRestore(); + } + }); + });