$ cat docs/performance.md
PerformanceDesempenho
The router costs a fraction of a microsecond per request. The time goes to node:http, the driver and validation. Tupik keeps that path short without changing how you write handlers.O roteador custa uma fração de microssegundo por requisição. O tempo vai para o node:http, o driver e a validação. O Tupik mantém esse caminho curto sem mudar o jeito de escrever handlers.
What the drivers do for youO que os drivers fazem por você
- No await when nothing waits.
app.handle(request)returns theResponseitself when the request has noonRequest,preHandleroronSendhook, no body, and its validators and handler are synchronous.@tupik/nodeand@tupik/buncall it, so a plainGETcosts no extra microtask.app.fetchkeeps returning a promise. - Abort signal on demand (Node).
ctx.req.signalis created the first time you read it. Requests that never read it pay for noAbortController. - One stream for the body (Node). The request body is a single web
ReadableStreamover the socket, with the byte limit (413) counted as data arrives. - Native routes (Bun).
serveBunregisters your paths inBun.serve({ routes })and keepsfetchas the fallback. Hooks, access rules and middleware run as before.
- Sem
awaitquando nada espera.app.handle(request)devolve a própriaResponsequando a requisição não tem hookonRequest,preHandlerouonSend, não tem corpo e os validadores e o handler são síncronos. O@tupik/nodee o@tupik/bunusam esse caminho, então umGETsimples não paga microtask extra.app.fetchcontinua devolvendo promise. - Sinal de abort sob demanda (Node).
ctx.req.signalsó é criado na primeira leitura. Quem nunca lê não pagaAbortController. - Um stream só para o corpo (Node). O corpo é um único
ReadableStreamsobre o socket, com o limite de bytes (413) contado conforme os dados chegam. - Rotas nativas (Bun). O
serveBunregistra as rotas emBun.serve({ routes })e mantém ofetchcomo reserva. Hooks, regras de acesso e middleware continuam iguais.
Synchronous validation and precompiled validatorsValidação síncrona e validadores pré-compilados
When every ~standard.validate answers synchronously, validation runs without an await. Zod, Valibot and ArkType are already Standard Schema. For validators compiled ahead of time, @tupik/schema has thin adapters that do not depend on the libraries:
Quando todo ~standard.validate responde de forma síncrona, a validação roda sem await. Zod, Valibot e ArkType já são Standard Schema. Para validadores compilados antes, o @tupik/schema tem adaptadores finos que não dependem das bibliotecas:
import Ajv from 'ajv';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import typia from 'typia';
import { createModule } from '@tupik/core';
import { fromAjv, fromTypeBox, fromTypia } from '@tupik/schema';
const item = fromAjv<Item>(new Ajv().compile(itemJsonSchema)); // or an Ajv standalone module
const user = fromTypeBox(TypeCompiler.Compile(UserSchema));
const order = fromTypia(typia.createValidate<Order>());
export const items = createModule('/items').post('/', {
access: 'authenticated',
schema: { body: item },
handler: (ctx) => ctx.status(201).json(ctx.body),
});import Ajv from 'ajv';
import { TypeCompiler } from '@sinclair/typebox/compiler';
import typia from 'typia';
import { createModule } from '@tupik/core';
import { fromAjv, fromTypeBox, fromTypia } from '@tupik/schema';
const item = fromAjv<Item>(new Ajv().compile(itemJsonSchema)); // ou um módulo standalone do Ajv
const user = fromTypeBox(TypeCompiler.Compile(UserSchema));
const order = fromTypia(typia.createValidate<Order>());
export const items = createModule('/items').post('/', {
access: 'authenticated',
schema: { body: item },
handler: (ctx) => ctx.status(201).json(ctx.body),
}); Any other validator works the same way: return { value } or { issues: [{ message, path }] } from '~standard'.validate without a promise.
Qualquer outro validador serve do mesmo jeito: devolva { value } ou { issues: [{ message, path }] } do '~standard'.validate sem promise.
Several cores: workersVários núcleos: workers
import { serve } from '@tupik/node';
serve(app, { port: 3000, workers: 'auto' }); // or a numberimport { serve } from '@tupik/node';
serve(app, { port: 3000, workers: 'auto' }); // ou um número serve forks node:cluster workers. Each one runs your entry script again, where the same serve call just listens. On Linux with Node 22.12 or newer, each worker binds its own socket with SO_REUSEPORT and the kernel spreads connections (reusePort: false turns it off). Elsewhere the workers share the cluster socket.
O serve cria workers do node:cluster. Cada um roda de novo o script de entrada, onde a mesma chamada só escuta a porta. No Linux com Node 22.12 ou mais novo, cada worker abre o próprio socket com SO_REUSEPORT e o kernel distribui as conexões (reusePort: false desliga). Fora disso os workers dividem o socket do cluster.
A crashed worker is replaced. SIGTERM and SIGINT, or close() on the returned ServeCluster, stop accepting, let in flight requests finish and kill what is left after shutdownTimeout (10 s).
Worker que cai é substituído. SIGTERM e SIGINT, ou close() no ServeCluster devolvido, param de aceitar conexões, deixam as requisições em andamento terminarem e matam o que sobrar depois de shutdownTimeout (10 s).
Measured numbersNúmeros medidos
Measured on 2026-12-01, Node.js 24.21.0, on a loaded machine. The numbers depend on the machine: compare before and after on the same one.
Medido em 2026-12-01, Node.js 24.21.0, com a máquina carregada. Os números dependem da máquina: compare antes e depois na mesma.
| MeasurementMedição | ResultResultado | CommandComando |
|---|---|---|
| GET JSON on Node, before and after Phase 7GET JSON no Node, antes e depois da Fase 7 | 26.9k to 29.4k req/s26,9k para 29,4k req/s | Phase 7 before/after run, autocannon, 8 interleaved roundsrodada antes/depois da Fase 7, autocannon, 8 rodadas intercaladas |
| POST with a validated JSON bodyPOST com corpo JSON validado | 9.0k to 12.0k req/s9,0k para 12,0k req/s | Phase 7 before/after run, autocannon, 8 interleaved roundsrodada antes/depois da Fase 7, autocannon, 8 rodadas intercaladas |
serve({ workers: 4 })serve({ workers: 4 }) | about 68k req/s (about 26k with 1 process)cerca de 68k req/s (cerca de 26k com 1 processo) | Phase 7 run, autocannon, Linuxrodada da Fase 7, autocannon, Linux |
How to measureComo medir
| CommandComando | What it measuresO que mede |
|---|---|
pnpm bench:ci | Worst RadixRouter.match() lookup, gated at 200 ns.Pior lookup do RadixRouter.match(), travado em 200 ns. |
pnpm bench:parity | Requests per second of a GET JSON route on Node, with autocannon.Requisições por segundo de uma rota GET JSON no Node, com autocannon. |
pnpm bench:body | POST with a JSON body: synchronous vs asynchronous validator.POST com corpo JSON: validador síncrono vs assíncrono. |