Why This Matters at Engineering Leadership Scale
Every API gateway and Backend for Frontend sits behind a router. Once a codebase grows past a few dozen routes, naive linear regex lists trigger subtle outages: registering GET /users/:id above GET /users/me silently hijacks /users/me, or auth middleware gets skipped on a newly mounted wildcard path.
In Atlassian M60/M70 and staff-level coding loops, the API Router drill tests how you pair tree structures (Prefix Trie) with composable async middleware ((req, next) => res). At minute 30, adding HTTP method isolation, strict precedence rules, and per-route auth middleware verifies whether your interfaces absorb new requirements without collapsing into order-dependent if/else chains.
Core Mental Model & Architecture
| Routing Architecture | Lookup Time | Registration | Precedence Behavior | Main Trade-Off |
|---|---|---|---|---|
| Segment Prefix Trie | O(D) (path segments) | O(D) | Deterministic: static > :param > * | Best scaling; zero registration-order bugs |
| Linear Regex List | O(R) (total routes) | O(1) | Fragile: depends on registration order | Slows at 500+ routes; prone to route shadowing |
| Flat HashMap | O(1) | O(1) | Exact paths only | Cannot match :param or * wildcards |
To absorb the Minute-30 Extension cleanly:
- Store
methods: Map<HttpMethod, RouteEntry>on each terminal trie node soGET /orders/:idandDELETE /orders/:idstay isolated and unmatched methods return405 Method Not Allowed. - Enforce strict lookup order at every node:
staticChildren->paramChild->wildcardChild. Static routes always beat:paramroutes regardless of registration order. - Compose
[...globalMiddlewares, ...routeMiddlewares]around the handler with a guard against callingnext()twice.
Step-by-Step Implementation Tutorial
1. Implement the Segment Trie, Precedence Matcher, and Middleware Pipeline (Minutes 5 to 28)
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
export interface HttpRequest {
method: HttpMethod; path: string; headers: Record<string, string>;
params: Record<string, string>; wildcard?: string;
}
export interface HttpResponse { status: number; body: unknown; }
export type RouteHandler = (req: HttpRequest) => Promise<HttpResponse> | HttpResponse;
export type Middleware = (req: HttpRequest, next: () => Promise<HttpResponse>) => Promise<HttpResponse>;
interface RouteEntry { handler: RouteHandler; middlewares: Middleware[]; }
class TrieNode {
public readonly staticChildren = new Map<string, TrieNode>();
public paramChild: { name: string; node: TrieNode } | null = null;
public wildcardChild: TrieNode | null = null;
public readonly methods = new Map<HttpMethod, RouteEntry>();
}
export class ApiRouter {
private readonly root = new TrieNode();
private readonly globalMiddlewares: Middleware[] = [];
public use(middleware: Middleware): void { this.globalMiddlewares.push(middleware); }
// Minute-30 Extension: Method-scoped route + per-route middlewares
public addRoute(method: HttpMethod, path: string, handler: RouteHandler, middlewares: Middleware[] = []): void {
const segs = this.tokenize(path);
let cur = this.root;
for (let i = 0; i < segs.length; i++) {
const seg = segs[i];
if (seg === "*") {
if (i !== segs.length - 1) throw new Error(`Wildcard "*" must be final segment: ${path}`);
cur = cur.wildcardChild ?? (cur.wildcardChild = new TrieNode());
} else if (seg.startsWith(":")) {
const name = seg.slice(1);
if (!name) throw new Error(`Empty param name: ${path}`);
if (!cur.paramChild) cur.paramChild = { name, node: new TrieNode() };
else if (cur.paramChild.name !== name) throw new Error(`Conflicting param :${name} vs :${cur.paramChild.name}`);
cur = cur.paramChild.node;
} else {
let next = cur.staticChildren.get(seg);
if (!next) { next = new TrieNode(); cur.staticChildren.set(seg, next); }
cur = next;
}
}
if (cur.methods.has(method)) throw new Error(`Duplicate route: ${method} ${path}`);
cur.methods.set(method, { handler, middlewares });
}
public async handle(method: HttpMethod, path: string, headers: Record<string, string> = {}): Promise<HttpResponse> {
const segs = this.tokenize(path);
const hit = this.matchNode(this.root, segs, 0, {});
if (!hit) return { status: 404, body: { error: "Not Found" } };
const entry = hit.node.methods.get(method);
if (!entry) {
return { status: 405, body: { error: "Method Not Allowed", allow: Array.from(hit.node.methods.keys()) } };
}
const req: HttpRequest = { method, path, headers, params: hit.params, wildcard: hit.wildcard };
return this.executeChain([...this.globalMiddlewares, ...entry.middlewares], entry.handler, req);
}
private matchNode(
node: TrieNode, segs: string[], idx: number, params: Record<string, string>
): { node: TrieNode; params: Record<string, string>; wildcard?: string } | null {
if (idx === segs.length) return node.methods.size > 0 ? { node, params: { ...params } } : null;
const seg = segs[idx];
// 1. Static > 2. :param > 3. * wildcard
const staticChild = node.staticChildren.get(seg);
if (staticChild) {
const hit = this.matchNode(staticChild, segs, idx + 1, params);
if (hit) return hit;
}
if (node.paramChild) {
params[node.paramChild.name] = seg;
const hit = this.matchNode(node.paramChild.node, segs, idx + 1, params);
delete params[node.paramChild.name];
if (hit) return hit;
}
if (node.wildcardChild && node.wildcardChild.methods.size > 0) {
return { node: node.wildcardChild, params: { ...params }, wildcard: segs.slice(idx).join("/") };
}
return null;
}
private async executeChain(middlewares: Middleware[], handler: RouteHandler, req: HttpRequest): Promise<HttpResponse> {
let lastIndex = -1;
const dispatch = async (i: number): Promise<HttpResponse> => {
if (i <= lastIndex) throw new Error("next() called multiple times in one middleware");
lastIndex = i;
return i === middlewares.length ? handler(req) : middlewares[i](req, () => dispatch(i + 1));
};
return dispatch(0);
}
private tokenize(path: string): string[] {
const clean = path.split("?")[0].replace(/^\/+|\/+$/g, "");
return clean === "" ? [] : clean.split("/");
}
}2. Write Focused Unit Tests & Verify Minute-30 Extensions (Minutes 30 to 50)
Assert four cases:
- Static beats
:param: RegisterGET /users/:idfirst andGET /users/mesecond; assert/users/mehits the static handler. - Method isolation &
405: RegisterGET /invoicesonly; assertPOST /invoicesreturns405withallow: ["GET"]. - Per-route auth short-circuit: Attach
requireBearerAuthtoDELETE /users/:id; missing header returns401without invoking the handler. - Wildcard fallback: Register
GET /files/*;/files/2026/q1/audit.pdfcaptureswildcard: "2026/q1/audit.pdf".
Worked Production Scenario: Before vs. After
Context: A fintech API gateway routed 420 endpoints across 8 microservices using a flat regex array loaded from per-squad config files. When a release shifted load order, GET /v1/accounts/:id shadowed GET /v1/accounts/export for 45 minutes (400 Invalid UUID: "export"), and global auth exclusion regexes accidentally exposed an admin route.
After: The Platform team migrated to the Segment Prefix Trie router with structural precedence, startup conflict assertions, and explicit per-route auth middleware arrays.
| Metric | Before | After |
|---|---|---|
| Route lookup latency (420 routes) | 1.9 ms p99 (linear scan) | 0.04 ms p99 (O(depth)) |
| Route-shadowing outages / quarter | 3 incidents | 0 (enforced structurally) |
| Auth middleware misconfig findings | 2 high-severity | 0 (explicit per-route chains) |
| Duplicate route conflict detection | None (silent override) | Fails CI on startup |
Common Failure Modes & Anti-Patterns
- Leaking
paramsduring trie backtracking: Failing a:parambranch and falling back to*withoutdelete params[name]leaves stale keys onreq.params. Fix: Delete the param key after each recursive branch returns and clone{ ...params }on hit. - Allowing duplicate
next()invocations: A buggy middleware callingnext()twice executes the handler twice and risks double-writes. Fix: Guardi <= lastIndexinsideexecuteChain(). - Silent conflicting param names: Allowing
/orgs/:orgId/aand/orgs/:tenantId/bon the same node breaks deterministic param extraction. Fix: Fail fast duringaddRoute().
How to Handle Pushback in the Room
Skeptical Principal Engineer: "Why drill router internals when Fastify and Hono already exist?"
Calm Response: "In production, we absolutely use Fastify or Hono rather than rolling our own HTTP router. Understanding trie precedence and middleware dispatch lets our Tech Leads diagnose route shadowing, middleware short-circuits, and gateway latency spikes in minutes."
Pushing Product Manager: "Can we mount a vanity-URL catch-all (/:orgSlug/*) at the top of the gateway this week?"
Calm Response: "Putting a catch-all at the top shadows static health and API routes unless precedence is structural. With trie static-over-param rules, we can mount /:orgSlug/* safely while guaranteeing /health and /api/* always win."
Key Takeaways & This Week's Action Rep
- Use a Segment Prefix Trie (
O(depth)): Lookup cost stays constant whether you have 20 or 2,000 endpoints. - Make precedence structural: Static >
:param>*eliminates merge-order routing outages. - Fail fast at startup: Reject duplicate routes, mid-path wildcards, and conflicting param names in CI.
- Guard middleware dispatch: Block double-
next()execution and compose global + per-route auth cleanly.
This Week's Action Rep: Code ApiRouter in 45 minutes without autocomplete. At minute 30, add 405 handling and a requireAuth per-route middleware test proving unauthenticated requests short-circuit with 401.