Why LLM Gateway Routing Adds Latency and How to Fix It: Measured TTFT and P95 Through SandBase
Originally published on the SandBase Blog. Routing between LLM providers adds latency in four places: your network to the gateway, the gateway's extra hop, the upstream provider and region that serves the model, and wha
Originally published on the SandBase Blog.
Routing between LLM providers adds latency in four places: your network to the gateway, the gateway's extra hop, the upstream provider and region that serves the model, and whatever the model does before its first visible token. In my 3 December 2026 measurements, the extra hop was the part I could not see. Model behaviour and the upstream path moved the numbers by seconds.
Scope of testing: one Mac in Hangzhou, China, on a congested consumer link to api.sandbase.ai, sequential requests, two runs of 20 per model. Every number includes my network, the SandBase gateway and the upstream provider. I had no direct provider keys, so I cannot split out gateway overhead in milliseconds.
Key takeaway
- Median streaming time to first token (TTFT), 3 Dec 2026, two runs of N=20: Claude Haiku 5.5 1.5 s / 1.5 s, GPT-5.4 mini 2.0 s / 1.8 s, DeepSeek V4.1 Flash (free) 4.8 s / 4.1 s, Gemini 3.8 Flash 7.9 s / 6.1 s.
- TTFT P95 was 1.3 to 3.4 times P50 across models and runs. Plan timeouts around P95 and the tail, not the median.
- The two slowest models spent a median of 58โ228 reasoning tokens before or instead of answering "11, 13, 17". On this prompt, reasoning cost far more time than a routing hop plausibly could.
- OpenRouter's Claude Sonnet 5 page showed P50 latency from 0.77 s (Google Vertex) to 2.25 s (Amazon Bedrock) for the same model and price on 3 Dec 2026. The upstream can matter more than the gateway.
- Prompt caching on Claude Haiku 5.5 through SandBase cut the 6,871-token prefix cost about 10x. It gave no clear TTFT win at that size.
3 Dec 2026, 16:00โ16:11 and 16:21โ16:29 Asia/Shanghai; max_tokens 64, streaming, one keep-alive connection per model. Dashed line: GET /v1/models on a warm connection. Rendered from the raw JSON.
Why routing between LLM providers adds latency
Short answer: a gateway adds one network hop and some request handling, but that was not where the seconds went. The large delays come from a slow or distant upstream, a model that reasons before it answers, a long prompt, a cold TCP/TLS connection, and retries after a timeout. Fix those first.
Your own network path. A bare TCP connect to api.sandbase.ai (Cloudflare's LAX edge, per the cf-ray header) took 152 ms at best and 277 ms at the median over 20 tries. TLS finished at a median of 613 ms. A GET /v1/models on an open connection took a median of 1.4โ1.5 s, about as long as Claude Haiku 5.5's whole TTFT. That GET returns a 12 KB catalog and I can't see its server time, but on this link the network appears to put a floor of roughly a second under every number. If your callers are in Asia and the gateway edge or upstream is in the US, measure this first.
The model thinks before it talks. Gemini 3.8 Flash answered "11, 13, 17" every time, but reported a median of 216 and 228 reasoning tokens in the two runs (range 96โ316) against my 64-token cap. That explains most of its 6โ8 s TTFT. DeepSeek V4.1 Flash (free) used a median 58 and 64 of its 64 tokens on reasoning, and only 15 of 40 calls finished the answer. Claude Haiku 5.5 and GPT-5.4 mini reported 0 reasoning tokens. On latency-critical paths, use a model or mode that does not reason, and size max_tokens for the reasoning budget.
Not explained yet: Gemini 3.8 Flash's usage reported 9,515โ9,526 prompt tokens for my 24-token prompt on every call. I have not traced where those come from.
The tail. TTFT P95 was 1.3โ3.4x P50. One Claude Haiku 5.5 call got its first token at 1.4 s, then took 23.3 s to close a 9-token stream. One DeepSeek free call took 48 s, which a fixed 30 s timeout would have killed.
The measured numbers
| Model (via SandBase) | TTFT P50 run1 / run2 | TTFT P95 run1 / run2 | Total P50 run1 / run2 | Total P95 run1 / run2 | Reasoning tokens (median) |
|---|---|---|---|---|---|
anthropic/claude-haiku-5.5 |
1,480 / 1,499 ms | 5,071 / 3,850 ms | 3,492 / 2,399 ms | 9,088 / 4,036 ms | 0 |
openai/gpt-5.4-mini |
2,021 / 1,835 ms | 3,550 / 3,313 ms | 2,636 / 2,377 ms | 3,810 / 3,778 ms | 0 |
deepseek/deepseek-v4.1-flash:free |
4,828 / 4,118 ms | 8,496 / 10,513 ms | 8,745 / 5,238 ms | 24,131 / 17,643 ms | 58 / 64 |
google/gemini-3.8-flash |
7,880 / 6,082 ms | 10,595 / 14,161 ms | 8,137 / 6,833 ms | 10,598 / 14,555 ms | 216 / 228 |
GET /v1/models, warm connection |
1,509 / 1,426 ms | 2,413 / 3,591 ms | n/a | n/a | n/a |
All 160 streaming calls returned HTTP 200. TTFT is the time from request to the first streamed text, including reasoning text when the provider streams it. P95 of 20 samples is interpolated between the 19th and 20th values, so read it as "the bad tail". The ranking held across both runs, but TTFT P50 moved by up to 1.8 s between runs eight minutes apart. That is the noise on a shared link, and why one run is not enough.
Upstream choice dominates: OpenRouter's public provider latency
I can't benchmark SandBase's upstreams one by one, but OpenRouter publishes per-provider numbers for the same model.
openrouter.ai/anthropic/claude-sonnet-5, Providers section, P50 selected, captured 3 Dec 2026. These are OpenRouter's measurements of its own routing, not SandBase numbers.
Same model, same $2 / $10 list price, and P50 ranged from 0.77 s to 2.25 s under standard routing, and up to 4.92 s on one regional Bedrock endpoint. OpenRouter's pricing FAQ says: "latency varies by model, provider and region. For consistent latency, pin a specific model and provider." A gateway that lands on a fast upstream can beat a direct call to a slow one. One that lands on a slow region costs seconds no proxy tuning wins back.
Prompt caching: a clear cost win, an unproven speed win
I sent a fixed 6,871-token system prompt to Claude Haiku 5.5 through SandBase's Anthropic-compatible POST /v1/messages, with cache_control: {"type": "ephemeral"} on the system block, streaming on: one first call, ten repeats, and five calls with a fresh prompt each. The first call reported cache_creation_input_tokens: 6871. Every repeat reported cache_read_input_tokens: 6871, cache_creation_input_tokens: 0 and input_tokens: 40.
3 Dec 2026, 16:18 Asia/Shanghai. Each call opened a new TLS connection. Costs are observed token counts times the model page prices.
Cost is the clear part. At the Claude Haiku 5.5 page prices on SandBase ($0.09 input, $0.11 cache write, $0.0085 cache read per 1M tokens), the prefix costs $0.618 per 1,000 calls uncached and $0.058 from cache. At Claude Sonnet 5's page prices ($1.70 input, $2.13 write, $0.17 read, rechecked 3 Dec 2026) the same tokens would be about $11.68 versus $1.17.
Speed I can't claim. Cache reads had a median TTFT of 3.4 s and fresh writes 5.0 s, but the ranges overlapped (2.4โ6.1 s versus 2.3โ6.4 s, plus one 15.3 s read). Much longer prompts may show a prefill saving. I didn't measure that.
www.sandbase.ai/models/anthropic/claude-haiku-5.5, captured 3 Dec 2026. The cache read and write prices used in the cost chart come from this card.
Two caveats. In this probe Haiku 5.5 spent all 64 output tokens on thinking (thinking_tokens: 64), so TTFT here is the first thinking delta; the same model reported 0 reasoning tokens on /v1/chat/completions above. And I first ran this on Claude Sonnet 5 with a ~20k-token system block: usage showed input_tokens: 20144 and only 2,297 tokens cached, so my block was not. On Haiku 5.5 the block cached as expected. On any gateway, check cache_read_input_tokens (or prompt_tokens_details.cached_tokens) on your model before counting on the discount.
How to fix LLM gateway latency
| Cause | What I saw on 3 Dec 2026 | Fix |
|---|---|---|
| Network to the gateway edge | TCP 152โ277 ms, TLS 613 ms median, Hangzhou to LAX | Reuse connections; run callers near the gateway edge and upstream region |
| Upstream provider and region | 0.77โ2.25 s P50 for one model (OpenRouter data) | Pin a provider or region you measured as fast; re-measure monthly |
| Reasoning before the answer | 216โ228 median reasoning tokens on Gemini 3.8 Flash, 6โ8 s TTFT | Non-reasoning model or mode on hot paths; budget max_tokens
|
| Long prompts | Cached 6.9k prefix: about 10x cheaper, TTFT unchanged within noise | Cache stable prefixes; trim what you resend |
| Waiting for the whole response | Short streams closed a median 0.44โ0.46 s after the first token | Stream and act on the first tokens |
| Tail latency and timeouts | TTFT P95 1.3โ3.4x P50; single 23 s and 48 s streams | Separate first-token and total timeouts; retry idempotent calls with backoff |
| Upstream outage | none in 160 calls | Fallback: SandBase retries the same model on another upstream provider before returning an error; it does not switch models |
The last row is what gateways are for. When an upstream returns an error, a same-model retry inside the gateway saves your client from handling the failure and re-sending the request itself.
Is there a fastest unified AI API gateway that won't time out during peak traffic?
No single gateway is fastest for everyone. Latency depends on where your callers are, which upstream serves each model, and the model itself. Measure four things from your region at your concurrency: TTFT P50 and P95, total P95, error and timeout rate at peak, and what happens when an upstream fails (same-model fallback, a 5xx, or a hang). My numbers are concurrency 1 and say nothing about peak traffic; use a load tool for that.
GitHub repos for benchmarking unified LLM API response times
Use guidellm or aiperf for LLM-specific TTFT and inter-token latency, and k6 for raw HTTP load. All checked on GitHub on 3 Dec 2026:
- vllm-project/guidellm (Apache-2.0, pushed 2 Dec 2026): targets OpenAI-compatible servers, reports TTFT, inter-token latency and end-to-end distributions, with synchronous, concurrent, constant-rate, Poisson and sweep profiles.
- ai-dynamo/aiperf, a benchmarking tool for generative-AI serving from the Dynamo project, active on 3 Dec 2026.
- grafana/k6, a general HTTP load tester scripted in JavaScript.
- ray-project/llmperf is archived (last push December 2024).
The stdlib script I used is below. It reads SANDBASE_API_KEY from the environment; point --base at another OpenAI-compatible gateway (and swap the key) to compare from the same machine.
#!/usr/bin/env python3
"""Measure TTFT and total time for streaming chat completions through an
OpenAI-compatible endpoint. Standard library only.
export SANDBASE_API_KEY=...
python3 llm_latency_bench.py --n 20 --models anthropic/claude-haiku-5.5 openai/gpt-5.4-mini
Numbers include your network, the gateway and the upstream provider.
"""
import argparse, http.client, json, os, sys, time, urllib.parse
PROMPT = "List three prime numbers between 10 and 30, comma-separated. No other text."
def pct(xs, p):
xs = sorted(xs)
if not xs:
return float("nan")
k = (len(xs) - 1) * p / 100
lo, hi = int(k), min(int(k) + 1, len(xs) - 1)
return xs[lo] + (xs[hi] - xs[lo]) * (k - lo)
def connect(base):
u = urllib.parse.urlparse(base)
return http.client.HTTPSConnection(u.hostname, u.port or 443, timeout=60)
def baseline(base, key, n):
"""GET /v1/models: cold = new TCP+TLS connection each time, warm = keep-alive."""
out = {}
for mode in ("cold", "warm"):
times, conn = [], connect(base)
for _ in range(n):
if mode == "cold":
conn.close()
conn = connect(base)
t0 = time.perf_counter()
conn.request("GET", "/v1/models", headers={"Authorization": f"Bearer {key}"})
r = conn.getresponse()
r.read()
times.append((time.perf_counter() - t0) * 1000)
if r.status != 200:
sys.exit(f"/v1/models returned {r.status}")
conn.close()
out[mode] = times
return out
def one_stream(conn, key, model, max_tokens):
body = json.dumps({
"model": model,
"messages": [{"role": "user", "content": PROMPT}],
"max_tokens": max_tokens,
"stream": True,
"stream_options": {"include_usage": True},
})
t0 = time.perf_counter()
conn.request("POST", "/v1/chat/completions", body=body, headers={
"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
r = conn.getresponse()
if r.status != 200:
return {"error": f"HTTP {r.status}: {r.read()[:200]!r}"}
first_byte = first_token = None
text, usage = "", None
while True:
line = r.readline()
if not line:
break
if first_byte is None:
first_byte = time.perf_counter()
line = line.strip()
if not line.startswith(b"data:"):
continue
data = line[5:].strip()
if data == b"[DONE]":
break
chunk = json.loads(data)
usage = chunk.get("usage") or usage
for ch in chunk.get("choices") or []:
d = ch.get("delta") or {}
piece = d.get("content") or d.get("reasoning_content") or d.get("reasoning") or ""
if piece and first_token is None:
first_token = time.perf_counter()
text += d.get("content") or ""
r.read()
t1 = time.perf_counter()
ms = lambda t: None if t is None else round((t - t0) * 1000, 1)
return {"ttfb_ms": ms(first_byte), "ttft_ms": ms(first_token), "total_ms": ms(t1),
"text": text.strip()[:80], "usage": usage}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base", default="https://api.sandbase.ai")
ap.add_argument("--models", nargs="*", default=[
"anthropic/claude-haiku-5.5", "openai/gpt-5.4-mini",
"google/gemini-3.8-flash", "deepseek/deepseek-v4.1-flash:free"])
ap.add_argument("--n", type=int, default=20)
ap.add_argument("--max-tokens", type=int, default=64)
ap.add_argument("--json-out")
a = ap.parse_args()
key = os.environ.get("SANDBASE_API_KEY") or sys.exit("set SANDBASE_API_KEY")
report = {"started": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "n": a.n, "prompt": PROMPT}
b = baseline(a.base, key, a.n)
report["baseline_ms"] = b
for mode, xs in b.items():
print(f"GET /v1/models {mode:4} p50 {pct(xs, 50):7.0f} ms p95 {pct(xs, 95):7.0f} ms")
print(f"\n{'model':38} {'ok':>5} {'TTFT p50':>9} {'TTFT p95':>9} {'total p50':>10} {'total p95':>10}")
report["models"] = {}
for model in a.models:
conn, runs = connect(a.base), []
for _ in range(a.n): # sequential, one keep-alive connection per model
try:
runs.append(one_stream(conn, key, model, a.max_tokens))
except Exception as e: # network error: record it, reconnect, keep going
runs.append({"error": repr(e)})
conn.close()
conn = connect(a.base)
conn.close()
report["models"][model] = runs
ok = [x for x in runs if "error" not in x and x["ttft_ms"] is not None]
tt = [x["ttft_ms"] for x in ok]
tot = [x["total_ms"] for x in ok]
print(f"{model:38} {len(ok):>2}/{a.n:<2} {pct(tt, 50):9.0f} {pct(tt, 95):9.0f}"
f" {pct(tot, 50):10.0f} {pct(tot, 95):10.0f}")
if a.json_out:
json.dump(report, open(a.json_out, "w"), indent=1)
if __name__ == "__main__":
main()
Run python3 llm_latency_bench.py --n 20 --json-out run.json at least twice, at peak hours, from the region where your servers live.
Start a free trial for an AI API platform with built-in caching
SandBase's Start plan is $0 with starter credits, no subscription and no credit card to start; after that you pay per call from one balance, failed calls are not charged, and model pages list token prices at or below the provider list price. For caching, the Claude Haiku 5.5 page lists cache read and write prices ($0.0085 and $0.11 per 1M tokens), and in my test the usage fields showed the provider's cache reads. That is prompt caching, not a response cache that returns stored answers.
Two alternatives, from their docs as of 3 Dec 2026:
- OpenRouter: the pricing page lists prompt caching as not on the Free plan and included on Standard (pay-as-you-go, 5.5% fee on credit purchases). Its caching guide describes sticky routing that keeps a cached conversation on one provider.
-
Vercel AI Gateway: a free tier with monthly free credits on a subset of models.
caching: 'auto'adds cache markers for Anthropic, MiniMax and Alibaba; responses are not stored, so response caching lives in your app.
What this test does not show
One machine, one city, one afternoon, concurrency 1: not a capacity test or an SLA. Gateway overhead is not isolated. The Gemini prompt-token count and the Sonnet 5 caching behaviour are untraced observations.
FAQ
How much latency does an LLM gateway add?
One network hop plus request handling; I couldn't isolate it without direct provider keys. To measure it, call the same model directly and through the gateway, from the same machine, at the same time.
Should I use streaming to reduce latency?
Yes for anything a person watches. It doesn't make the first token sooner, but you can act on it without waiting for the full response.
Does prompt caching make responses faster?
Cheaper, yes (about 10x on the cached prefix). Faster, not measurably at 6.9k tokens.
What timeout should I set for LLM API calls?
Base it on measured P95 and the worst tail, with a separate first-token timeout. Here a 10 s first-token limit would cut Gemini 3.8 Flash's P95, and a 30 s total limit one DeepSeek free call.
Related reading
- Qwen4-Max vs Qwen3.8 Max: measured TTFT, TPOT, throughput and cache hit rate runs the same kind of probe in more depth for two models.
- Anthropic prompt caching for agents covers how to structure prompts so the cache actually hits.
Measurements: 3 Dec 2026, Asia/Shanghai, one MacBook Pro on China Telecom in Hangzhou, api.sandbase.ai via the Cloudflare LAX edge. Raw JSON, scripts and chart code are kept with this article's review notes. Prices are from SandBase model pages, OpenRouter and Vercel docs read the same day.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.


