ai newsFr., 4. Dez.
EilmeldungAlibaba Releases Qwen4-35B-A3B: Open-Weight MoE Model With 1M Context

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 whatever the model does before its first visible token. In my 3 December 2026 meas

dev.toFreitag 04:26 · 04.12.12 Min. Lesezeit
Bild: dev.to

Posted on Dec 4 • Originally published at blog.sandbase.ai

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.

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.

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.

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.

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.

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.

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.

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.

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:

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 ( ) Enter fullscreen mode Exit fullscreen mode 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.

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:

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.

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.

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.

Quelle: dev.to (dev.to). Original öffnen