Documentation menuMenu da documentação

$ 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 the Response itself when the request has no onRequest, preHandler or onSend hook, no body, and its validators and handler are synchronous. @tupik/node and @tupik/bun call it, so a plain GET costs no extra microtask. app.fetch keeps returning a promise.
  • Abort signal on demand (Node). ctx.req.signal is created the first time you read it. Requests that never read it pay for no AbortController.
  • One stream for the body (Node). The request body is a single web ReadableStream over the socket, with the byte limit (413) counted as data arrives.
  • Native routes (Bun). serveBun registers your paths in Bun.serve({ routes }) and keeps fetch as the fallback. Hooks, access rules and middleware run as before.
  • Sem await quando nada espera. app.handle(request) devolve a própria Response quando a requisição não tem hook onRequest, preHandler ou onSend, não tem corpo e os validadores e o handler são síncronos. O @tupik/node e o @tupik/bun usam esse caminho, então um GET simples não paga microtask extra. app.fetch continua devolvendo promise.
  • Sinal de abort sob demanda (Node). ctx.req.signal só é criado na primeira leitura. Quem nunca lê não paga AbortController.
  • Um stream só para o corpo (Node). O corpo é um único ReadableStream sobre o socket, com o limite de bytes (413) contado conforme os dados chegam.
  • Rotas nativas (Bun). O serveBun registra as rotas em Bun.serve({ routes }) e mantém o fetch como 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:

items.ts
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

server.ts
import { serve } from '@tupik/node';

serve(app, { port: 3000, workers: 'auto' }); // or a number
import { 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çãoResultResultadoCommandComando
GET JSON on Node, before and after Phase 7GET JSON no Node, antes e depois da Fase 726.9k to 29.4k req/s26,9k para 29,4k req/sPhase 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 validado9.0k to 12.0k req/s9,0k para 12,0k req/sPhase 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

CommandComandoWhat it measuresO que mede
pnpm bench:ciWorst RadixRouter.match() lookup, gated at 200 ns.Pior lookup do RadixRouter.match(), travado em 200 ns.
pnpm bench:parityRequests 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:bodyPOST with a JSON body: synchronous vs asynchronous validator.POST com corpo JSON: validador síncrono vs assíncrono.