Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Gateway | The front door every inference request passes through before it reaches an engine. |
| Policy | The platform’s rules: who may call which model, how much, at what priority, and how it is billed. |
| Edge | The outermost layer facing the internet: TLS, firewall rules, DDoS protection. |
| AI gateway | A gateway that understands LLM APIs: token-based limits, many model providers behind one API, usage accounting. |
| ext_proc | Envoy’s external processing filter: the proxy streams a request’s headers and body to a separate service over gRPC and lets it change them or choose where the request goes. |
| Endpoint picker (EPP) | The ext_proc service of the Gateway API Inference Extension; it picks the replica (21.g, 21.h). |
| SSE | Server-Sent Events, the data: ... lines that carry a streamed response (12.p). |
| Scope | What one API key is allowed to do: which models, features and limits. |
1. What is it?#
An inference gateway is the single front door for all inference traffic. Everything that every request needs, and that has nothing to do with running the model, lives there: identity, permissions, limits, validation, model names, usage accounting, logging. The engines then know nothing about tenants, quotas or billing.
In 2026 this front door is usually two or three layers, each with a name:
CLIENT
│
▼
EDGE TLS, WAF, DDoS, coarse IP limits cloud load balancer, CDN
│
▼
AI GATEWAY API keys and scopes, token quotas, Agent Router (formerly Envoy AI
("tier one") model aliases, provider fallback, Gateway), agentgateway, LiteLLM,
usage and cost records Kong AI Gateway, cloud products
│
▼
INFERENCE GATEWAY choose the replica in a self-hosted pool Gateway API gateway + endpoint
("tier two") (load, prefix cache, LoRA, priority) picker (llm-d Router, Dynamo EPP)
│
▼
ENGINES inference vLLM, SGLang, TensorRT-LLMAgent Router’s own docs call this the two-tier gateway pattern. Small platforms collapse the layers into one process; large ones keep them apart because they change at different speeds and are owned by different teams.
Facts checked on 13 November 2026.
2. Why does it exist?#
Put this logic in the engine instead and:
- every engine process runs auth, rate limiting and billing code, competing with the engine loop for CPU (20.a);
- a policy change means restarting model servers, which takes minutes each (20.h);
- quota state is copied across N engines and drifts apart;
- the engine becomes specific to your platform and can no longer be swapped or upgraded freely.
With a gateway, policy deploys in seconds, the gateway scales on cheap CPU nodes in seconds, and there is one place to look for who called what. The gateway owns policy; engines own inference.
3. Simple analogy#
A hotel. The doorman (edge) keeps out trouble. The front desk (AI gateway) checks your booking, your loyalty tier and your credit card, and records every charge to your room. The concierge (inference gateway) knows which restaurant in the building has a free table and which one already knows your order. The kitchens (engines) only cook. Nobody asks the chef to check passports.
4. Tiny example: one request through the layers#
A client streams a chat completion with a 2,000-token prompt and 400 output tokens:
EDGE TLS terminated, IP within limits ~1 ms
AI GATEWAY key sk-…42 → tenant "acme", scope allows chat-large;
token quota: 2,000 in + 400 reserved out = OK;
alias chat-large → chat-general v1.5.0 (21.b) < 1 ms
INFERENCE GATEWAY ext_proc → EPP: tokens hashed, replica 3 holds the
prefix and has room → header
x-gateway-destination-endpoint: 10.0.3.17:8000 < 1 ms
ENGINE prefill, then 400 tokens streamed back through every
layer as SSE seconds
AI GATEWAY stream ends: record 2,000 in / 400 out for "acme";
release the concurrency slot; refund unused quotaSection 6 measures what that costs in CPU: about 25 µs to parse the request body and about 2 µs per streamed token on a laptop. The GPU work behind the same request is thousands of times larger.
5. Technical explanation#
The request pipeline#
1. Terminate TLS
2. Parse HTTP and the JSON body
3. Authenticate API key hash lookup, or JWT verified with cached keys
4. Authorise does this key's scope allow this model and these features?
5. Validate limits and parameter ranges (20.b)
6. Resolve the model name alias → model and version, canary split (21.b, 20.j)
7. Check limits requests, tokens, concurrency per tenant (23.j, 21.f)
8. Tokenise (if routing needs token IDs; do it once, pass the IDs on)
9. Choose pool and replica (21.g, 21.h)
10. Forward HTTP or gRPC to the engine
11. Stream the response back SSE framing, disconnect → abort the engine request (12.p)
12. Record usage on every exit path, including errors and disconnects
13. Release the slot and refund the unused part of the token reservationSteps 3–7 and 12–13 are the AI gateway’s job. Steps 8–9 are the inference gateway’s. Who applies the chat template and detokenises depends on the stack: with vLLM’s OpenAI-compatible server, the engine’s own frontend does both (16.e, 16.f); a gRPC-to-engine design such as SGLang Model Gateway’s gRPC mode moves them into the gateway, in Rust.
How the inference gateway picks a replica: ext_proc#
On Kubernetes the inference gateway is any Gateway API implementation that supports Envoy’s
ext_proc filter and the Gateway API Inference Extension. An HTTPRoute points at an
InferencePool (the replicas of one model) instead of a normal Service. For each request:
proxy ──headers + body──► EPP (gRPC stream, ext_proc protocol)
◄──x-gateway-destination-endpoint: 10.0.3.17:8000
(+ optional ...-fallback endpoint for a retry)
proxy ──request──► that podIf the EPP cannot pick a ready endpoint the proxy returns 503; if the request should be dropped
(flow control, 21.f), 429. The EPP needs the body, so the proxy must stream it, and the llm-d
Router supports only Envoy’s FULL_DUPLEX_STREAMED body mode. Implementations named by the
projects include Envoy Gateway, kgateway, agentgateway, Istio and GKE’s managed gateway; the
llm-d Router can also run standalone with its own Envoy, without any Gateway API controller.
Authentication and scopes#
API KEYS store only a hash; never log the key
cache key_hash → tenant, scopes, limits with a short TTL
→ the cache is what keeps serving when the key store is slow or down
(fail closed for unknown keys, keep cached ones for the TTL; 23.e)
JWT verify the signature locally against cached public keys (JWKS)
no network call per request; revocation needs short expiry
SCOPES models: [chat-large, chat-small]
features: [streaming, tools, structured_output]
max_context: 32768
tier: standard → becomes the request's priority (21.f)Scopes are under-used and valuable. Limiting what each key can reach caps both the cost a leaked key can run up and the blast radius of a bug.
What the gateway adds to streaming#
How to stream correctly (SSE framing, incremental detokenisation, stop-sequence hold-back, in-band errors, disconnect detection) is 12.p. The gateway adds two duties:
func (g *Gateway) stream(w http.ResponseWriter, r *http.Request, rc *RequestContext) {
nOut := 0
defer func() { // every exit: finished, engine error, client gone
g.usage.Record(rc.Tenant, rc.Model, rc.PromptTokens, nOut) // billing and showback
g.quota.Release(rc.Tenant, rc.ReservedTokens-nOut) // refund the unused reservation
}()
for tok := range g.engine.Stream(r.Context(), rc) { // r.Context() ends when the client leaves
nOut++
writeSSE(w, tok)
}
}- Record usage on every path. If usage is recorded only after
[DONE], aborted and failed requests are never billed or counted, and the cost figures (23.c) are wrong. - Propagate the disconnect. The gateway must cancel its upstream request when the client goes, or the engine keeps generating for nobody.
Every proxy layer must pass the stream through unbuffered (9.a). Add the served model version to
a response header (for example X-Model-Version) so client reports can be matched to deployments.
The landscape, November 2026#
LAYER PROJECT / PRODUCT NOTES
AI gateway Agent Router (was Envoy AI Envoy-based; renamed and moved to the
Gateway), v1.2.1 Agentic AI Foundation (Linux Foundation)
in September 2026; CRDs and the aigw CLI
unchanged
agentgateway v1.7.0 Rust proxy for LLM, MCP and agent-to-agent
traffic; also an Inference Extension gateway
LiteLLM Python proxy and SDK; many providers behind
one OpenAI-compatible API; budgets, keys
Kong AI Gateway, cloud AI commercial or managed
gateways
Inference gateway llm-d Router v1.0.0 the full endpoint picker (21.j)
Dynamo EPP Dynamo's router as an endpoint picker (21.j)
SGLang Model Gateway SGLang's router; cache-aware routing, P/D,
rate limiting, circuit breakers
Gateway API Envoy Gateway, kgateway kgateway v2.5 handed its agentgateway
proxies v2.5.1, Istio, GKE Gateway control plane to the agentgateway project6. Under the hood: what a gateway spends CPU on#
This program measures the three costs that scale with traffic: parsing a request body, looking up an API key, and framing and writing one streamed token to a real TCP socket.
// gwcost.go — what does an inference gateway spend CPU on? Measure three per-request and
// per-token costs with testing.Benchmark, then size a gateway from them.
package main
import (
"bufio"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net"
"strings"
"testing"
)
type message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type chatRequest struct {
Model string `json:"model"`
Messages []message `json:"messages"`
MaxTokens int `json:"max_tokens"`
Stream bool `json:"stream"`
}
type delta struct {
Content string `json:"content"`
}
type choice struct {
Index int `json:"index"`
Delta delta `json:"delta"`
}
type chunk struct { // one OpenAI-style chat.completion.chunk
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []choice `json:"choices"`
}
func nsPerOp(f func(b *testing.B)) float64 {
r := testing.Benchmark(f)
return float64(r.T.Nanoseconds()) / float64(r.N)
}
func main() {
// 1. Parse a request body with a ~2,000-token prompt (about 8,000 characters).
body, _ := json.Marshal(chatRequest{
Model: "chat-large",
Messages: []message{{"system", strings.Repeat("You are helpful. ", 100)}, {"user", strings.Repeat("word ", 1300)}},
MaxTokens: 400, Stream: true,
})
parse := nsPerOp(func(b *testing.B) {
for range b.N {
var req chatRequest
if err := json.Unmarshal(body, &req); err != nil {
panic(err)
}
}
})
// 2. Authenticate an API key: hash it, look the hash up in an in-memory cache.
keys := map[[32]byte]string{}
for i := range 100000 {
keys[sha256.Sum256(fmt.Appendf(nil, "sk-%d", i))] = "tenant"
}
key := []byte("sk-4242")
auth := nsPerOp(func(b *testing.B) {
for range b.N {
if keys[sha256.Sum256(key)] == "" {
panic("unknown key")
}
}
})
// 3. Frame one streamed token: build the chunk, encode it, write "data: ...\n\n" to memory.
w := bufio.NewWriter(io.Discard)
c := chunk{ID: "chatcmpl-123", Object: "chat.completion.chunk", Created: 1763000000,
Model: "chat-large", Choices: []choice{{Delta: delta{" token"}}}}
frame := nsPerOp(func(b *testing.B) {
for range b.N {
buf, _ := json.Marshal(c)
w.WriteString("data: ")
w.Write(buf)
w.WriteString("\n\n")
w.Flush()
}
})
// 4. The same, written and flushed to a real loopback TCP socket: one write syscall per token.
ln, _ := net.Listen("tcp", "127.0.0.1:0")
go func() {
conn, _ := ln.Accept()
io.Copy(io.Discard, conn) // the "client" reads everything
}()
conn, _ := net.Dial("tcp", ln.Addr().String())
sw := bufio.NewWriter(conn)
frameSock := nsPerOp(func(b *testing.B) {
for range b.N {
buf, _ := json.Marshal(c)
sw.WriteString("data: ")
sw.Write(buf)
sw.WriteString("\n\n")
sw.Flush()
}
})
fmt.Printf("parse 8 KB request body %6.1f µs\n", parse/1000)
fmt.Printf("API key hash + lookup %6.2f µs\n", auth/1000)
fmt.Printf("frame one SSE token %6.2f µs (encode only)\n", frame/1000)
fmt.Printf(" ... and write it %6.2f µs (flushed to a TCP socket, no TLS)\n", frameSock/1000)
const reqPerSec, outTokens = 1000.0, 400.0
perReq := reqPerSec * (parse + auth) / 1e9
perTok := reqPerSec * outTokens * frameSock / 1e9
fmt.Printf("\nat %.0f req/s with %.0f output tokens each:\n", reqPerSec, outTokens)
fmt.Printf(" per-request work %.2f cores\n", perReq)
fmt.Printf(" per-token streaming %.2f cores (%.0f tokens/s)\n", perTok, reqPerSec*outTokens)
}Output (Go 1.25 on an Apple M-series laptop; your numbers will differ):
parse 8 KB request body 25.0 µs
API key hash + lookup 0.05 µs
frame one SSE token 0.20 µs (encode only)
... and write it 1.91 µs (flushed to a TCP socket, no TLS)
at 1000 req/s with 400 output tokens each:
per-request work 0.03 cores
per-token streaming 0.76 cores (400000 tokens/s)What it shows:
- Per-token streaming dominates, and most of it is the write system call on every flush, not the JSON. At 400,000 tokens per second that is under one core here; TLS encryption, HTTP/2 framing, logging and detokenisation in the gateway add to it, so plan for several times this.
- Per-request work is small next to it, unless the gateway also tokenises long prompts. Measure your tokenizer on your real prompt lengths before deciding where to tokenise.
- The gateway is cheap compared to the GPUs behind it. A fleet streaming 400,000 tokens per second needs a lot of GPUs and a handful of gateway cores. That is why moving work out of the engines and into the gateway is almost always right.
7. Performance implications#
- Gateway latency is paid by every request, so keep the per-request path in memory: cached auth, cached routing tables, no database calls. A 20 ms gateway erases a prefix-cache hit on a short prompt.
- Scale it on CPU and connection count, not on requests per second: long streams hold connections open for minutes.
- Stateless pods scale in seconds (with cached auth and routing state); engines take minutes (20.g). Give the gateway its own autoscaler and generous headroom, because when it falls over, every model is down.
- Token-based limits need counting, which needs the token counts the engine returns in the
final
usagechunk; request a final usage chunk for streams (stream_options.include_usagein the OpenAI API) rather than re-tokenising the output.
8. Production implications#
- Adopt, then extend. An AI gateway (Agent Router, agentgateway, LiteLLM or a commercial one) plus a Gateway API inference gateway with an endpoint picker covers most needs. Write your own only where your policy is unusual, ideally as a plugin or an ext_proc filter.
- Keep the edge generic. TLS, WAF and IP limits belong in the cloud or CDN layer; token quotas do not.
- Cache auth so the key store is never on the critical path.
- Limit by tokens and concurrency, not only requests (23.j).
- Record usage in a
defer/finallyand test the abort path explicitly. - Propagate disconnects to the engine.
- Disable buffering at every layer and test the whole path from a real client (9.a).
- Run the gateway highly available, in more than one zone, and treat its config like code (reviewed, versioned, rolled out gradually, with last-known-good; 21.a).
9. Common mistakes#
- Policy in the engine. Slow to change and competes with the engine loop.
- Proxy buffering somewhere on the path. Streaming turns into one late response (9.a, 22.k).
- An auth-store lookup on every request. Latency and a hard dependency.
- Request-based rate limiting for requests that differ 1,000x in cost (23.j).
- No disconnect propagation. Engines generate tokens nobody reads.
- Usage recorded only on success. Aborted and failed requests disappear from billing.
- A generic API gateway as the inference gateway. It cannot count tokens or pick replicas by cache and load.
- One gateway instance or one zone. The front door is the single point of failure for every model.
10. Hands-on exercise#
- Run
gwcost.go. Make the streamed token text 10x longer and the prompt 4x longer. Which cost moves, and why? - Add TLS. Wrap the socket in
crypto/tlswith a self-signed certificate and re-measure the per-token cost. - Build the pipeline. Implement section 5’s steps 1–13 in front of a vLLM server (this is
Project 12 in the Projects section). Test it with the official
openaiclient library. - Kill the key store. With a 60 s auth cache, stop the store and confirm cached keys keep working, unknown keys are refused, and both are logged.
- Abort mid-stream. Start a 4,096-token request, disconnect after 100 tokens, and check that the engine stopped, usage says 100, and the quota got the rest back.
- On Kubernetes. Put two vLLM pods in an
InferencePoolbehind a Gateway API implementation with the llm-d Router, and watchx-gateway-destination-endpointin the proxy’s access log.
11. Interview questions#
- What belongs in a gateway rather than in the engine, and why?
- What are the layers between a client and an engine, and what does each own?
- How does an Envoy-based gateway let an endpoint picker choose the replica?
- What dominates a gateway’s CPU cost, and how would you size it?
- Why cache auth lookups, and what should happen when the auth store is down?
- Why must usage be recorded in a
finally/defer? - Why is a generic API gateway not enough for LLM traffic?
12. Further reading#
Checked on 13 November 2026.