llmgw — LLM Gateway
llmgw is a reverse proxy, written in Go, that sits in front of one or more OpenAI-compatible LLM APIs. A client points the OpenAI SDK's base_url at the gateway and keeps its code unchanged; the gateway adds per-key rate limiting, health-checked routing with failover, token and cost accounting, Prometheus metrics, and an optional semantic cache, while passing streamed responses through without buffering. It is meant for a developer or small team running several applications against LLM providers who want one place to enforce limits and see what the traffic costs. It is a single process with in-memory state.
Features
Each feature below is implemented in the current code and covered by the tests named beside it.
| Feature | Tests |
|---|---|
OpenAI-compatible /v1/chat/completions and /v1/models, with gateway errors in the OpenAI error envelope |
TestErrorEnvelopeShape, TestModelsEndpoint, scripts/verify-sdk.py |
| Streaming passthrough with a flush per event; client disconnect cancels the upstream call; an idle timeout bounds the gap between events | TestStreamingIsUnbuffered, TestTheUnbufferedTestActuallyDetectsBuffering, TestClientDisconnectCancelsUpstream, TestStreamIdleTimeoutCutsStalledStream |
Per-key rate limiting: a requests-per-second bucket checked before the body is read, and a tokens-per-minute bucket charged with a prompt estimate and reconciled against real usage; 429 with Retry-After; idle limiters evicted |
TestRequestBurstIsExact, TestRefillTiming, TestRateLimitResponseShape, TestSweepEvictsOnlyIdleLimiters, TestIdleTTLMustCoverTheWorstCaseRefill |
Smooth weighted round-robin across healthy upstreams, background health checks, and one retry on connection error or 502/503/504 before the first byte reaches the client, never after |
TestWeightedDistribution, TestThresholdBeforeMarkingUnhealthy, TestFailoverOnConnectionError, TestNoRetryAfterStreamingBegins, TestNoRetryOn4xx |
Token counting with a tiktoken-compatible BPE tokeniser, per-tenant and per-model cost, the provider's usage preferred when present, and every figure labelled as measured or estimated |
TestUpstreamUsageIsAuthoritative, TestStreamedUsageFallsBackToLocalCounting, TestAccountantAccumulatesPerTenantAndModel, TestAccessLogCarriesCostAndSource |
Prometheus text-format /metrics (hand-rolled, no client library) and /healthz |
TestMetricsEndpointShape, TestTokenAndCostMetrics, TestMetricsNeverExposeGatewayKeys, TestHealthOK |
| Optional semantic cache: cosine similarity over embeddings, isolated per tenant, only for non-streaming low-temperature requests, LRU and TTL eviction, stores run in the background with a concurrency bound | TestCacheHitAvoidsUpstream, TestCacheNeverServesAnotherTenant, TestHighTemperatureIsNotCached, TestLRUEviction, TestCacheStoreDoesNotHoldTheConnection |
| Graceful shutdown that drains in-flight requests up to a deadline | TestServeDrainsInFlightRequest, TestShutdownDeadlineCancelsStragglers |
A mock OpenAI-compatible upstream with streaming, token delay, injected failures and --die-after |
cmd/mockupstream tests, e.g. TestDieAfterIgnoresHealthChecks |
go test -race ./... passes on all 13 packages.
Quick start
Requires Go 1.26 or newer. The commands below use make; on Windows use MSYS2's mingw32-make, or run the Go command shown beside each target.
make build # go build ./...
make test # go test ./...
Start the mock upstream in one terminal:
make mock # go run ./cmd/mockupstream (listens on 127.0.0.1:9090)
Start the gateway in front of it in a second terminal:
make run # BENCH_UPSTREAM_KEY=sk-bench-upstream go run ./cmd/gateway --config scripts/sdk-mock.yaml
curl http://127.0.0.1:8080/healthz
# {"status":"ok","upstreams":[{"name":"mock","healthy":true}]}
scripts/sdk-mock.yaml needs no provider key. Its gateway key is sk-gw-sdk, limited to 5 requests per second. Point the OpenAI Python SDK at the gateway (pip install openai):
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="sk-gw-sdk")
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "hello"}],
)
print(resp.choices[0].message.content)
for chunk in client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "hello"}],
stream=True,
):
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
scripts/verify-sdk.py runs a fuller SDK check against the same setup, including the 401, 404 and 429 error mappings; see scripts/README.md.
A real provider. configs/config.example.yaml documents every setting. configs/config.groq.example.yaml is a working template for Groq; copy it, export the key named by its api_key_env, and start the gateway with go run ./cmd/gateway --config <your copy>. Config files name environment variables and never contain keys, and the gateway does not read .env itself; .env.example lists the variables. Upstream URLs are built as base_url + /v1/..., so base_url omits the version segment (for example https://api.groq.com/openai).
Architecture
Client (OpenAI SDK)
|
v
+-------------------------------+
| Gateway |
| HTTP server (net/http) |
| ├─ auth: gateway key → tenant|
| ├─ rate limiter (per key) |
| ├─ semantic cache (optional) |
| ├─ router (pick upstream) |
| ├─ proxy (stream or buffer) |
| ├─ token/cost accounting |
| └─ metrics (/metrics) |
+-------------------------------+
| |
v v
Upstream A Upstream B
The middleware order is LogRequests → Observe → Recover → Authenticate → LimitRequests, then the handler. docs/guide/README.md walks a request through the packages in order, and docs/decisions/ records why each non-obvious choice was made.
Benchmarks
Conditions: Intel Core i7-8650U (4 cores, 8 threads, 16 GB), Windows 11 Pro, Go 1.27.0. The load generator, the gateway and the mock upstreams ran on the same machine, so these are figures for a shared laptop, not for dedicated hardware. The rate, 20 req/s streaming and behaviour-under-load tables are from commit 8925aba, 2026-09-10, with GOMAXPROCS=8. The concurrent-stream tables are from later sessions, each named in its rows. Every number is read from a file in bench/results/. make bench-report regenerates every table from those files, and make check fails if a table no longer matches them.
Each latency figure is service time (request start to last byte) from bench/loadgen, an open-loop generator that holds the request rate fixed. "Added" is the gateway run minus the baseline run, which sends the same load straight to the mock.
Setup shared by the rows below:
go build -o loadgen ./bench/loadgen
export BENCH_UPSTREAM_KEY=sk-bench-upstream
go run ./cmd/mockupstream --addr 127.0.0.1:9090 --response-tokens 64 --log-level warn
go run ./cmd/mockupstream --addr 127.0.0.1:9091 --response-tokens 64 --log-level warn
go run ./cmd/gateway --config bench/bench.yaml
Added latency against request rate
Command, for each rate N (15 s runs; 12 s from 4,000/s up):
./loadgen -target http://127.0.0.1:9090 -rate N -duration 15s -warmup 3s -out bench/results/baseline-N.json
./loadgen -target http://127.0.0.1:8080 -key sk-bench-open -rate N -duration 15s -warmup 3s -out bench/results/gateway-N.json
| Rate | Baseline p50 | Gateway p50 | Added p50 | Baseline p99 | Gateway p99 | Added p99 | Files |
|---|---|---|---|---|---|---|---|
| 50/s | 0.429 ms | 0.850 ms | +0.421 ms | 0.744 ms | 1.269 ms | +0.525 ms | *-50.json |
| 100/s | 0.404 ms | 0.817 ms | +0.413 ms | 0.672 ms | 1.253 ms | +0.581 ms | *-100.json |
| 200/s | 0.426 ms | 0.791 ms | +0.365 ms | 0.790 ms | 1.313 ms | +0.523 ms | *-200.json |
| 500/s | 0.354 ms | 0.783 ms | +0.429 ms | 0.926 ms | 1.562 ms | +0.636 ms | *-500.json |
| 1,000/s | 0.339 ms | 0.693 ms | +0.354 ms | 0.911 ms | 1.346 ms | +0.435 ms | *-1000.json |
| 2,000/s | 0.297 ms | 0.724 ms | +0.426 ms | 0.706 ms | 1.498 ms | +0.793 ms | *-2000.json |
| 4,000/s | 0.309 ms | 0.718 ms | +0.409 ms | 0.981 ms | 2.526 ms | +1.545 ms | *-4000.json |
| 6,000/s | 0.320 ms | 0.856 ms | +0.537 ms | 1.078 ms | 6.668 ms | +5.590 ms | *-6000.json |
| 8,000/s | 0.313 ms | 362.324 ms | — | 1.263 ms | 7,213.752 ms | — | *-8000.json |
Added p50 stays between 0.35 and 0.54 ms from 50 to 6,000 requests per second. p99 rises first, at 4,000/s and above. At 8,000/s the gateway run completed 34,543 of 72,000 requests: 36,677 were shed at the generator's in-flight limit and 780 were refused connections. The baseline run served the same rate with neither, so the mock was not the limit. The run cannot separate a machine saturated by the generator, gateway and mocks sharing eight threads from the gateway's own accept queue overflowing; that would need the gateway on dedicated cores. The gateway has no load shedding of its own, so past capacity overload reaches clients as refused connections and latency rather than as 503s.
Streaming
Mock restarted with --response-tokens 50 --token-delay 20ms; runs with -stream -rate 20 -duration 20s -warmup 3s, baseline and gateway as above (baseline-stream.json, gateway-stream.json).
| Metric | Baseline | Gateway | Added |
|---|---|---|---|
| Time to first byte, p50 | 0.339 ms | 0.714 ms | +0.376 ms |
| Gap between events, p50 | 20.409 ms | 20.396 ms | -0.013 ms |
| Gap between events, p99 | 20.760 ms | 20.740 ms | -0.020 ms |
The gap rows are negative: through the gateway the gaps were no longer than straight from the mock, to within what one run resolves.
Concurrent streams
The concurrent-stream suite (make bench-stream-full, decision 016) starts the mock and the gateway itself, from binaries built at the commit it records. It ran on the High performance power plan, on AC power, with Defender excluding the repository. The mock sends 50 tokens, with 20 ms before the first and between each, so a stream lives about a second. To hold N streams open, the generator opens N a second. Every configuration ran 5 times, interleaved with the others. Each value is the median of the five, with the min-to-max range in brackets. Overhead is the gateway run minus a baseline run straight to the mock, made beside it. A run during which other processes used more than 5% of the machine is flagged as disturbed, and counted, never dropped.
The sessions are:
- two full suites, one on each side of
2050a81, which shrank Pipe's copy buffer from 32 KiB to 4 KiB; - two sessions of the buffer A/B described below.
Together they give six measurements each at 200 and 500 streams.
50 and 200 streams, where every session agrees:
| Streams | Session | Pipe buffer | TTFB overhead p50 | p99 | p99.9 | gap p99 overhead | generator lag p99 | disturbed pairs |
|---|---|---|---|---|---|---|---|---|
| 50 | streams-3c194d9 |
32 KiB | +0.342 [+0.331 to +0.345] | +0.427 [+0.405 to +0.596] | +0.840 [+0.409 to +1.071] | +0.073 [+0.050 to +0.086] | 0.115 [0.088 to 0.125] | none |
| 50 | streams-137f97e |
4 KiB | +0.344 [+0.333 to +0.344] | +0.409 [+0.353 to +1.247] | +0.838 [+0.326 to +20.552] | +0.055 [+0.049 to +0.223] | 0.123 [0.115 to 0.136] | none |
| 200 | streams-3c194d9 |
32 KiB | +0.292 [+0.280 to +0.299] | +0.685 [+0.638 to +0.835] | +1.826 [+1.521 to +2.109] | +0.037 [+0.027 to +0.121] | 0.043 [0.041 to 0.050] | none |
| 200 | streams-137f97e |
4 KiB | +0.313 [+0.307 to +0.326] | +0.850 [+0.666 to +1.118] | +2.121 [+1.443 to +8.192] | +0.081 [+0.029 to +0.165] | 0.059 [0.046 to 0.078] | none |
| 200 | buffer-ab-927a339 |
32 KiB | +0.330 [+0.296 to +0.338] (1 disturbed; +0.332 without) | +0.623 [+0.588 to +0.764] (1 disturbed; +0.622 without) | +1.558 [+1.465 to +2.006] (1 disturbed; +1.639 without) | +0.097 [+0.031 to +0.214] (1 disturbed; +0.084 without) | 0.053 [0.041 to 0.066] (1 disturbed; 0.054 without) | 1 of 5 |
| 200 | buffer-ab-927a339 |
4 KiB | +0.321 [+0.314 to +0.327] | +0.728 [+0.640 to +0.786] | +1.721 [+1.278 to +2.232] | +0.069 [+0.028 to +0.112] | 0.049 [0.042 to 0.067] | none |
| 200 | buffer-ab-34f68ae-reversed |
4 KiB | +0.287 [+0.278 to +0.295] | +0.680 [+0.481 to +0.700] | +1.490 [+0.998 to +1.846] | +0.061 [+0.001 to +0.078] | 0.047 [0.041 to 0.066] | none |
| 200 | buffer-ab-34f68ae-reversed |
32 KiB | +0.304 [+0.298 to +0.311] | +0.705 [+0.639 to +0.825] | +1.524 [+1.357 to +1.935] | +0.024 [+0.013 to +0.052] | 0.049 [0.043 to 0.053] | none |
At 200 streams, in all six measurements, the gateway adds 0.29 to 0.33 ms to time to first byte at p50 and 0.62 to 0.85 ms at p99 (session medians). Its median addition to the p99 gap between events, which is where buffering under concurrency would show, is under 0.1 ms in every session.
500 streams is this laptop's saturation point. The generator, the gateway and the mock share four physical cores, and at 500 streams the generator itself runs late: its own p99 lag is 3 to 6 ms in every session.
| Streams | Session | Pipe buffer | TTFB overhead p50 | p99 | p99.9 | gap p99 overhead | generator lag p99 | disturbed pairs |
|---|---|---|---|---|---|---|---|---|
| 500 | streams-3c194d9 |
32 KiB | +0.546 [+0.538 to +0.566] | +5.289 [+4.967 to +6.154] | +10.318 [+7.870 to +14.546] | +4.800 [+4.505 to +5.541] | 3.588 [3.499 to 4.167] | none |
| 500 | streams-137f97e |
4 KiB | +0.627 [+0.603 to +1.246] (1 disturbed; +0.623 without) | +11.488 [+5.864 to +32.904] (1 disturbed; +8.683 without) | +29.988 [+8.742 to +106.733] (1 disturbed; +20.090 without) | +6.644 [+5.084 to +12.319] (1 disturbed; +5.893 without) | 5.412 [3.854 to 12.868] (1 disturbed; 4.639 without) | 1 of 5 |
| 500 | buffer-ab-927a339 |
32 KiB | +0.618 [+0.479 to +0.683] | +5.652 [+5.339 to +18.600] | +10.056 [+7.802 to +54.592] | +5.040 [+4.969 to +8.606] | 3.856 [3.781 to 6.646] | none |
| 500 | buffer-ab-927a339 |
4 KiB | +0.626 [+0.620 to +0.881] (1 disturbed; +0.624 without) | +17.283 [+11.462 to +42.302] (1 disturbed; +15.508 without) | +51.197 [+42.230 to +144.247] (1 disturbed; +53.536 without) | +6.835 [+6.254 to +10.657] (1 disturbed; +6.586 without) | 5.931 [5.597 to 21.911] (1 disturbed; 5.873 without) | 1 of 5 |
| 500 | buffer-ab-34f68ae-reversed |
4 KiB | +0.535 [+0.442 to +0.549] | +5.238 [+4.302 to +5.564] | +8.639 [+4.506 to +12.553] | +4.695 [+3.674 to +4.979] | 3.432 [3.002 to 3.738] | none |
| 500 | buffer-ab-34f68ae-reversed |
32 KiB | +0.560 [+0.552 to +0.639] | +5.335 [+5.096 to +14.409] | +8.280 [+8.060 to +39.152] | +4.475 [+4.355 to +8.450] | 3.502 [3.286 to 8.450] | none |
The clean figure is from buffer-ab-34f68ae-reversed, the only session with no disturbed runs. There, the shipped 4 KiB build's p99 TTFB overhead was +5.238 ms [+4.302 to +5.564]. Across sessions, p99 moved with the machine's state rather than with the gateway. The two full suites' medians were +5.3 ms (3c194d9) and +11.5 ms (137f97e). The first A/B session's 4 KiB runs reached +17.3 ms, with WSL and Docker running in the background. p50 stayed between +0.53 and +0.63 ms in every session.
Where p99 TTFB overhead crosses 5 ms. A sweep raises the number of open streams until p99 overhead passes the threshold:
| Session | Threshold | Crossed at (median [range]) | Step per repetition | generator lag p99 in the crossing run | Limit, as the suite reads it |
|---|---|---|---|---|---|
streams-3c194d9 |
5.0 ms | 750 [500 to 750] streams | 500, 750, 750, 750, 500 | 27.140 [3.602 to 29.417] ms | generator in 5 of 5 |
streams-137f97e |
5.0 ms | 500 [500 to 500] streams | 500, 500, 500, 500, 500 | 4.691 [4.335 to 13.994] ms | generator in 5 of 5 |
In every repetition of both suites, the generator's own p99 lag in the crossing run was at least half the threshold, so the suite attributes the crossing to the generator. The crossing marks where this shared laptop stops being able to measure the gateway. It is not a capacity limit of the gateway.
Co-location. At 200 streams, each suite also ran with the generator, the mock and the gateway pinned to disjoint physical cores (one, one and two), against the default of all three sharing every core:
| Session | Quantity | Unpinned | Pinned to disjoint cores | Beyond run-to-run range? |
|---|---|---|---|---|
streams-3c194d9 |
TTFB overhead p50 (ms) at 200 streams | +0.292 [+0.280 to +0.299] | +0.358 [+0.351 to +0.365] (1 disturbed; +0.356 without) | yes |
streams-3c194d9 |
TTFB overhead p99 (ms) at 200 streams | +0.685 [+0.638 to +0.835] | +0.655 [+0.270 to +1.067] (1 disturbed; +0.538 without) | no |
streams-3c194d9 |
TTFT overhead p99 (ms) at 200 streams | +0.535 [+0.528 to +0.620] | +0.823 [+0.363 to +1.475] (1 disturbed; +0.605 without) | no |
streams-3c194d9 |
gap p99 through the gateway (ms) at 200 streams | 21.664 [21.645 to 21.719] | 22.587 [22.209 to 23.289] (1 disturbed; 22.463 without) | yes |
streams-137f97e |
TTFB overhead p50 (ms) at 200 streams | +0.313 [+0.307 to +0.326] | +0.374 [+0.363 to +0.377] | yes |
streams-137f97e |
TTFB overhead p99 (ms) at 200 streams | +0.850 [+0.666 to +1.118] | +0.667 [+0.408 to +1.007] | no |
streams-137f97e |
TTFT overhead p99 (ms) at 200 streams | +0.635 [+0.585 to +0.962] | +0.701 [+0.394 to +1.014] | no |
streams-137f97e |
gap p99 through the gateway (ms) at 200 streams | 21.712 [21.686 to 21.785] | 22.625 [22.598 to 22.726] | yes |
In both suites, pinning raised p50 TTFB overhead by about 0.06 ms and the gap p99 through the gateway by about 0.9 ms, beyond the run-to-run range. p99 TTFB overhead stayed within range. Pinning gives each process fewer cores, so it is not a cleaner configuration here, only a different one.
Memory per open stream. These are slopes of a least-squares fit across 0, 50, 200 and 500 open streams, over five repetitions:
| Per open stream | streams-3c194d9 (32 KiB Pipe buffer) |
streams-137f97e (4 KiB Pipe buffer) |
|---|---|---|
| Working set (OS), slope | 188.1 KiB [186.5 KiB to 189.0 KiB] | 137.7 KiB [137.3 KiB to 139.5 KiB] |
| Private bytes (OS), slope | 186.9 KiB [186.4 KiB to 188.3 KiB] | 135.9 KiB [135.4 KiB to 137.4 KiB] |
Go heap including uncollected garbage (llmgw_heap_bytes), slope |
106.5 KiB [90.0 KiB to 112.7 KiB] | 59.3 KiB [57.3 KiB to 67.3 KiB] |
| Go heap, live (heap profiles after a forced GC) | not captured in this run | 33.6 KiB [24.9 KiB to 40.9 KiB] (200 streams against 0, 10 profiles per step) |
| Goroutines, slope | 4.00 [3.99 to 4.01] | 4.04 [4.02 to 4.24] |
Shrinking Pipe's copy buffer from 32 KiB to 4 KiB (2050a81) took the working set per open st
