Skip to content

perf(middleware): precompose the middleware chain at construction time - #264

Merged
pi0 merged 1 commit into
mainfrom
perf/middleware-fold
Jul 17, 2026
Merged

pi0 merged 1 commit into
mainfrom
perf/middleware-fold

Conversation

@pi0x

@pi0x pi0x commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

What

wrapFetch now folds the middleware array into a single composed handler once at construction time, instead of recursively dispatching through callMiddleware on every request.

Why

Per request, the recursive dispatch paid one call frame with 4 arguments, a middleware.length read, an index comparison, an array access, and a closure allocation per layer. After the fold, only the per-layer next closure remains — that one is inherent to the next: () => Response API since it must capture per-request state.

Micro-benchmark (Node, passthrough middleware, sentinel response to isolate dispatch cost): ~18–25% faster dispatch at 1–5 middleware (~10–20 ns/request), neutral at 10. srvx's own plugins add 0–3 middleware, which is the range where the fold wins. End-to-end this is small relative to total request cost, but it's free.

Behavior note

Middleware added to server.options.middleware after construction now consistently has no effect. This was never a coherent contract: the old code honored late additions only when the array was non-empty at construction, because the empty case already returned the raw fetch handler. All in-tree mutators (_plugins.ts, _trust-proxy.ts, mtls.ts, tracing.ts) run inside plugins, which every adapter applies before calling wrapFetch, so nothing observable changes.

Testing

  • 1030 tests passed (35 skipped), typecheck and formatting clean.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Improved request middleware handling by composing the middleware chain once during server setup.
    • Preserved existing request behavior, including direct handling when no middleware is configured.

Fold middleware into the fetch handler once in wrapFetch instead of
dispatching recursively per request. This drops the per-request frame,
length read, index compare, and array access per layer — only the
inherent per-layer `next` closure remains (~18-25% faster dispatch at
1-5 middleware, neutral at 10).

Also makes mutation semantics consistent: middleware added to
`server.options.middleware` after construction now uniformly has no
effect (previously honored only when the array was non-empty at
construction, since the empty case already returned the raw handler).
All in-tree mutators (plugins, tracing, trust-proxy, mTLS) run before
wrapFetch, so behavior is unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@pi0x
pi0x requested a review from pi0 as a code owner July 17, 2026 09:27
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3f190604-56cc-44b5-bccc-ebc4849e93fd

📥 Commits

Reviewing files that changed from the base of the PR and between 8dc6d15 and 90efd48.

📒 Files selected for processing (1)
  • src/_middleware.ts

📝 Walkthrough

Walkthrough

wrapFetch now composes configured middleware into a single handler during construction, folding middleware in reverse order around the base fetch function and removing recursive per-request dispatch.

Changes

Middleware composition

Layer / File(s) Summary
Compose the middleware handler chain
src/_middleware.ts
Removes unused imports and recursive middleware execution, then builds the middleware chain once with reverse-order closures around server.options.fetch.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: pi0

Poem

A rabbit hops through middleware bright,
Folding each layer from left to right.
Closures nest in a tidy chain,
Fetch awaits its turn again.
“No recursion!” the bunny sings,
“Just swift composed handler springs!”

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: precomposing middleware at construction time for performance.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/middleware-fold

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 17, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/srvx@264

commit: 90efd48

@pi0
pi0 merged commit 0c8b3f1 into main Jul 17, 2026
14 checks passed
@pi0
pi0 deleted the perf/middleware-fold branch July 17, 2026 09:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants