Gateways and Routing

Topics Covered

The Role of a Gateway

What sits between users and engines

Why LLM traffic needs special handling

Model names as an abstraction

Usage tracking and attribution

Policy enforcement

Build or adopt

Where the gateway runs

Streaming through the gateway

Multi provider abstraction

Security at the edge

Observability from the gateway

A gateway in a small team

Configuration as data

An engine serves one model on a set of GPUs. Real products need much more around it: authentication, quotas, routing across many replicas and models, retries, logging and cost tracking. The gateway is the layer that provides these. This lesson covers what an LLM gateway does, how load balancing differs for LLM traffic, how cache aware routing raises efficiency, how rate limits and fairness protect shared capacity, and how retries, fallbacks and timeouts keep the service reliable.

What sits between users and engines

A request from an application usually passes through several layers before reaching an engine. An API gateway terminates TLS, authenticates the caller and applies coarse limits. An LLM specific gateway or router understands models and tokens: it maps the requested model name to a pool of replicas, counts tokens for quotas and billing, applies per customer limits, picks a replica, retries failures and records usage. Some organizations combine these into one service; others use a general API gateway plus a dedicated LLM router. Either way, the functions are the same.

The gateway checks who is calling, whether they have quota and which model they want, then sends the request to one replica.

Why LLM traffic needs special handling

Generic API gateways were built for requests that take milliseconds and cost roughly the same. LLM requests break both assumptions. A request may stream for a minute, so connection handling and timeouts must allow long lived responses. Requests vary in cost by orders of magnitude depending on prompt and output length, so counting requests is a poor proxy for load or spend; counting tokens is needed. Replicas hold state, the KV cache, that makes some replicas better choices than others for a given request. And upstream capacity is expensive and scarce, so protecting it with limits matters more than for cheap services.

Model names as an abstraction

Applications typically ask for a model by name, such as a chat model alias, rather than by replica address. The gateway maps that name to the current deployment, which may be a pool of self hosted replicas, a managed provider, or a mix. This indirection lets the platform team swap model versions, move traffic between providers, run canaries and shift load without changing application code. It also lets the gateway enforce which teams may use which models, which matters when some models are expensive or carry special data handling terms.

Usage tracking and attribution

Because cost scales with tokens, the gateway is the natural place to record usage: input tokens, cached input tokens, output tokens, model, caller, team, feature and latency for every request. These records drive internal chargeback, customer billing, budget alerts and capacity planning. Accurate attribution often reveals surprises, such as a single feature with long prompts consuming most of the spend, or a retry loop in a client multiplying costs. Without a central record, such patterns stay hidden across many services calling models directly.

Policy enforcement

Gateways also enforce policies that individual applications might forget. These include maximum prompt and output lengths, allowed models per team, content filtering on inputs and outputs where required, removal or masking of sensitive data before it reaches external providers, and logging rules. Centralizing policy in the gateway makes it consistent across services and easier to audit, though it also makes the gateway a critical component that must be highly available and fast, adding as little latency as possible.

Build or adopt

Many open source and commercial gateways exist, offering OpenAI compatible endpoints, provider routing, rate limiting, caching and usage tracking out of the box. Some teams adopt one; others build a thin gateway tailored to their platform, often on top of a general proxy. The choice depends on how much custom routing logic is needed, such as cache aware or cost aware routing, and how well an existing gateway integrates with the organization identity, billing and observability systems. Whatever is chosen, the gateway sits on the hot path of every request, so its latency and reliability deserve the same care as the engines behind it.

Where the gateway runs

Gateways usually run as a horizontally scaled stateless service in front of the engine pools, with shared state such as rate limit counters and routing indexes held in a fast store. Keeping the gateway stateless lets it scale with request volume independently of GPUs and survive the loss of any single instance. Because it adds a network hop to every request, it should run close to the engines, in the same region and ideally the same cluster, and its own processing time should be a small fraction of TTFT. A gateway that adds fifty milliseconds to every call can undo much of the effort spent tuning engines.

Streaming through the gateway

Most LLM responses stream as server sent events, a sequence of small chunks over one long HTTP response. The gateway must pass these chunks through as they arrive rather than buffering the full response, or users lose the benefit of streaming. It also needs to count output tokens as they pass, for usage tracking and limit refunds, and to handle the client disconnecting mid stream by cancelling the upstream request promptly, so the engine stops generating tokens nobody will read. Missing cancellation is a common source of wasted GPU time, especially for chat interfaces where users often close a tab or press stop.

The user closes the tab. The gateway sees the disconnect and cancels upstream, so the engine stops spending GPU time on unread tokens.

Multi provider abstraction

Applications increasingly use several model providers and self hosted models at once. Each provider has slightly different request formats, error codes, rate limit headers and streaming details. A gateway that presents one consistent API and translates to each backend frees application teams from writing provider specific code, and lets the platform move traffic between providers centrally. The abstraction is never perfect, because providers differ in features such as tool calling and caching, so the gateway should expose capabilities explicitly rather than pretend every backend is identical.

Security at the edge

The gateway is the main defense for expensive backends. It should validate request sizes and parameters before they reach engines, reject malformed or oversized inputs, and keep engine endpoints unreachable from outside the private network. API keys should be scoped to teams or applications with least privilege, rotated regularly and never embedded in client side code. For external providers, the gateway can hold provider credentials centrally so that application services never see them, reducing the chance of leaked keys and making rotation a single change.

Observability from the gateway

Because every request passes through it, the gateway gives the clearest end to end view of the service. It can record the full latency a caller experienced, broken down into gateway processing, queueing at the router, time to first token and generation time, along with which replica or provider served the request and whether retries or fallbacks occurred. Engine metrics show what happens inside each replica, but only the gateway sees the whole path. Dashboards built from gateway records answer questions such as which callers see the worst latency, which models fail most often and how much traffic is served by fallbacks, and they are usually the first place on call engineers look when users report problems.

A gateway in a small team

Not every deployment needs a sophisticated gateway on day one. A small team calling one provider can start with a thin internal wrapper that holds credentials, logs usage per feature and applies a simple timeout and retry policy. As traffic, providers and teams grow, the same wrapper can evolve into a full gateway with routing, limits and fallbacks. Starting with a single choke point early is valuable even when it does little, because adding one later means finding and changing every direct call scattered through the codebase.

Configuration as data

Routing rules, model aliases, limits and fallback chains change often. Storing them as versioned configuration that the gateway reloads without a restart lets operators shift traffic, adjust limits or add a fallback within minutes, while keeping a reviewed history of every change.

Count tokens, not requests

LLM requests vary in cost by orders of magnitude. Quotas, billing, load balancing and capacity planning all work better when they measure tokens rather than request counts.