perf: pre-compile middleware chains at build time (#3104)

Pre-compiles middleware chains once at startup instead of constructing
them per-request.

## Changes

- Replace `runMiddlewares(middlewares, ctx, onError)` (per-request) with
`compileMiddlewares(middlewares, onError)` (once at startup) which
returns a single `Middleware<State>` function
- Router now stores a single compiled handler per method/route (`T |
null`) instead of arrays (`T[]`)
- The compiled chain passes `tail` (the original `ctx.next`) as a
parameter to each step, avoiding the infinite recursion bug where a
compiled tail reads an already-overwritten `ctx.next` — safe under
concurrent requests
- Lazy middleware resolution is preserved: a lazy middleware is resolved
on first request and the resolved function replaces the lazy wrapper in
the closure

## Benchmarks

Synthetic benchmarks (10 middlewares, `deno bench`) show the per-request
savings are small in isolation — middleware execution and async/await
overhead dominate. The main value is architectural: building the chain
once is correct and eliminates per-request allocations, which may
compound under high concurrency.

---------

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marvin Hagemeister
2026-03-29 21:50:22 +02:00
committed by GitHub
co-authored by Bartek Iwańczuk Claude Opus 4.6
parent dc2324807c
commit 4edfe2f5a4
6 changed files with 314 additions and 166 deletions
+7 -12
View File
@@ -2,11 +2,7 @@ import { trace } from "@opentelemetry/api";
import { DENO_DEPLOYMENT_ID } from "@fresh/build-id";
import * as colors from "@std/fmt/colors";
import {
type MaybeLazyMiddleware,
type Middleware,
runMiddlewares,
} from "./middlewares/mod.ts";
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
import { Context } from "./context.ts";
import { mergePath, type Method, UrlPatternRouter } from "./router.ts";
import type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
@@ -387,12 +383,13 @@ export class App<State> {
}
}
const router = new UrlPatternRouter<MaybeLazyMiddleware<State>>();
const router = new UrlPatternRouter<Middleware<State>>();
const { rootMiddlewares } = applyCommands(
const { rootHandler } = applyCommands(
router,
this.#commands,
this.config.basePath,
this.#onError,
);
return async (
@@ -405,7 +402,7 @@ export class App<State> {
const method = req.method.toUpperCase() as Method;
const matched = router.match(method, url);
let { params, pattern, handlers, methodMatch } = matched;
let { params, pattern, item: handler, methodMatch } = matched;
const span = trace.getActiveSpan();
if (span && pattern) {
@@ -416,7 +413,7 @@ export class App<State> {
let next: () => Promise<Response>;
if (pattern === null || !methodMatch) {
handlers = rootMiddlewares;
handler = rootHandler;
}
if (matched.pattern !== null && !methodMatch) {
@@ -442,9 +439,7 @@ export class App<State> {
);
try {
if (handlers.length === 0) return await next();
const result = await runMiddlewares(handlers, ctx, this.#onError);
const result = await (handler !== null ? handler(ctx) : next());
if (!(result instanceof Response)) {
throw new Error(
`Expected a "Response" instance to be returned, but got: ${result}`,