Skip to content
Projects
Reference implementation

llm-routing-gateway

A policy-driven model router with explainable decisions, fallbacks behind circuit breakers, tenant budgets, and a replay harness that regression-tests routing changes against recorded traffic.

Status
Reference implementation. Providers are in-process mocks, and models, prices and tenants are fictional. No network calls.
Authorship
"Implemented with AI coding agents (Claude Code)," in the repository's own words: an independent reference implementation written from scratch, with fictional providers and prices.
Stack
TypeScript · Node.js 22 · Vitest · No runtime dependencies
Demonstrates
Constraint filtering with reason codes · Deterministic weighted ranking · Fallback chains and circuit breakers · Windowed tenant budgets · Replay diff as a CI gate
Verified
122 Vitest tests pass; lint, type check and build are clean; route and replay return their documented exit codes, and the sample log regenerates byte-identically. Observed at commit 838bb497e189d61e133babf6d21d1d50b6219dc6.
Commands run
npm ci
npm run lint
npm run typecheck
npx vitest run
npm run build
Repository
github.com/Donovanfitch-dev/llm-routing-gateway

Engineering problem

In most applications the model is chosen by a string literal buried in a call site. That holds until a provider has an outage, a tenant's contract forbids a vendor, a cheaper model becomes good enough for classification, a data-residency rule appears, or someone asks why spend doubled. Each of those is an operational policy question, and answering it by editing scattered code is slow, unreviewable and untestable as a whole.

Representative solution

Treat model choice as a policy evaluated against a catalog, the way a firewall evaluates rules. A catalog says what exists; a request descriptor says what a call needs; a JSON policy says how to choose; a decision record says exactly what happened and why; and a replay harness says what would change if the policy changed, using recorded requests, before anything ships.

The router itself, routeRequest, is a pure function with no clock, no randomness and no I/O. Open breakers and the tenant's budget window are passed in and echoed into the decision, so every record is self-contained and replayable.

Architecture

Routing runs in a fixed order: pick a task-class override if one applies; evaluate every catalog entry against every hard constraint, without short-circuiting, so an eliminated model lists all of its reasons; score the survivors on weighted cost, quality and latency; rank them with deterministic tie-breaks; apply the budget gate; and build the fallback chain. The gateway then tries the primary and walks the chain on retryable errors, timeouts and unclassified exceptions.

  • Reason codes.DENY_RULE, PROVIDER_NOT_ALLOWED, MISSING_CAPABILITY, CONTEXT_EXCEEDED, REGION_MISMATCH, LATENCY_EXCEEDS_LIMIT, QUALITY_BELOW_MINIMUM, COST_EXCEEDS_LIMIT and CIRCUIT_OPEN.
  • Tie-breaks.Lower estimated cost, then higher quality tier, then route id in plain string order.
  • Data

    Validated on load, with a JSON path for every problem

    • model catalog
    • routing policy
    • request descriptor
  • Routing core

    Pure: no clock, no randomness, no I/O

    • constraint filter
    • weighted ranking
    • budget gate
    • fallback chain
    • decision record
  • Gateway runtime

    • circuit breakers
    • tenant budgets
    • execution with fallback
    • JSONL decision log
  • Replay harness

    Re-routes recorded requests without executing anything

    • diff report
    • threshold exit codes
  • Provider adapters

    In-process mocks behind an adapter interface

    • aurora
    • boreal
    • cirrus

    fictional providers, models and prices

The data the router reads, the pure routing core, the runtime around it, and the tools that replay its records.

Core components

  • router.ts.The pure routing pipeline and the decision record.
  • validate.ts and load.ts.Custom validators with JSON paths for every problem; unknown keys rejected; policy references checked against the catalog.
  • breaker.ts.A per-provider breaker, closed, open and half-open, on an injectable clock. Only availability failures count against it.
  • budget.ts.Per-tenant spend tracked over a fixed window, with reject or downgrade when a request would exceed it.
  • gateway.ts and providers.ts.Execution with fallback over a provider adapter interface, and the scripted MockProvider.
  • log.ts, replay.ts and the CLIs.An append-only JSONL decision log validated on read, the replay engine with thresholds, and the route and replay commands.

Engineering decisions

  • Policy as data.A JSON policy can be diffed, reviewed, validated, versioned and replayed against history. A policy written as code could not be evaluated safely against old traffic.
  • Determinism.Scores are rounded and ties break on explicit keys, so identical inputs produce a byte-identical decision. Load spreading or canarying must therefore be explicit inputs, not randomness inside the router.
  • Only availability failures trip a breaker.A retryable error, a timeout or an unclassified exception counts as a provider fault and falls back. An adapter's explicit non-retryable error means the provider answered and the request was wrong, so it stops the walk and counts as proof of liveness.
  • Budgets charge actual usage.Routing estimates cost from caller-supplied token counts; afterwards the gateway charges what the adapter reports. Every route in the primary slot and the fallback chain must fit the remaining budget by its estimate.

Tradeoffs

  • Expressiveness.The policy language has only the rule shapes the engine understands. That ceiling is deliberate.
  • Soft budget, not a hard cap.Estimates can be wrong and concurrent requests can overshoot a window.
  • Breaker tuning.A low threshold or a long cool-down protects callers but sheds a merely flaky provider; the reverse keeps capacity at the cost of more failed calls. The defaults are illustrative.
  • Relative cost scores.Cost is min-max normalized within the eligible set, so one very expensive candidate compresses the differences among the cheaper ones and lets quality and latency dominate.

Verified functionality

Marked implemented and tested in the repository's status table, and exercised by the suite and the recordings below:

  • Catalog, request and policy types with custom validators
  • Hard-constraint filtering with reason codes, weighted ranking and deterministic tie-breaking
  • Deny rules and per-task-class overrides
  • Execution with fallback across retryable, non-retryable and unclassified errors, and timeouts
  • The circuit breaker, with skips recorded in the decision
  • Per-tenant windowed budgets with reject and downgrade
  • The JSONL decision log, the replay harness, its diff report and threshold exit codes

Demonstration

Four runs of the built CLIs against the repository's synthetic catalog, policies and request log. Every provider (aurora, boreal, cirrus), model, tenant and price is fictional, and no request leaves the process: the adapters are scripted mocks. Nothing here costs money or calls an API.

Routing inputs, policy evaluation and an explained decision

Command: $ node dist/cli/route.js

Request   demo-001  tenant=tenant-alpha  task=extract-json
          tokens in/out=4000/800  capabilities=tools,jsonOutput  region=eu  max-latency=standard  max-cost=$0.020000
Policy    baseline  override=extract-json  weights cost=0.5 quality=0.3 latency=0.2
Status    routed
Budget    within_budget  limit=$1.000000 spent=$0.000000 remaining=$1.000000 estimate=$0.002560
Primary   cirrus/cirrus-flash
Fallbacks 1. aurora/aurora-medium

Ranking (score = weighted cost/quality/latency, 0..1)
  #1  cirrus/cirrus-flash    score=0.8500  cost=1.00 quality=0.50 latency=1.00  est=$0.002560
  #2  aurora/aurora-medium   score=0.3250  cost=0.00 quality=0.75 latency=0.50  est=$0.012800

Eliminated (6 of 8)
  aurora/aurora-large
      LATENCY_EXCEEDS_LIMIT  slow is slower than standard
      COST_EXCEEDS_LIMIT     estimated $0.0512 > max $0.02
  aurora/aurora-lite
      MISSING_CAPABILITY     lacks tools
      QUALITY_BELOW_MINIMUM  tier 2 < required 3
  boreal/boreal-mini
      DENY_RULE              deny-boreal-mini-for-extraction: fictional evaluation finding: unreliable structured extraction
      REGION_MISMATCH        requires eu, offers us, apac
      QUALITY_BELOW_MINIMUM  tier 2 < required 3
  boreal/boreal-pro
      REGION_MISMATCH        requires eu, offers us
  boreal/boreal-vision
      MISSING_CAPABILITY     lacks tools
      REGION_MISMATCH        requires eu, offers us
  cirrus/cirrus-max
      LATENCY_EXCEEDS_LIMIT  slow is slower than standard
      COST_EXCEEDS_LIMIT     estimated $0.0768 > max $0.02
Exit code 0. Recorded output, unedited.The request needs tools and JSON output in the EU within two cents. Six of eight models are eliminated, each with every reason it failed; the two survivors are ranked by their weighted score components; the cheapest becomes primary and the other becomes the fallback.

An open circuit breaker and a budget downgrade

Command: $ node dist/cli/route.js --id demo-002 --tenant tenant-gamma --task code-review --capability tools --in 9000 --out 1200 --open-provider aurora --spent 0.01

Request   demo-002  tenant=tenant-gamma  task=code-review
          tokens in/out=9000/1200  capabilities=tools  region=any  max-latency=any  max-cost=none
Policy    baseline  override=code-review  weights cost=0.1 quality=0.8 latency=0.1
Breakers  open: aurora
Status    routed
Budget    downgraded  limit=$0.050000 spent=$0.010000 remaining=$0.040000 estimate=$0.151200  downgraded from cirrus/cirrus-max
          excluded cirrus/cirrus-max (est $0.151200 > remaining $0.040000) from primary and fallbacks [EXCEEDS_REMAINING_BUDGET]
Primary   boreal/boreal-pro
Fallbacks (none)

Ranking (score = weighted cost/quality/latency, 0..1)
  #1  cirrus/cirrus-max      score=0.8000  cost=0.00 quality=1.00 latency=0.00  est=$0.151200
  #2  boreal/boreal-pro      score=0.7500  cost=1.00 quality=0.75 latency=0.50  est=$0.037800

Eliminated (6 of 8)
  aurora/aurora-large
      CIRCUIT_OPEN           circuit breaker for aurora is open
  aurora/aurora-lite
      MISSING_CAPABILITY     lacks tools
      QUALITY_BELOW_MINIMUM  tier 2 < required 4
      CIRCUIT_OPEN           circuit breaker for aurora is open
  aurora/aurora-medium
      CIRCUIT_OPEN           circuit breaker for aurora is open
  boreal/boreal-mini
      QUALITY_BELOW_MINIMUM  tier 2 < required 4
  boreal/boreal-vision
      MISSING_CAPABILITY     lacks tools
      QUALITY_BELOW_MINIMUM  tier 3 < required 4
  cirrus/cirrus-flash
      QUALITY_BELOW_MINIMUM  tier 3 < required 4
Exit code 0. Recorded output, unedited.aurora's breaker is open, so all three aurora models are excluded with CIRCUIT_OPEN. The best-scoring route would cost $0.1512 against $0.04 left in the tenant's window, so it is excluded from the primary slot and the fallback chain, and the next affordable route is chosen.

Executing against scripted mock providers

Command: $ npx tsx examples/generate-sample-log.ts

req-001 tenant-alpha  summarize       routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-002 tenant-alpha  classify        routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-003 tenant-beta   chat            routed     success      budget=within_budget open=[] boreal/boreal-mini:timeout(TIMEOUT) aurora/aurora-lite:ok
req-004 tenant-gamma  summarize       routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-005 tenant-alpha  code-review     routed     success      budget=within_budget open=[] aurora/aurora-large:ok
req-006 tenant-beta   extract-json    routed     success      budget=within_budget open=[] aurora/aurora-medium:ok
req-007 tenant-gamma  classify        routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-008 tenant-alpha  vision-describe routed     success      budget=within_budget open=[] boreal/boreal-vision:ok
req-009 tenant-beta   code-review     routed     success      budget=within_budget open=[] aurora/aurora-large:error(UNAVAILABLE) boreal/boreal-pro:ok
req-010 tenant-alpha  chat            routed     success      budget=within_budget open=[] boreal/boreal-mini:ok
req-011 tenant-gamma  code-review     routed     success      budget=downgraded open=[] aurora/aurora-medium:error(UNAVAILABLE) boreal/boreal-pro:ok
req-012 tenant-alpha  code-review     routed     success      budget=within_budget open=[] aurora/aurora-large:error(UNAVAILABLE) cirrus/cirrus-max:ok
req-013 tenant-beta   code-review     routed     success      budget=within_budget open=[aurora] boreal/boreal-pro:ok
req-014 tenant-alpha  code-review     routed     success      budget=within_budget open=[aurora] cirrus/cirrus-max:ok
req-015 tenant-gamma  chat            routed     success      budget=within_budget open=[aurora] cirrus/cirrus-flash:ok
req-016 tenant-alpha  summarize       routed     success      budget=within_budget open=[aurora] cirrus/cirrus-flash:ok
req-017 tenant-beta   classify        routed     success      budget=within_budget open=[] boreal/boreal-mini:ok
req-018 tenant-alpha  vision-describe routed     success      budget=within_budget open=[] aurora/aurora-large:ok
req-019 tenant-beta   extract-json    routed     failed       budget=within_budget open=[] aurora/aurora-medium:error(INVALID_REQUEST)
req-020 tenant-alpha  code-review     routed     success      budget=downgraded open=[] aurora/aurora-medium:ok
req-021 tenant-gamma  summarize       routed     success      budget=downgraded open=[] boreal/boreal-mini:ok
req-022 tenant-alpha  chat            routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-023 tenant-beta   vision-describe routed     success      budget=within_budget open=[] boreal/boreal-vision:ok
req-024 tenant-alpha  extract-json    routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-025 tenant-gamma  vision-describe rejected   not_executed budget=rejected open=[] 
req-026 tenant-alpha  summarize       routed     success      budget=within_budget open=[] boreal/boreal-mini:ok
req-027 tenant-beta   chat            routed     success      budget=within_budget open=[] boreal/boreal-mini:ok
req-028 tenant-alpha  code-review     routed     success      budget=downgraded open=[] aurora/aurora-medium:ok
req-029 tenant-alpha  classify        routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-030 tenant-beta   summarize       routed     success      budget=within_budget open=[] boreal/boreal-mini:ok
req-031 tenant-alpha  translate       routed     success      budget=within_budget open=[] cirrus/cirrus-flash:ok
req-032 tenant-beta   vision-describe unroutable not_executed budget=- open=[] 
wrote 32 records
Exit code 0. Recorded output, unedited.This is the script that produced the repository's sample log, run through the real gateway. req-003 times out and falls back; req-009, req-011 and req-012 hit UNAVAILABLE, fall back, and trip aurora's breaker, which is open for req-013 to req-016; req-019 gets a non-retryable INVALID_REQUEST, which stops the walk; req-025 is rejected by the budget and req-032 has no eligible model.

Replaying recorded traffic against a candidate policy (exit 1)

Command: $ node dist/cli/replay.js

Replay: baseline (recorded) -> candidate-cost-saver (candidate)

Requests replayed      32
  unchanged            21
  changed primary      6
  newly unroutable     3
  newly routable       1
  still unroutable     1

Estimated cost over 27 comparable requests
  baseline             $0.831148
  candidate            $1.122735
  delta                $0.291587 (+35.08%)

Per task class
  task class        reqs  changed  unroutable      baseline     candidate         delta
  chat                 5        0           0     $0.002700     $0.002700     $0.000000
  classify             4        3           0     $0.000453     $0.000140    -$0.000313
  code-review          8        2           2     $0.780000     $1.063200     $0.283200
  extract-json         3        0           0     $0.026480     $0.026480     $0.000000
  summarize            6        1           0     $0.010190     $0.018890     $0.008700
  translate            1        0           0     $0.002400     $0.002400     $0.000000
  vision-describe      5        0           1     $0.008925     $0.008925     $0.000000

Changed primary routes
  req-002    classify         cirrus/cirrus-flash -> boreal/boreal-mini
  req-007    classify         cirrus/cirrus-flash -> boreal/boreal-mini
  req-020    code-review      aurora/aurora-medium -> aurora/aurora-large
  req-021    summarize        boreal/boreal-mini -> cirrus/cirrus-flash
  req-028    code-review      aurora/aurora-medium -> aurora/aurora-large
  req-029    classify         cirrus/cirrus-flash -> boreal/boreal-mini

Newly unroutable
  req-011    code-review      was aurora/aurora-medium; now rejected [BUDGET_EXCEEDED]
      estimated $0.1008 exceeds remaining $0.046946 and policy rejects
  req-013    code-review      was boreal/boreal-pro; now unroutable [NO_ELIGIBLE_CANDIDATE]
      CIRCUIT_OPEN x3, DENY_RULE x2, MISSING_CAPABILITY x2, QUALITY_BELOW_MINIMUM x6
  req-018    vision-describe  was aurora/aurora-large; now unroutable [NO_ELIGIBLE_CANDIDATE]
      CONTEXT_EXCEEDED x2, MISSING_CAPABILITY x5, PROVIDER_NOT_ALLOWED x5, QUALITY_BELOW_MINIMUM x2

Thresholds: maxNewlyUnroutable=0
Result: FAIL
  - newly unroutable requests 3 exceeds limit 0
Exit code 1. Recorded output, unedited.The candidate policy would change six primary routes, make three requests unroutable and raise estimated cost by 35.08%. The default gate allows zero newly unroutable requests, so the run fails, before anything is deployed.

Reproduce it

git clone https://github.com/Donovanfitch-dev/llm-routing-gateway.git && cd llm-routing-gateway
git checkout 838bb49
npm ci && npm run build
node dist/cli/route.js
node dist/cli/replay.js

Failure modes and limitations

  • Mocks only.There are no real providers, no network calls and no authentication. Quality tiers and latency classes are labels in a JSON file, not measurements.
  • Replay compares primary routes only.A candidate that reorders or shortens fallback chains but keeps the primaries shows no diff. Budget rejections are counted with requests no model can serve, under newly unroutable.
  • Replay cannot measure quality.It shows which requests would route differently and the estimated cost change. It cannot show response quality, real latency, real availability, or how traffic itself would change. Its budget re-simulation approximates the original spend from the log and is a prototype.
  • Single-process state.Breaker state and budget windows live in memory, and two gateway processes would each keep their own view.
  • Estimates, not tokens.There is no tokenizer, and the mock adapters echo the caller's estimates back as usage.
  • Not implemented.Streaming, real SDK adapters, shared state across processes, durable log storage, live quality feedback, policy hot-reload and shadow traffic are conceptual only.

Testing and validation

On 2026-11-11, against commit 838bb49: lint and type check exited cleanly, Vitest reported 122 passed in 9 files, and the build succeeded. The built route command exited 0 for both recorded requests; the built replay command exited 1, as its default gate requires for this candidate policy; and regenerating the sample log produced a file byte-identical to the committed one. The repository's GitHub Actions workflow concluded success on the same commit.

The CLI logic is unit tested; the built binaries have no automated test of their own, which is one reason this page records them running.


Source and documentation