`BENCHMARKS.md` answered "how does this compare to fastify" and nothing answered "did the last two months cost anything". Those are different questions and the second one is the one a release has to pass, so it needed its own tool rather than a second reading of the first one's table. `npm run bench:compare` runs two worktrees of this repository against each other on one box in one sitting, alternating which side goes first each round so drift lands on both rather than on whichever ran second. It shares one `node_modules` and one byte-identical server file, which holds everything except `src/` constant — and is only sound while `package.json` has not moved between the revisions, which the header says out loud. Three things it refuses to do quietly, each of which it did once before being taught not to: - A run whose connections all errored reports 0 req/s, and a median absorbs that without complaint. Non-2xx, errors and timeouts now fail the case, and so does a zero. Not on the warmup, which exists to absorb exactly the cold-start noise a fresh server produces. - A range-overlap check flags a row as directional, and its own documentation says to treat that as "measure it again", never as a result. Three samples of two overlapping distributions separate by chance often enough to have produced a regression report that five rounds then erased. - `cors.origins` invocations are counted rather than timed. The benchmark's predicate is a `Set` lookup, so calls saved are invisible in req/s — but the option takes a function so it can be a lookup, and there the same saving is a network round trip. **The runtime servers finally run.** `bench/servers/green-tea-deno.ts` and `-bun.ts` were written in July and referenced by nothing — not the runner, not a script, not CI. The runner only knew how to launch Node, so both sat there looking like coverage the table did not have. Launchers are per runtime now and they get their own section, kept out of the cross-framework tables because a green-tea-on-Bun row beside fastify-on-Node reads as a comparison nobody made. `green-tea-node.ts` is new and loads `dist/` like its Deno and Bun counterparts. The runtimes table exists to vary the runtime, and a Node row reading `src/` through tsx would have varied the load form at the same time. A route-table-width dimension, because every matcher cost scales with how many candidates a request walks past and the tables here use six routes. Three separate matcher findings measured as noise before this existed, which said nothing about them and everything about the instrument. Finally, `run.ts` preserves whatever sits below a marker instead of overwriting the file whole. The tables answer what is true today; the notes below them carry which release moved a number and what the move bought, and regenerating used to delete that silently. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
244 lines
8.8 KiB
TypeScript
244 lines
8.8 KiB
TypeScript
import autocannon from 'autocannon';
|
|
import { spawn, execSync } from 'child_process';
|
|
import os from 'os';
|
|
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
import { SCENARIOS, STEP_ROUTES } from './scenarios';
|
|
import { aggregate } from './stats';
|
|
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
|
|
|
|
/** Hand-written notes start here and are carried across regenerations verbatim. */
|
|
const KEEP_BELOW = '<!-- keep-below: hand-written, survives `npm run bench` -->';
|
|
|
|
const SMOKE = process.env.BENCH_SMOKE === '1';
|
|
const CONNS = Number(process.env.BENCH_CONNS ?? 100);
|
|
const DURATION = SMOKE ? 1 : Number(process.env.BENCH_DURATION ?? 10);
|
|
const RUNS = SMOKE ? 1 : Number(process.env.BENCH_RUNS ?? 5);
|
|
const WARMUP = SMOKE ? 0 : Number(process.env.BENCH_WARMUP ?? 1);
|
|
|
|
/** Whether a runtime is on PATH. */
|
|
function which(cmd: string): boolean {
|
|
try {
|
|
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function log(msg: string): void {
|
|
process.stderr.write(`[bench] ${msg}\n`);
|
|
}
|
|
|
|
interface RunResult {
|
|
reqSec: number;
|
|
p50: number;
|
|
p99: number;
|
|
p999: number;
|
|
}
|
|
|
|
/**
|
|
* How each server is launched. Node servers are TypeScript run through tsx; the Deno and Bun ones
|
|
* are handed to their own runtime, which is the whole point of measuring them.
|
|
*/
|
|
const LAUNCHERS: Record<string, (file: string) => { cmd: string; args: string[] }> = {
|
|
node: (file) => ({ cmd: process.execPath, args: ['--import', 'tsx', file] }),
|
|
// `-A` rather than an enumerated permission set: this is a benchmark server on loopback, and a
|
|
// missing flag fails as a boot timeout that reads like a framework problem.
|
|
deno: (file) => ({ cmd: 'deno', args: ['run', '-A', file] }),
|
|
bun: (file) => ({ cmd: 'bun', args: [file] }),
|
|
};
|
|
|
|
async function spawnServer(
|
|
name: string,
|
|
extraEnv: Record<string, string> = {},
|
|
runtime: 'node' | 'deno' | 'bun' = 'node',
|
|
): Promise<{ port: number; kill: () => Promise<void> }> {
|
|
const { cmd, args } = LAUNCHERS[runtime](`bench/servers/${name}.ts`);
|
|
const child = spawn(cmd, args, {
|
|
env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...extraEnv },
|
|
});
|
|
let stderr = '';
|
|
child.stderr.on('data', (d) => (stderr += d));
|
|
const port = await new Promise<number>((resolve, reject) => {
|
|
const t = setTimeout(() => {
|
|
child.kill('SIGKILL');
|
|
reject(new Error(`${name} failed to boot (no READY in 10s):\n${stderr}`));
|
|
}, 10000);
|
|
let buf = '';
|
|
child.stdout.on('data', (d) => {
|
|
buf += d;
|
|
const m = /READY (\d+)/.exec(buf);
|
|
if (m) {
|
|
clearTimeout(t);
|
|
resolve(Number(m[1]));
|
|
}
|
|
});
|
|
child.on('exit', (code) => {
|
|
clearTimeout(t);
|
|
reject(new Error(`${name} exited early (code ${code}):\n${stderr}`));
|
|
});
|
|
});
|
|
const kill = (): Promise<void> =>
|
|
new Promise<void>((resolve) => {
|
|
child.on('exit', () => resolve());
|
|
child.kill('SIGTERM');
|
|
setTimeout(() => {
|
|
try {
|
|
child.kill('SIGKILL');
|
|
} catch {
|
|
/* already dead */
|
|
}
|
|
}, 2000);
|
|
});
|
|
return { port, kill };
|
|
}
|
|
|
|
async function bench(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise<RunResult> {
|
|
const r: any = await autocannon({
|
|
url: `http://127.0.0.1:${port}${path}`,
|
|
connections: CONNS,
|
|
duration: DURATION,
|
|
pipelining: 1,
|
|
method,
|
|
headers: body ? { 'content-type': 'application/json' } : undefined,
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
return { reqSec: r.requests.average, p50: r.latency.p50, p99: r.latency.p99, p999: r.latency.p99_9 };
|
|
}
|
|
|
|
async function measure(port: number, path: string, method: 'GET' | 'POST', body?: unknown): Promise<RunResult[]> {
|
|
for (let i = 0; i < WARMUP; i++) await bench(port, path, method, body); // discarded
|
|
const runs: RunResult[] = [];
|
|
for (let i = 0; i < RUNS; i++) runs.push(await bench(port, path, method, body));
|
|
return runs;
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const frameworks = ['raw-http', 'fastify', 'express', 'green-tea', 'nestjs-express', 'nestjs-fastify'];
|
|
const scenarioBlocks: ScenarioBlock[] = SCENARIOS.map((s) => ({
|
|
title: s.title,
|
|
name: s.name,
|
|
approximation: s.approximation,
|
|
rows: [],
|
|
}));
|
|
const stepScaling: RenderData['stepScaling'] = [];
|
|
const secureCost: RenderData['secureCost'] = [];
|
|
const runtimes: RenderData['runtimes'] = [];
|
|
|
|
for (const fw of frameworks) {
|
|
log(`booting ${fw}`);
|
|
const { port, kill } = await spawnServer(fw);
|
|
try {
|
|
for (const s of SCENARIOS) {
|
|
log(`${fw} / ${s.name}`);
|
|
const runs = await measure(port, s.path, s.method, s.body);
|
|
const agg = aggregate(runs.map((r) => r.reqSec));
|
|
const last = runs[runs.length - 1];
|
|
const row: Row = {
|
|
framework: fw,
|
|
reqSec: { median: agg.median, min: agg.min, max: agg.max, stddev: agg.stddev, cv: agg.cv },
|
|
p50: last.p50,
|
|
p99: last.p99,
|
|
p999: last.p999,
|
|
};
|
|
scenarioBlocks.find((b) => b.name === s.name)!.rows.push(row);
|
|
}
|
|
if (fw === 'green-tea') {
|
|
for (const sr of STEP_ROUTES) {
|
|
const runs = await measure(port, sr.path, 'GET');
|
|
stepScaling.push({ path: sr.path, steps: sr.steps, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
|
}
|
|
// Reuse the hello scenario's already-computed median so the parity row exactly matches
|
|
// the green-tea hello-table number (rather than re-measuring the same server/config).
|
|
const helloMedian = scenarioBlocks
|
|
.find((b) => b.name === 'hello')!
|
|
.rows.find((r) => r.framework === 'green-tea')!.reqSec.median;
|
|
secureCost.push({ label: 'security:false (parity)', reqSec: helloMedian });
|
|
}
|
|
} finally {
|
|
await kill();
|
|
}
|
|
}
|
|
|
|
log('booting green-tea (GT_SECURE=1)');
|
|
{
|
|
const { port, kill } = await spawnServer('green-tea', { GT_SECURE: '1' });
|
|
try {
|
|
secureCost.push({
|
|
label: 'security:true (default)',
|
|
reqSec: aggregate((await measure(port, '/hello', 'GET')).map((r) => r.reqSec)).median,
|
|
});
|
|
} finally {
|
|
await kill();
|
|
}
|
|
}
|
|
|
|
// green-tea on each runtime it supports. Kept out of the cross-framework tables above on purpose:
|
|
// those compare frameworks on one runtime, and a green-tea-on-Bun row sitting beside
|
|
// fastify-on-Node would read as a comparison nobody made.
|
|
//
|
|
// All three load `dist/`, so what varies is the runtime. Skipped rather than failed when a
|
|
// runtime is not installed — a contributor without Bun should still get every other table.
|
|
for (const { runtime, server } of [
|
|
{ runtime: 'node', server: 'green-tea-node' },
|
|
{ runtime: 'deno', server: 'green-tea-deno' },
|
|
{ runtime: 'bun', server: 'green-tea-bun' },
|
|
] as const) {
|
|
if (runtime !== 'node' && !which(runtime)) {
|
|
log(`skipping ${runtime}: not installed`);
|
|
continue;
|
|
}
|
|
|
|
log(`booting green-tea on ${runtime}`);
|
|
|
|
try {
|
|
const { port, kill } = await spawnServer(server, {}, runtime);
|
|
|
|
try {
|
|
for (const s of SCENARIOS) {
|
|
const runs = await measure(port, s.path, s.method, s.body);
|
|
runtimes.push({ runtime, scenario: s.title, reqSec: aggregate(runs.map((r) => r.reqSec)).median });
|
|
}
|
|
} finally {
|
|
await kill();
|
|
}
|
|
} catch (error) {
|
|
// A runtime that cannot boot the built bundle is worth reporting, not worth losing the rest
|
|
// of the run over.
|
|
log(`${runtime} failed to boot: ${(error as Error).message.split('\n')[0]}`);
|
|
}
|
|
}
|
|
|
|
const commit = execSync('git rev-parse --short HEAD').toString().trim();
|
|
const data: RenderData = {
|
|
env: {
|
|
date: new Date().toISOString().slice(0, 10),
|
|
commit,
|
|
node: process.version,
|
|
os: os.platform(),
|
|
cpu: `${os.cpus()[0].model} (${os.cpus().length} cores)`,
|
|
ram: `${Math.round(os.totalmem() / 1e9)} GB`,
|
|
pinned: false,
|
|
},
|
|
config: { conns: CONNS, duration: DURATION, runs: RUNS, warmup: WARMUP, pipelining: 1 },
|
|
scenarios: scenarioBlocks,
|
|
stepScaling,
|
|
secureCost,
|
|
runtimes,
|
|
};
|
|
// Everything below the marker is written by hand and survives a re-run. The generated tables
|
|
// answer "how fast is it today"; the notes below them carry what a table cannot — which release
|
|
// moved a number, and what the move bought. Regenerating and silently deleting that is how the
|
|
// history this file exists to keep gets lost a second time.
|
|
const previous = existsSync('BENCHMARKS.md') ? readFileSync('BENCHMARKS.md', 'utf8') : '';
|
|
const kept = previous.includes(KEEP_BELOW) ? previous.slice(previous.indexOf(KEEP_BELOW)) : '';
|
|
writeFileSync('BENCHMARKS.md', renderMarkdown(data) + (kept ? `\n${kept}` : ''));
|
|
writeFileSync('bench/results.json', JSON.stringify(data, null, 2));
|
|
log('wrote BENCHMARKS.md + bench/results.json');
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|