Merge feature/benchmarks: honest autocannon harness vs Express/Fastify/NestJS/raw-http
CI / build (push) Has been cancelled

Q2 complete. Repeatable bench/ harness (devDep-only: autocannon, express@5,
fastify@5, @nestjs/*, tsx) — isolated child-process servers, warmup + median of
N runs, writes BENCHMARKS.md. Compares green-tea vs raw http, Express 5, Fastify
5, and NestJS on both platform-express and platform-fastify. Fairness controls
(security-header parity via security:false, keep-alive parity, etag/x-powered-by
off, equal validation work, disclosed single-box/loopback contention) verified
live. green-tea is the fastest high-level framework in 3/4 scenarios. Review
caught real fairness bugs pre-merge (Fastify 72s keep-alive, double-measured
parity row, missing charset/scope disclosures).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-06 23:49:43 -05:00
commit 1abcc51620
18 files changed
+4593 -1

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
> **TL;DR**: `raw-http` posted the highest median req/s in the first benchmarked scenario on this box — see the single-box caveat below before reading anything into the absolute numbers.
# green-tea Benchmarks
## Environment
- **Date**: 2026-07-07
- **Commit**: fe1831a
- **Node**: v22.22.2
- **OS**: darwin
- **CPU**: Apple M4 Max (16 cores)
- **RAM**: 69 GB
- **Core-pinned**: no
- **autocannon config**: 100 connections, 5s duration, 3 runs (1 warmup discarded), pipelining 1
> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over
> loopback on the same machine, sharing the same cores as the server processes they measured. That
> contention overstates absolute throughput for every framework and compresses the differences *between*
> frameworks — do not read the raw req/s numbers as what you would see on separate client/server hardware.
> The honest takeaway is the **ratio** between frameworks in the same table, not any single absolute
> number. Note also that green-tea runs with `security:false` in the cross-framework tables below, purely
> for response-header parity with the other frameworks (none of which set the same security headers by
> default) — the real cost of running green-tea secure-by-default is measured separately in its own
> section further down.
## Cross-framework scenarios
### JSON hello (overhead)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 115,398 | 0.00 | 1.00 | 1.00 | 0.3% | 114,822–115,539 |
| green-tea | 98,093 | 0.00 | 1.00 | 2.00 | 0.3% | 98,054–98,669 |
| nestjs-fastify | 95,034 | 1.00 | 1.00 | 2.00 | 0.5% | 94,240–95,264 |
| fastify | 86,765 | 1.00 | 2.00 | 2.00 | 0.3% | 86,496–87,123 |
| express | 24,366 | 3.00 | 5.00 | 8.00 | 0.2% | 24,283–24,418 |
| nestjs-express | 21,762 | 4.00 | 6.00 | 10.00 | 0.4% | 21,698–21,896 |
### Route param
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 116,333 | 0.00 | 1.00 | 1.00 | 0.2% | 115,974–116,410 |
| green-tea | 93,434 | 1.00 | 2.00 | 2.00 | 0.2% | 93,152–93,613 |
| nestjs-fastify | 89,312 | 1.00 | 2.00 | 2.00 | 0.1% | 89,235–89,530 |
| fastify | 86,278 | 1.00 | 2.00 | 2.00 | 0.3% | 86,138–86,765 |
| express | 23,835 | 3.00 | 5.00 | 8.00 | 0.5% | 23,803–24,046 |
| nestjs-express | 20,955 | 4.00 | 6.00 | 11.00 | 0.6% | 20,949–21,202 |
### Pipeline (3 steps) (approximation)
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 113,491 | 0.00 | 1.00 | 1.00 | 0.8% | 112,531–114,810 |
| nestjs-fastify | 87,328 | 1.00 | 2.00 | 2.00 | 0.4% | 86,867–87,661 |
| fastify | 85,024 | 1.00 | 2.00 | 2.00 | 0.3% | 84,512–85,178 |
| green-tea | 84,896 | 1.00 | 2.00 | 2.00 | 0.5% | 84,243–85,267 |
| express | 23,950 | 3.00 | 5.00 | 8.00 | 0.2% | 23,902–24,011 |
| nestjs-express | 20,824 | 4.00 | 6.00 | 11.00 | 0.1% | 20,805–20,878 |
### POST JSON + validation
| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |
| --- | --- | --- | --- | --- | --- | --- |
| raw-http | 100,141 | 0.00 | 1.00 | 2.00 | 0.2% | 99,846–100,294 |
| green-tea | 77,178 | 1.00 | 2.00 | 2.00 | 0.1% | 77,126–77,254 |
| fastify | 63,722 | 1.00 | 2.00 | 3.00 | 0.1% | 63,574–63,760 |
| nestjs-fastify | 59,146 | 1.00 | 3.00 | 3.00 | 0.3% | 59,005–59,376 |
| express | 20,098 | 4.00 | 6.00 | 12.00 | 0.2% | 20,056–20,174 |
| nestjs-express | 18,856 | 5.00 | 7.00 | 30.00 | 0.5% | 18,853–19,067 |
## Step-scaling (green-tea)
| Path | Steps | req/s |
| --- | --- | --- |
| /steps/0 | 0 | 92,282 |
| /steps/3 | 3 | 81,530 |
| /steps/5 | 5 | 71,994 |
Each additional pipeline step costs roughly 4,058 req/s (-22.0% over 5 steps), on this box.
## Cost of secure-by-default (green-tea)
| Label | req/s |
| --- | --- |
| security:false (parity) | 98,093 |
| security:true (default) | 92,998 |
The real cost of running secure-by-default (rather than the parity-mode `security:false` used above) is ~5.2% req/s on this box.
> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs
> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately
> measured yet (deferred) — so this table is narrower than the design spec's 4-point plan.
## Methodology
- **Parity controls**: every framework is configured for the fairest possible comparison —
security-header parity (matching header sets across frameworks, or green-tea running with
`security:false` in the cross-framework tables), keep-alive parity, and Express's `etag` and
`x-powered-by` disabled. The `/validate` scenario always sends a valid body so every framework
takes its success path and performs equivalent validation work.
- **Pipeline approximation**: scenarios marked `(approximation)` (e.g. the multi-step pipeline route)
do not have an exact one-to-one equivalent in every framework; the closest reasonable approximation
is used for each framework and the result should be read as indicative, not as an exact apples-to-apples
measurement.
- **Serialization parity**: all four frameworks serialize their JSON responses with plain
`JSON.stringify` in these benchmarks. Fastify's `fast-json-stringify` response serializer is
deliberately **not** engaged — only its input `schema.body` validation is used — so no framework
gets a serialization fast path the others lack.
- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send
`Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.
This is a minor header-byte asymmetry that is disclosed here rather than normalized away.
- **NestJS runs on an underlying adapter** (Express or Fastify): the `nestjs-express` / `nestjs-fastify`
rows measure Nest's DI / decorator / routing overhead **on top of** that adapter, so compare each
against its own base (`express` / `fastify`) rather than against the field. Nest's idiomatic
`ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check
as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled
on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.
+11
View File
@@ -131,6 +131,17 @@ The handler signature declares exactly what it wants — in any order, nothing m
1. **Typed functional core (`flow`)** — `flow().step(...).step(...).handle(...)`; step outputs accumulate into the context type (`Acc & Out`). This is where the compile-time guarantee lives.
2. **Declarative decorator layer** — `@Provider/@Step/@Module/@Route/@Get/@Transformer` + argument decorators. Emits runtime metadata, builds and topologically sorts the graph, validates at boot.
## Benchmarks
Reproducible autocannon comparison vs Express 5, Fastify 5, and raw Node `http`
lives in [BENCHMARKS.md](./BENCHMARKS.md) (regenerate with `npm run bench`).
Numbers are single-box + loopback — absolute req/s is overstated and
inter-framework differences are compressed; treat cross-framework *ratios* as
the honest signal, not the raw throughput. The cross-framework table runs
green-tea with `security:false` for header parity; the real cost of green-tea's
secure-by-default headers/validation is measured separately in that file.
## Development
```bash
+214
View File
@@ -0,0 +1,214 @@
export interface EnvInfo {
date: string;
commit: string;
node: string;
os: string;
cpu: string;
ram: string;
pinned: boolean;
}
export interface Config {
conns: number;
duration: number;
runs: number;
warmup: number;
pipelining: number;
}
export interface Row {
framework: string;
reqSec: { median: number; min: number; max: number; stddev: number; cv: number };
p50: number;
p99: number;
p999: number;
}
export interface ScenarioBlock {
title: string;
name: string;
approximation?: boolean;
rows: Row[];
}
export interface RenderData {
env: EnvInfo;
config: Config;
scenarios: ScenarioBlock[];
stepScaling: { path: string; steps: number; reqSec: number }[];
secureCost: { label: string; reqSec: number }[];
}
const fmtInt = (n: number): string => Math.round(n).toLocaleString('en-US');
const fmtLatency = (n: number): string => n.toFixed(2);
const fmtCv = (n: number): string => `${(n * 100).toFixed(1)}%`;
const fmtRange = (min: number, max: number): string => `${fmtInt(min)}–${fmtInt(max)}`;
function renderEnvSection(env: EnvInfo, config: Config): string {
return [
'## Environment',
'',
`- **Date**: ${env.date}`,
`- **Commit**: ${env.commit}`,
`- **Node**: ${env.node}`,
`- **OS**: ${env.os}`,
`- **CPU**: ${env.cpu}`,
`- **RAM**: ${env.ram}`,
`- **Core-pinned**: ${env.pinned ? 'yes' : 'no'}`,
`- **autocannon config**: ${config.conns} connections, ${config.duration}s duration, ` +
`${config.runs} runs (${config.warmup} warmup discarded), pipelining ${config.pipelining}`,
'',
].join('\n');
}
function renderCaveat(): string {
return [
'> **A note on honesty: this is a single-box benchmark.** All frameworks were driven with autocannon over',
'> loopback on the same machine, sharing the same cores as the server processes they measured. That',
"> contention overstates absolute throughput for every framework and compresses the differences *between*",
'> frameworks — do not read the raw req/s numbers as what you would see on separate client/server hardware.',
'> The honest takeaway is the **ratio** between frameworks in the same table, not any single absolute',
'> number. Note also that green-tea runs with `security:false` in the cross-framework tables below, purely',
'> for response-header parity with the other frameworks (none of which set the same security headers by',
'> default) — the real cost of running green-tea secure-by-default is measured separately in its own',
'> section further down.',
'',
].join('\n');
}
function renderScenarioTable(rows: Row[]): string {
const sorted = [...rows].sort((a, b) => b.reqSec.median - a.reqSec.median);
const header = '| Framework | req/s (median) | p50 (ms) | p99 (ms) | p999 (ms) | CV | min–max req/s |';
const divider = '| --- | --- | --- | --- | --- | --- | --- |';
const lines = sorted.map((row) => {
const { framework, reqSec, p50, p99, p999 } = row;
return (
`| ${framework} | ${fmtInt(reqSec.median)} | ${fmtLatency(p50)} | ${fmtLatency(p99)} | ` +
`${fmtLatency(p999)} | ${fmtCv(reqSec.cv)} | ${fmtRange(reqSec.min, reqSec.max)} |`
);
});
return [header, divider, ...lines].join('\n');
}
function renderScenarios(scenarios: ScenarioBlock[]): string {
return scenarios
.map((scenario) => {
const heading = `### ${scenario.title}${scenario.approximation ? ' (approximation)' : ''}`;
return [heading, '', renderScenarioTable(scenario.rows), ''].join('\n');
})
.join('\n');
}
function renderStepScaling(stepScaling: RenderData['stepScaling']): string {
const sorted = [...stepScaling].sort((a, b) => a.steps - b.steps);
const header = '| Path | Steps | req/s |';
const divider = '| --- | --- | --- |';
const lines = sorted.map((row) => `| ${row.path} | ${row.steps} | ${fmtInt(row.reqSec)} |`);
let deltaNote = '';
if (sorted.length >= 2) {
const first = sorted[0];
const last = sorted[sorted.length - 1];
const stepDiff = last.steps - first.steps;
if (stepDiff > 0) {
const reqDiff = last.reqSec - first.reqSec;
const perStep = reqDiff / stepDiff;
const pct = first.reqSec ? (reqDiff / first.reqSec) * 100 : 0;
deltaNote =
`Each additional pipeline step costs roughly ${fmtInt(Math.abs(perStep))} req/s ` +
`(${pct <= 0 ? '-' : ''}${Math.abs(pct).toFixed(1)}% over ${stepDiff} step${stepDiff === 1 ? '' : 's'}), ` +
`on this box.`;
}
}
return ['## Step-scaling (green-tea)', '', header, divider, ...lines, '', deltaNote, ''].join('\n');
}
function renderSecureCost(secureCost: RenderData['secureCost']): string {
const header = '| Label | req/s |';
const divider = '| --- | --- |';
const lines = secureCost.map((row) => `| ${row.label} | ${fmtInt(row.reqSec)} |`);
let deltaNote = '';
if (secureCost.length >= 2) {
const baseline = secureCost[0];
const withSecurity = secureCost[secureCost.length - 1];
const reqDiff = baseline.reqSec - withSecurity.reqSec;
const pct = baseline.reqSec ? (reqDiff / baseline.reqSec) * 100 : 0;
deltaNote = `The real cost of running secure-by-default (rather than the parity-mode \`security:false\` used above) is ~${pct.toFixed(1)}% req/s on this box.`;
}
return [
'## Cost of secure-by-default (green-tea)',
'',
header,
divider,
...lines,
'',
deltaNote,
'',
'> Scope: this micro-bench currently measures the security-**headers** cost only (`security:false` vs',
'> `security:true` on `/hello`). The incremental cost of `@body` validation and CORS is not separately',
'> measured yet (deferred) — so this table is narrower than the design spec\'s 4-point plan.',
'',
].join('\n');
}
function renderMethodology(): string {
return [
'## Methodology',
'',
'- **Parity controls**: every framework is configured for the fairest possible comparison —',
' security-header parity (matching header sets across frameworks, or green-tea running with',
' `security:false` in the cross-framework tables), keep-alive parity, and Express\'s `etag` and',
" `x-powered-by` disabled. The `/validate` scenario always sends a valid body so every framework",
' takes its success path and performs equivalent validation work.',
'- **Pipeline approximation**: scenarios marked `(approximation)` (e.g. the multi-step pipeline route)',
" do not have an exact one-to-one equivalent in every framework; the closest reasonable approximation",
' is used for each framework and the result should be read as indicative, not as an exact apples-to-apples',
' measurement.',
'- **Serialization parity**: all four frameworks serialize their JSON responses with plain',
' `JSON.stringify` in these benchmarks. Fastify\'s `fast-json-stringify` response serializer is',
' deliberately **not** engaged — only its input `schema.body` validation is used — so no framework',
' gets a serialization fast path the others lack.',
'- **Content-type charset asymmetry (disclosed, not controlled)**: green-tea and raw-http send',
' `Content-Type: application/json` while Express and Fastify send `application/json; charset=utf-8`.',
' This is a minor header-byte asymmetry that is disclosed here rather than normalized away.',
'- **NestJS runs on an underlying adapter** (Express or Fastify): the `nestjs-express` / `nestjs-fastify`',
" rows measure Nest's DI / decorator / routing overhead **on top of** that adapter, so compare each",
' against its own base (`express` / `fastify`) rather than against the field. Nest\'s idiomatic',
' `ValidationPipe` / class-validator is **not** used — `/validate` performs the same manual field check',
' as every other server (parity). The same parity controls apply: `etag` and `x-powered-by` are disabled',
' on the underlying Express instance, and `keepAliveTimeout` is 5000 on both adapters.',
'',
].join('\n');
}
function renderLeaderboard(scenarios: ScenarioBlock[]): string {
const first = scenarios[0];
if (!first || first.rows.length === 0) return '';
const leader = [...first.rows].sort((a, b) => b.reqSec.median - a.reqSec.median)[0];
return [
`> **TL;DR**: \`${leader.framework}\` posted the highest median req/s in the first benchmarked scenario ` +
`on this box — see the single-box caveat below before reading anything into the absolute numbers.`,
'',
].join('\n');
}
export function renderMarkdown(data: RenderData): string {
const { env, config, scenarios, stepScaling, secureCost } = data;
return [
renderLeaderboard(scenarios),
'# green-tea Benchmarks',
'',
renderEnvSection(env, config),
renderCaveat(),
'## Cross-framework scenarios',
'',
renderScenarios(scenarios),
renderStepScaling(stepScaling),
renderSecureCost(secureCost),
renderMethodology(),
].join('\n');
}
+384
View File
@@ -0,0 +1,384 @@
{
"env": {
"date": "2026-07-07",
"commit": "fe1831a",
"node": "v22.22.2",
"os": "darwin",
"cpu": "Apple M4 Max (16 cores)",
"ram": "69 GB",
"pinned": false
},
"config": {
"conns": 100,
"duration": 5,
"runs": 3,
"warmup": 1,
"pipelining": 1
},
"scenarios": [
{
"title": "JSON hello (overhead)",
"name": "hello",
"rows": [
{
"framework": "raw-http",
"reqSec": {
"median": 115398.4,
"min": 114822.4,
"max": 115539.2,
"stddev": 310.09010876768724,
"cv": 0.0026905088104554075
},
"p50": 0,
"p99": 1,
"p999": 1
},
{
"framework": "fastify",
"reqSec": {
"median": 86764.8,
"min": 86496,
"max": 87123.2,
"stddev": 256.9227813090051,
"cv": 0.002960121758353106
},
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "express",
"reqSec": {
"median": 24366.4,
"min": 24283.2,
"max": 24417.6,
"stddev": 55.38455460585383,
"cv": 0.002273984274990166
},
"p50": 3,
"p99": 5,
"p999": 8
},
{
"framework": "green-tea",
"reqSec": {
"median": 98092.8,
"min": 98054.4,
"max": 98668.8,
"stddev": 281.0175795212842,
"cv": 0.002859589501804015
},
"p50": 0,
"p99": 1,
"p999": 2
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 21761.6,
"min": 21697.6,
"max": 21896,
"stddev": 82.67870880032535,
"cv": 0.0037952010918943873
},
"p50": 4,
"p99": 6,
"p999": 10
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 95033.6,
"min": 94240,
"max": 95264,
"stddev": 438.6166536839312,
"cv": 0.00462452048886261
},
"p50": 1,
"p99": 1,
"p999": 2
}
]
},
{
"title": "Route param",
"name": "param",
"rows": [
{
"framework": "raw-http",
"reqSec": {
"median": 116332.8,
"min": 115974.4,
"max": 116409.6,
"stddev": 189.66281191162406,
"cv": 0.001631663389130871
},
"p50": 0,
"p99": 1,
"p999": 1
},
{
"framework": "fastify",
"reqSec": {
"median": 86278.4,
"min": 86137.6,
"max": 86764.8,
"stddev": 268.69839349476365,
"cv": 0.003110165492522174
},
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "express",
"reqSec": {
"median": 23835.2,
"min": 23803.2,
"max": 24046.4,
"stddev": 107.89690552662897,
"cv": 0.004515472130491916
},
"p50": 3,
"p99": 5,
"p999": 8
},
{
"framework": "green-tea",
"reqSec": {
"median": 93433.6,
"min": 93152,
"max": 93612.8,
"stddev": 189.6628119116206,
"cv": 0.002030662686635119
},
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 20955.2,
"min": 20948.8,
"max": 21201.6,
"stddev": 117.69157432317111,
"cv": 0.005594982425799189
},
"p50": 4,
"p99": 6,
"p999": 11
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 89312,
"min": 89235.2,
"max": 89529.6,
"stddev": 124.68598780759793,
"cv": 0.001395338811201841
},
"p50": 1,
"p99": 2,
"p999": 2
}
]
},
{
"title": "Pipeline (3 steps)",
"name": "pipeline",
"approximation": true,
"rows": [
{
"framework": "raw-http",
"reqSec": {
"median": 113491.2,
"min": 112531.2,
"max": 114809.6,
"stddev": 933.9810324031724,
"cv": 0.008220892102882115
},
"p50": 0,
"p99": 1,
"p999": 1
},
{
"framework": "fastify",
"reqSec": {
"median": 85024,
"min": 84512,
"max": 85177.6,
"stddev": 284.55819947576623,
"cv": 0.003351507726431956
},
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "express",
"reqSec": {
"median": 23950.4,
"min": 23902.4,
"max": 24011.2,
"stddev": 44.519758410046,
"cv": 0.0018585004345727763
},
"p50": 3,
"p99": 5,
"p999": 8
},
{
"framework": "green-tea",
"reqSec": {
"median": 84896,
"min": 84243.2,
"max": 85267.2,
"stddev": 423.2825796347192,
"cv": 0.004991414284012342
},
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 20824,
"min": 20804.8,
"max": 20878.41,
"stddev": 31.17605954717337,
"cv": 0.001496278247605678
},
"p50": 4,
"p99": 6,
"p999": 11
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 87328,
"min": 86867.2,
"max": 87660.8,
"stddev": 325.38753646827104,
"cv": 0.0037278603866430907
},
"p50": 1,
"p99": 2,
"p999": 2
}
]
},
{
"title": "POST JSON + validation",
"name": "validate",
"rows": [
{
"framework": "raw-http",
"reqSec": {
"median": 100140.8,
"min": 99846.4,
"max": 100294.4,
"stddev": 185.88177843875883,
"cv": 0.0018570746103533369
},
"p50": 0,
"p99": 1,
"p999": 2
},
{
"framework": "fastify",
"reqSec": {
"median": 63721.6,
"min": 63574.4,
"max": 63760,
"stddev": 79.99288857281053,
"cv": 0.0012560645345785087
},
"p50": 1,
"p99": 2,
"p999": 3
},
{
"framework": "express",
"reqSec": {
"median": 20097.6,
"min": 20056,
"max": 20174.41,
"stddev": 49.04789518646266,
"cv": 0.0024390608203285337
},
"p50": 4,
"p99": 6,
"p999": 12
},
{
"framework": "green-tea",
"reqSec": {
"median": 77177.61,
"min": 77126.4,
"max": 77254.4,
"stddev": 52.602458962379814,
"cv": 0.0006815013839797027
},
"p50": 1,
"p99": 2,
"p999": 2
},
{
"framework": "nestjs-express",
"reqSec": {
"median": 18856,
"min": 18852.8,
"max": 19067.2,
"stddev": 100.32338821143516,
"cv": 0.005301010367660728
},
"p50": 5,
"p99": 7,
"p999": 30
},
{
"framework": "nestjs-fastify",
"reqSec": {
"median": 59145.6,
"min": 59004.8,
"max": 59376,
"stddev": 153.00625985741647,
"cv": 0.002585636725423652
},
"p50": 1,
"p99": 3,
"p999": 3
}
]
}
],
"stepScaling": [
{
"path": "/steps/0",
"steps": 0,
"reqSec": 92281.6
},
{
"path": "/steps/3",
"steps": 3,
"reqSec": 81529.61
},
{
"path": "/steps/5",
"steps": 5,
"reqSec": 71993.61
}
],
"secureCost": [
{
"label": "security:false (parity)",
"reqSec": 98092.8
},
{
"label": "security:true (default)",
"reqSec": 92998.4
}
]
}
+172
View File
@@ -0,0 +1,172 @@
import autocannon from 'autocannon';
import { spawn, execSync } from 'child_process';
import os from 'os';
import { writeFileSync } from 'fs';
import { SCENARIOS, STEP_ROUTES } from './scenarios';
import { aggregate } from './stats';
import { renderMarkdown, type RenderData, type Row, type ScenarioBlock } from './render';
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);
function log(msg: string): void {
process.stderr.write(`[bench] ${msg}\n`);
}
interface RunResult {
reqSec: number;
p50: number;
p99: number;
p999: number;
}
async function spawnServer(
name: string,
extraEnv: Record<string, string> = {},
): Promise<{ port: number; kill: () => Promise<void> }> {
const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${name}.ts`], {
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'] = [];
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();
}
}
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,
};
writeFileSync('BENCHMARKS.md', renderMarkdown(data));
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);
});
+25
View File
@@ -0,0 +1,25 @@
export interface Scenario {
name: string; // key
title: string; // display
method: 'GET' | 'POST';
path: string; // route path (no host)
body?: unknown; // JSON body for POST
approximation?: boolean;
}
// The always-valid validation body — every framework takes the success path.
export const VALIDATE_BODY = { email: 'bench@example.com' };
export const SCENARIOS: Scenario[] = [
{ name: 'hello', title: 'JSON hello (overhead)', method: 'GET', path: '/hello' },
{ name: 'param', title: 'Route param', method: 'GET', path: '/users/42' },
{ name: 'pipeline', title: 'Pipeline (3 steps)', method: 'GET', path: '/pipeline', approximation: true },
{ name: 'validate', title: 'POST JSON + validation',method: 'POST', path: '/validate', body: VALIDATE_BODY },
];
// green-tea-only step-scaling routes
export const STEP_ROUTES = [
{ name: 'steps0', steps: 0, path: '/steps/0' },
{ name: 'steps3', steps: 3, path: '/steps/3' },
{ name: 'steps5', steps: 5, path: '/steps/5' },
];
+20
View File
@@ -0,0 +1,20 @@
import { Module, Controller, Get, Post, Param, Body, HttpException, MiddlewareConsumer, NestModule } from '@nestjs/common';
@Controller()
export class BenchController {
@Get('hello') hello() { return { hello: 'world' }; }
@Get('users/:id') user(@Param('id') id: string) { return { id }; }
@Get('pipeline') pipeline() { return { hello: 'world', s3: 3 }; }
@Post('validate') validate(@Body() b: any) {
if (!(b && typeof b.email === 'string' && b.email.includes('@'))) throw new HttpException({ error: 'invalid' }, 422);
return { email: b.email };
}
}
// pipeline parity: 3 middleware hops on /pipeline (approximation of 3 @Steps), adapter-agnostic
const mw = (_n: number) => (_req: any, _res: any, next: any) => next();
@Module({ controllers: [BenchController] })
export class BenchModule implements NestModule {
configure(c: MiddlewareConsumer) { c.apply(mw(1), mw(2), mw(3)).forRoutes('pipeline'); }
}
+19
View File
@@ -0,0 +1,19 @@
import express from 'express';
const app = express();
app.disable('x-powered-by');
app.set('etag', false);
app.use(express.json());
app.get('/hello', (_req, res) => { res.json({ hello: 'world' }); });
app.get('/users/:id', (req, res) => { res.json({ id: req.params.id }); });
const mw = (n: number) => (_req: any, res: any, next: any) => { res.locals[`s${n}`] = n; next(); };
app.get('/pipeline', mw(1), mw(2), mw(3), (_req, res) => { res.json({ hello: 'world', s3: res.locals.s3 }); });
app.post('/validate', (req: any, res) => {
const b = req.body;
if (!(b && typeof b.email === 'string' && b.email.includes('@'))) { res.status(422).json({ error: 'invalid' }); return; }
res.json({ email: b.email });
});
const server = app.listen(0, () => {
server.keepAliveTimeout = 5000;
console.log(`READY ${(server.address() as any).port}`);
});
+18
View File
@@ -0,0 +1,18 @@
import Fastify from 'fastify';
const app = Fastify({ logger: false, keepAliveTimeout: 5000 });
app.get('/hello', async () => ({ hello: 'world' }));
app.get('/users/:id', async (req: any) => ({ id: req.params.id }));
const hook = (n: number) => (req: any, _res: any, done: any) => { req[`s${n}`] = n; done(); };
app.get('/pipeline', { preHandler: [hook(1), hook(2), hook(3)] }, async (req: any) => ({ hello: 'world', s3: req.s3 }));
app.post('/validate', {
schema: { body: { type: 'object', required: ['email'], properties: { email: { type: 'string' } } } },
}, async (req: any, reply) => {
const b = req.body;
if (!b.email.includes('@')) { reply.code(422); return { error: 'invalid' }; }
return { email: b.email };
});
app.listen({ port: 0 }, (err, addr) => {
if (err) { console.error(err); process.exit(1); }
console.log(`READY ${Number(new URL(addr).port)}`);
});
+44
View File
@@ -0,0 +1,44 @@
import 'reflect-metadata';
import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index';
// email schema (Standard Schema, hand-rolled — same field check the others do)
const emailSchema = {
'~standard': { version: 1 as const, vendor: 'bench', validate: (v: any) =>
(v && typeof v.email === 'string' && v.email.includes('@')) ? { value: v } : { issues: [{ message: 'invalid email' }] } },
};
// 5 chained steps: s1..s5, each needs the previous. Routes @needs the Nth to pull exactly N.
function makeStep(n: number) {
@Step({ provides: `s${n}`, needs: n > 1 ? [`s${n - 1}`] : [] })
class S { run() { return { [`s${n}`]: n }; } }
return S;
}
const steps = [1, 2, 3, 4, 5].map(makeStep);
@Route('/')
class Bench {
@Get('/hello') hello() { return { hello: 'world' }; }
@Get('/users/:id') user(@param('id') id: string) { return { id }; }
@Get('/pipeline') pipeline(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; }
@Get('/steps/0') steps0() { return { hello: 'world' }; }
@Get('/steps/3') steps3(@needs('s3') s3: number) { return { hello: 'world', s3 }; }
@Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; }
}
@Module({ mountpoint: '/', steps, controllers: [Bench] })
class BenchModule {}
// PARITY: security OFF for the cross-framework table. GT_SECURE=1 flips it on for the secure-cost micro-bench.
const secure = process.env.GT_SECURE === '1';
const app = createApp({ modules: [BenchModule], security: secure });
async function main() {
// fail loudly if decorators didn't apply (inspect throws "no route" on empty plan, so wrap)
try { if (app.inspect('/hello').length === 0) throw new Error('empty'); }
catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); }
const server = await app.listen(0);
server.keepAliveTimeout = 5000; // parity value (all servers use 5000)
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+17
View File
@@ -0,0 +1,17 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import express from 'express';
import { BenchModule } from './_nest-shared';
async function main() {
const inst = express();
inst.disable('x-powered-by');
inst.set('etag', false);
const app = await NestFactory.create(BenchModule, new ExpressAdapter(inst), { logger: false });
await app.listen(0, '127.0.0.1');
const server = app.getHttpServer();
server.keepAliveTimeout = 5000; // parity (works on Node http.Server after listen)
console.log(`READY ${server.address().port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+13
View File
@@ -0,0 +1,13 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { BenchModule } from './_nest-shared';
async function main() {
const adapter = new FastifyAdapter({ logger: false, keepAliveTimeout: 5000 }); // parity via constructor
const app = await NestFactory.create<NestFastifyApplication>(BenchModule, adapter, { logger: false });
await app.listen(0, '127.0.0.1');
const server = app.getHttpServer();
console.log(`READY ${(server.address() as any).port}`);
}
main().catch((e) => { console.error(e); process.exit(1); });
+18
View File
@@ -0,0 +1,18 @@
import http from 'http';
const server = http.createServer((req, res) => {
const url = (req.url ?? '/').split('?')[0];
const send = (obj: unknown, code = 200) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)); };
if (req.method === 'GET' && url === '/hello') return send({ hello: 'world' });
if (req.method === 'GET' && url.startsWith('/users/')) return send({ id: url.slice('/users/'.length) });
if (req.method === 'GET' && url === '/pipeline') { const s: any = {}; [1, 2, 3].forEach((n) => (s[`s${n}`] = n)); return send({ hello: 'world', s3: s.s3 }); }
if (req.method === 'POST' && url === '/validate') {
let raw = ''; req.on('data', (c) => (raw += c)); req.on('end', () => {
try { const b = JSON.parse(raw); if (typeof b.email === 'string' && b.email.includes('@')) return send({ email: b.email }); return send({ error: 'invalid' }, 422); }
catch { return send({ error: 'bad json' }, 400); }
}); return;
}
send({ error: 'not found' }, 404);
});
server.keepAliveTimeout = 5000;
server.listen(0, () => console.log(`READY ${(server.address() as any).port}`));
+18
View File
@@ -0,0 +1,18 @@
export interface Agg {
median: number;
mean: number;
stddev: number;
cv: number;
min: number;
max: number;
}
export function aggregate(values: number[]): Agg {
const xs = [...values].sort((a, b) => a - b);
const n = xs.length;
const mean = xs.reduce((s, x) => s + x, 0) / n;
const median = n % 2 ? xs[(n - 1) / 2] : (xs[n / 2 - 1] + xs[n / 2]) / 2;
const variance = xs.reduce((s, x) => s + (x - mean) ** 2, 0) / n;
const stddev = Math.sqrt(variance);
return { median, mean, stddev, cv: mean ? stddev / mean : 0, min: xs[0], max: xs[n - 1] };
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "noEmit": true },
"include": ["."]
}
+3405
View File
File diff suppressed because it is too large. Load diff
+14 -1
View File
@@ -10,7 +10,9 @@
"build": "tsc -p tsconfig.json",
"test": "vitest run",
"test:dev": "vitest",
"typecheck": "tsc --noEmit -p tsconfig.json"
"typecheck": "tsc --noEmit -p tsconfig.json",
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
"bench": "tsx bench/run.ts"
},
"dependencies": {
"reflect-metadata": "0.2.2"
@@ -24,9 +26,20 @@
}
},
"devDependencies": {
"@nestjs/common": "^11.1.27",
"@nestjs/core": "^11.1.27",
"@nestjs/platform-express": "^11.1.27",
"@nestjs/platform-fastify": "^11.1.27",
"@types/autocannon": "^7.12.7",
"@types/express": "^5.0.6",
"@types/node": "^18.19.0",
"@types/ws": "^8.18.1",
"autocannon": "^8.0.0",
"express": "^5.2.1",
"fastify": "^5.10.0",
"graphql": "^16.9.0",
"rxjs": "^7.8.2",
"tsx": "^4.23.0",
"typescript": "^5.5.0",
"vitest": "^2.0.0",
"ws": "^8.21.0"
+78
View File
@@ -0,0 +1,78 @@
import { describe, it, expect } from 'vitest';
import { aggregate } from '../bench/stats';
import { renderMarkdown } from '../bench/render';
describe('aggregate', () => {
it('median, stddev, cv, min/max over run req/s', () => {
const a = aggregate([100, 110, 120, 130, 140]);
expect(a.median).toBe(120);
expect(a.min).toBe(100);
expect(a.max).toBe(140);
expect(a.stddev).toBeGreaterThan(0);
expect(a.cv).toBeCloseTo(a.stddev / a.mean, 6);
});
});
describe('renderMarkdown', () => {
const data = {
env: {
date: '2026-07-06',
commit: 'abc123',
node: 'v18.19.0',
os: 'darwin',
cpu: 'M1 (8 cores)',
ram: '16 GB',
pinned: false,
},
config: { conns: 100, duration: 10, runs: 5, warmup: 1, pipelining: 1 },
scenarios: [
{
title: 'JSON hello (overhead)',
name: 'hello',
approximation: false,
rows: [
{
framework: 'fastify',
reqSec: { median: 50000, min: 49000, max: 51000, stddev: 700, cv: 0.014 },
p50: 1.5,
p99: 4,
p999: 9,
},
{
framework: 'green-tea',
reqSec: { median: 42000, min: 41000, max: 43000, stddev: 600, cv: 0.014 },
p50: 1.9,
p99: 5,
p999: 11,
},
],
},
],
stepScaling: [
{ path: '/steps/0', steps: 0, reqSec: 45000 },
{ path: '/steps/3', steps: 3, reqSec: 40000 },
],
secureCost: [
{ label: 'security:false (parity)', reqSec: 45000 },
{ label: 'security:true (default)', reqSec: 43000 },
],
};
it('renders env header, a per-scenario table with a row per framework, and the micro-bench sections', () => {
const md = renderMarkdown(data as any);
expect(md).toContain('# green-tea Benchmarks');
expect(md).toContain('abc123'); // commit
expect(md).toContain('single-box'); // contention caveat
expect(md).toContain('JSON hello (overhead)');
expect(md).toContain('fastify');
expect(md).toContain('green-tea');
expect(md).toMatch(/req\/s/i);
expect(md).toContain('p99');
expect(md).toContain('Step-scaling');
expect(md).toContain('secure-by-default');
expect(md).toContain('approximation'); // methodology mentions the pipeline approximation
});
it('sorts each scenario rows by median req/s descending', () => {
const md = renderMarkdown(data as any);
expect(md.indexOf('fastify')).toBeLessThan(md.indexOf('green-tea')); // fastify (50k) before green-tea (42k)
});
});