Bun.serve routes: building the table is quadratic and lookup is linear in the number of sibling routes
What version of Bun is running?
1.4.3-canary.1+5f554969b
What platform is your computer?
Linux 7.0.0-31-generic x86_64
What steps can reproduce the bug?
Save as repro.ts and run bun repro.ts:
console.log(`Bun ${Bun.version} (${Bun.revision}) ${process.platform} ${process.arch}`);
for (const n of [500, 1000, 2000, 4000]) {
const routes: Record<string, () => Response> = {};
for (let i = 0; i < n; i++) routes[`/s${i}`] = () => new Response("x");
const t0 = performance.now();
const server = Bun.serve({ port: 0, routes, fetch: () => new Response("fetch") });
const build = performance.now() - t0;
const time = async (path: string) => {
const t = performance.now();
for (let k = 0; k < 2000; k++) await (await fetch(`${server.url}${path.slice(1)}`)).text();
return ((performance.now() - t) / 2000) * 1000;
};
const first = await time("/s0");
const last = await time(`/s${n - 1}`);
console.log(`${String(n).padStart(4)} routes: Bun.serve() ${build.toFixed(1).padStart(7)} ms; GET first-registered ${first.toFixed(1)} µs, last-registered ${last.toFixed(1)} µs (sequential fetch, same process)`);
server.stop(true);
}Output:
500 routes: Bun.serve() 15.6 ms; GET first-registered 36.0 µs, last-registered 34.0 µs (sequential fetch, same process)
1000 routes: Bun.serve() 69.6 ms; GET first-registered 32.0 µs, last-registered 43.2 µs (sequential fetch, same process)
2000 routes: Bun.serve() 242.5 ms; GET first-registered 31.1 µs, last-registered 38.5 µs (sequential fetch, same process)
4000 routes: Bun.serve() 1161.6 ms; GET first-registered 36.8 µs, last-registered 58.1 µs (sequential fetch, same process)What is the expected behavior?
Building the routes table is roughly linear in the number of routes. Looking up a route doesn't depend on how many sibling routes were registered before it.
What do you see instead?
Building the table is quadratic in the number of sibling routes at one level. Doubling from 2,000 to 4,000 routes takes Bun.serve() from 243 ms to 1.16 s, and server.reload({ routes }) costs the same.
Lookup is linear in registration position. Under load (oha, 64 connections) with 5,000 flat sibling routes, the last-registered route served about 7.7k req/s against about 120k for the first. In-process, the gap grows with the sibling count (above: 36.8 µs vs 58.1 µs at 4,000). Requests that match no route pay a full scan before reaching fetch.
Additional information
From reading the source (not verified beyond this repro): uWS's HttpRouter keeps each node's children in a std::vector, scanned linearly both on insert (getNode) and on match (packages/bun-uws/src/HttpRouter.h). A bare-function route is also inserted once per HTTP method, so 1,000 bare-function routes build in about 79 ms against about 6.8 ms for { GET } objects. Nesting routes under shared prefixes avoids most of the cost: 4,000 routes in groups of 50 build in about 47 ms.
Source: oven-sh/bun