AI gateways, rate limits, cost control, and reliability
Model calls are slow, expensive, and sometimes unavailable. This guide explains the gateway that fronts them, token-aware rate limiting, ways to cut cost, how to serve many tenants safely, and the reliability patterns that keep an AI feature working when a provider does not.
Production AI in 60 seconds
- An AI gateway is the single front door to models: authentication, limits, caching, routing, fallbacks, logging, and cost tracking.
- Limit by tokens, not only requests. One request can be ten tokens or ten thousand.
- Cost levers, in rough order of payoff: a cheaper model where it is good enough, shared-prefix caching, shorter outputs, batching offline work, and better retrieval.
- Multi-tenancy needs isolation of data, quota, and cost, so one customer cannot read, starve, or bill another.
- Reliability comes from timeouts, retries with backoff, fallback models, graceful degradation, and validated outputs.
The AI gateway
When several products call models directly, each one repeats the same work: handling keys, retrying failures, counting tokens, and logging. Changing a provider means changing every product. A gateway moves that work into one service. Products call the gateway with a stable interface, and the gateway decides which model and provider handle the call.
- Authentication and quotas: one place to issue keys, attribute usage to a team or customer, and cut off a leaked key.
- Rate limiting: protect providers and budgets, and keep one noisy user from starving the rest.
- Caching: exact and semantic caches in front of the model, described in the caching guide.
- Routing and fallback: choose a model by task and difficulty, and switch providers when one fails.
- Guardrails: shared input and output checks, so every product gets the same protections.
- Observability: a uniform trace, token count, latency, and cost for every call.
- Key hiding: products never hold the provider's secret keys.
A gateway is also a new single point of failure and an extra network hop, so run it with the same care as any critical service: several instances, health checks, and a plan for bypass in an emergency. For a small product, a library with the same functions inside your application is a reasonable first step.
Rate limiting for AI
Classic rate limiting counts requests. For model calls that is not enough, because one request may be a short question and another a hundred-page document. Providers limit on several dimensions, and your own limits should match them.
| Limit | What it counts | Protects against | Notes |
|---|---|---|---|
| Requests per minute (RPM) | Number of calls | Floods of tiny calls | Simple, but blind to size |
| Tokens per minute (TPM) | Input plus output tokens | Large prompts and long outputs | Needs an estimate before the call and a correction after |
| Concurrent requests | Calls in flight | Overloading a server or provider | Important for slow, long generations |
| Cost-based budget | Money per user, team, or day | Runaway spend | Convert tokens to money using the current price |
The output length is unknown until the call finishes, so a token limiter works in two steps: reserve an estimate before the call, using the prompt size plus the maximum output you allow, then settle the difference when the real count is known. A token bucket fits this well: the bucket refills at a steady rate, and each call takes tokens from it.
# Illustrative: limit by tokens per minute, with reserve-then-settle accounting.
import time
class TokenBucket:
def __init__(self, tokens_per_minute):
self.capacity = tokens_per_minute
self.available = tokens_per_minute
self.rate = tokens_per_minute / 60.0
self.last = time.monotonic()
def _refill(self):
now = time.monotonic()
self.available = min(self.capacity, self.available + (now - self.last) * self.rate)
self.last = now
def reserve(self, estimate):
self._refill()
if self.available < estimate:
return False # the caller should wait or return a 429 with Retry-After
self.available -= estimate
return True
def settle(self, estimate, actual):
self.available += max(0, estimate - actual) # give back what was not used
# estimate = prompt_tokens + max_output_tokens
Routing between models
Models differ widely in price and speed, and most requests do not need the largest one. Routing sends each request to the cheapest model likely to answer it well. The router can be rules (short questions go to the small model), a classifier, or a cascade: try the small model first, check the answer's confidence or validity, and escalate to the large model only if the check fails. Measure the effect on quality, not only on cost, because a cheap model that fails often is not cheap.
# Illustrative: try the cheap model, verify, escalate if the check fails.
# call_model(), looks_valid() and the model names are placeholders.
CHAIN = ['small-model', 'medium-model', 'large-model']
def answer_with_cascade(prompt, schema):
last = None
for model in CHAIN:
try:
out = call_model(model, prompt, timeout=20)
except Exception:
continue # provider error: try the next model
if looks_valid(out, schema): # schema check, groundedness check, or a confidence signal
return {'text': out, 'model': model}
last = out
return {'text': last, 'model': CHAIN[-1], 'warning': 'low confidence'}
Cost optimisation
Before optimising, measure: tokens in and out, per request, per feature, per customer. The biggest saving is almost always in a few places. The list below is in the order that usually pays off.
- Use a cheaper model where it is good enough. Classification, extraction, and routing rarely need the largest model.
- Use prompt caching. Put the stable part of the prompt first, so the provider or engine can reuse it.
- Use a semantic or exact cache for repeated questions, where the answer may be reused safely.
- Shorten outputs. Set a maximum, ask for concise formats, and use structured output instead of prose where a program reads the result.
- Trim the input. Send only the retrieved passages that matter, and compact long histories.
- Batch offline work. Many providers price asynchronous batch jobs lower than interactive calls, in exchange for a longer wait.
- Self-host smaller models when volume is high and steady, and the task is narrow.
- Improve retrieval. Better retrieval sends fewer, more relevant passages, which cuts tokens and raises quality.
# Illustrative: prices change; load them from configuration, never hard-code them.
PRICES = {'small-model': (0.15, 0.60), 'large-model': (3.00, 15.00)} # dollars per million tokens (in, out)
def cost_usd(model, input_tokens, output_tokens):
price_in, price_out = PRICES[model]
return (input_tokens * price_in + output_tokens * price_out) / 1_000_000
def record_usage(tenant, feature, model, usage):
metrics.increment('llm_cost_usd', cost_usd(model, usage.input_tokens, usage.output_tokens),
tags={'tenant': tenant, 'feature': feature, 'model': model})
Serving many tenants
A product used by many customers, called tenants, shares infrastructure among them. In AI systems the shared parts include the model endpoint, the vector index, the cache, and the logs. The design question is how much to share and how to keep tenants apart.
- Data isolation: every stored chunk, memory, and cache entry carries a tenant ID, and every query filters on it inside the store. For stricter needs, give each tenant its own index or namespace.
- Quota isolation: per-tenant token and concurrency limits, so one tenant cannot use all the capacity.
- Cost attribution: record usage per tenant, so pricing and chargeback are based on facts.
- Cache isolation: never share a cached answer across tenants unless it is built only from public data.
- Model and prompt customisation: allow per-tenant settings through configuration, with limits, not by copying code.
- Noisy neighbours: put large or batch tenants on separate queues or capacity.
Reliability: when the model or the provider fails
Model providers have outages, rate limits, and slow periods, and models sometimes return malformed output. A reliable AI feature plans for each. The patterns are familiar from distributed systems, applied to a new dependency.
- Timeouts: every call has one, set from the user's patience, not from the provider's maximum.
- Retries with exponential backoff and jitter: retry on temporary errors and rate-limit responses, wait longer each time, and add random variation so many clients do not retry at the same moment. Retry only safe or idempotent calls.
- Fallback models: if the primary model or provider fails, try a second one. Test the fallback regularly, because an untested fallback usually fails when needed.
- Circuit breaker: after repeated failures, stop calling the failing dependency for a short time instead of piling on requests.
- Graceful degradation: when everything fails, return something useful: a cached answer, a simpler non-AI path, or a clear message with a way to contact a person.
- Output validation: check the format and the content of every response before using it, and retry or fall back when the check fails.
# Illustrative: retry temporary errors, then fall back to another model.
import random, time
RETRYABLE = (TimeoutError, RateLimitError, ServerError) # placeholders for your client's exceptions
def call_with_retries(model, prompt, attempts=3, base_delay=0.5):
for attempt in range(attempts):
try:
return call_model(model, prompt, timeout=20)
except RETRYABLE:
if attempt == attempts - 1:
raise
delay = base_delay * (2 ** attempt) + random.uniform(0, 0.25) # backoff plus jitter
time.sleep(delay)
def resilient_answer(prompt):
for model in ['primary-model', 'fallback-model']:
try:
return call_with_retries(model, prompt)
except RETRYABLE:
continue
return cached_or_simple_answer(prompt) # graceful degradation
Long tasks: queues and asynchronous work
Some AI tasks take minutes: summarising a large document, processing a batch of files, running an agent with many steps. Do not hold a web request open for them. Accept the request, return a job ID at once, put the work on a queue, and let workers process it. The client checks the job's status, receives a callback, or is notified when it finishes. A queue also absorbs bursts, since workers pull jobs at the rate the models and limits allow, and it makes retries and rate limiting simpler to manage.
What to watch
| Signal | Why it matters | Typical alert |
|---|---|---|
| Tokens and cost per request, tenant, and feature | Finds runaway spend and the best saving | Cost per day above a budget |
| Time to first token and total latency | User experience | p95 above a threshold |
| Error and rate-limit rate by provider | Early sign of an outage or a quota problem | A sudden rise in 429 or 5xx |
| Fallback and cache hit rates | Shows hidden dependency on a failing path | Fallback rate above its normal level |
| Queue depth and job age | Shows batch work falling behind | Oldest job older than its limit |
| Guardrail block rate | Shows attacks or an over-strict rule | A step change in either direction |
What this means for your role
Common mistakes
Further reading
- Rate limiting, the general algorithms behind token buckets.
- Circuit breaker, the pattern for failing dependencies.
- Message queues, for long-running AI jobs.
- Types of caching in AI systems, the caches a gateway can host.
- How inference works, the capacity and cost estimation these controls protect.
A model call is a remote, costly, fallible dependency. Put one gateway in front of it, count tokens, plan for failure, and attribute every cent.