Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## 2026-09-07 - Cached expensive URL normalization in router loop

**Learning:** URL normalization (`pathCandidates`) was being re-evaluated for every single route in the routing table loop (`config.routes`). This function decodes URI strings and loops up to 8 times to handle edge cases like `%2f` and dot segments. This led to O(N) evaluations, heavily degrading performance for configurations with many routes.

**Action:** Caching the result of `pathCandidates` inside the routing loop prevents it from being recalculated. The cache is initialized lazily so that configurations where the host doesn't match don't incur the cost at all. I also cached the request method uppercase string to save those recalculations too.
16 changes: 10 additions & 6 deletions packages/jouska/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ export const matchUrl = (
headers: Headers,
): Match | undefined => {
const host = url.hostname.toLowerCase();
const requestMethod = method.toUpperCase();
let cachedPathCandidates: string[] | undefined;

for (let i = 0; i < config.routes.length; i++) {
const route = config.routes[i]!;
Expand All @@ -300,13 +302,15 @@ export const matchUrl = (
if (hostPattern !== undefined && !hostMatches(hostPattern, host)) {
continue;
}
if (
pathPrefix !== undefined &&
!pathCandidates(url.pathname).some((c) => pathMatches(pathPrefix, c))
) {
continue;
if (pathPrefix !== undefined) {
if (cachedPathCandidates === undefined) {
cachedPathCandidates = pathCandidates(url.pathname);
}
if (!cachedPathCandidates.some((c) => pathMatches(pathPrefix, c))) {
continue;
}
}
if (methods !== undefined && !methods.some((m) => m.toUpperCase() === method.toUpperCase())) {
if (methods !== undefined && !methods.some((m) => m.toUpperCase() === requestMethod)) {
continue;
}
if (!conditionsHold(route, url, headers)) {
Expand Down
Loading