The threat model for an inference endpoint
Four adversary types matter and they need different controls. The unauthenticated internet wants to find an open port, a default key, or a proxy that forwards anything. The authenticated tenant wants to exceed its quota, reach another tenant's data, or use your GPUs for free inference on its own product. The insider or compromised application holds a valid key and is the hardest case, because every control that trusts the key is now bypassed. The supply chain wants a malicious image, a tampered weight file, or a dependency that executes at import time.
The assets are equally specific. GPU capacity is the one people forget: a single long-context request can pin tens of gigabytes of KV cache and starve every other user, so availability is a security property here in a way it is not for a stateless CRUD API. Beyond compute, the endpoint holds model weights, prompt and completion logs that often contain regulated data, upstream credentials used by tools, and the integrity of every response your product ships.
Start with the network, not the model
- No public address on the inference server: it listens on a private interface and is reachable only from the gateway, with a security group or NetworkPolicy that names the gateway's identity rather than a CIDR.
- One ingress path: a reverse proxy or API gateway terminates TLS, enforces body limits and timeouts, and is the only component with a public listener.
- Deny egress by default: the inference process needs no outbound internet, and the tool sandbox needs an explicit allowlist, because both are prompt-injection targets.
- Block link-local metadata: drop traffic to 169.254.169.254 and the IPv6 equivalent so a fetch tool or a malicious model file cannot reach instance credentials.
- Mutual TLS between gateway and inference: it removes the class of attack where anything that reaches the port is treated as trusted, and it survives a shared cluster.
- Read-only root filesystem and a non-root user in the container, with the model mounted read-only and no writable path except a scratch volume with a size limit.
Authentication: a gateway, not a flag
Most inference servers ship a single static API key flag, and it is exactly that: one shared secret, compared in constant time, with no notion of tenants, scopes, expiry or revocation beyond restarting the process. That is acceptable for a laptop and unacceptable for anything multi-tenant. Put a gateway in front and let the inference server accept traffic only from the gateway over mTLS, so the static key becomes an internal implementation detail rather than the product's authentication system.
The gateway should support two identity paths. Machines authenticate with scoped API keys; humans authenticate through OIDC so that access follows your existing joiner-mover-leaver process and MFA policy. Keys are generated once, shown once, stored as a hash with a short lookup prefix, and carry metadata: tenant, allowed models, requests per minute, tokens per minute, monthly budget, expiry, and the environment they are valid in. That metadata is the authorisation model, and it should be editable without redeploying the model server.
Issue keys per application and per environment, never one key shared across staging and production or across two services that happen to be written by the same team. A key that appears in a mobile binary or a browser bundle is public; if your product needs to call the API from a client you do not control, proxy it through your own backend and keep the key server-side.
Rotation has to be boring. Support overlapping validity so a new key can be deployed before the old one is revoked, publish a maximum lifetime, and alert on keys that have not rotated.
Authorisation: scope every request to a tenant
Authenticated is not authorised. The gateway should resolve the tenant from the credential and inject it into the request context, and every downstream component should read it from there rather than from a field the caller supplied. This one rule closes the most common cross-tenant bug in LLM products, where the retriever filters on a tenant_id that arrives in the JSON body and is trivially edited.
Enforce a model allowlist per key. A key issued for a small classification model should not be able to call the 70B model, both because the cost difference is two orders of magnitude and because the larger model may have different data handling. If you serve per-tenant adapters or LoRA modules, bind the adapter to the tenant at the gateway and reject requests that name an adapter the key does not own. Keep an explicit deny for administrative routes, and make sure the inference server's own docs and metrics endpoints are not reachable from the same listener as the API.
Rate limiting that counts tokens, not requests
Requests per second is the wrong unit for language models. Cost and latency scale with tokens: prefill work grows with input length, decode work grows with output length, and KV cache occupancy grows with the context you keep alive. Limits therefore need at least four dimensions: requests per minute, input tokens per minute, output tokens per minute, and concurrent sequences.
Implement admission as a reservation rather than a post-hoc count. Tokenize the prompt (or estimate with the model's tokenizer) to reserve input tokens, reserve the requested max_tokens for output, and settle the difference when the request finishes. Without reservation, a burst of long requests all pass the check before any of them completes, and the limit is decorative. A token bucket per tenant with a small burst allowance and a hard ceiling on concurrency is the standard shape.
Return 429 with a Retry-After header and a machine-readable error body, and make sure the SDK or client library backs off rather than retrying immediately. On the server side, protect the whole cluster with a global concurrency cap sized to the GPU's actual batch capacity, and keep a separate reserved pool for interactive traffic so a batch job cannot make the chat product unusable. If you run multiple replicas, the counters live in a shared store such as Redis with atomic operations, not in each process's memory, or the effective limit is the configured limit multiplied by the replica count.
Caps that stop one request from owning the cluster
- Maximum context length: set the server's max model length to the product requirement, not the architecture's theoretical maximum, because a larger window is a larger attack surface for both memory and injection.
- Maximum output tokens: cap it per route, for example 1,024 for classification, 4,096 for chat, and require an explicit entitlement for anything above.
- Body size limit: 1 MB at the proxy is generous for text and blocks the trivial memory exhaustion attempt; count base64 images and attachments against a separate, smaller budget.
- Streaming timeouts: set a time-to-first-token limit and an inter-token limit, not a single total timeout, so a slow-loris style stream cannot hold a connection and a KV slot indefinitely.
- Cancellation on disconnect: propagate client disconnects to the inference engine so abandoned streams free their cache instead of generating into the void.
- Tool and agent loops: cap iterations, total tool calls, wall-clock time and cumulative tokens per user turn, and enforce the cap in the orchestrator rather than in the prompt.
- Sampling parameters: constrain n, best_of, logprobs and stop-sequence counts, since each multiplies work in ways a request-count limit does not see.
Guardrails in the request path
Guardrails are filters and classifiers around the model, and their value depends entirely on where they sit. Input filtering catches known-bad categories, prompt-injection patterns and oversized or malformed content before you pay for prefill. Output filtering catches data leakage, unsafe content and malformed structured output before it reaches a user or a downstream system. PII detection can redact before logging or before sending text to a third-party tool. None of these are security boundaries on their own, but each is a useful signal and a useful speed bump.
Decide fail-open versus fail-closed per route, and write the decision down. A moderation timeout should probably fail closed on a public chat endpoint and fail open on an internal summarisation job where availability matters more. Instrument whichever you choose: a guardrail that silently fails open for a week is worse than none, because it creates false assurance in the security review.
Secrets, weights and the supply chain
The inference process should hold almost nothing. It needs the weights, a place to write logs, and a certificate. It should not have cloud credentials, database passwords, or the Hugging Face token used to download the model at build time. If tools need credentials, a broker injects them into the tool process after authorisation, and the model server never sees them. Mount secrets as files with restrictive permissions rather than baking them into images or environment variables that end up in a crash dump.
Pin everything by digest. Container images should be referenced by sha256 digest, verified with cosign or an equivalent signature check in admission control, and accompanied by an SBOM. Model weights should be fetched from a private registry you control, verified against a recorded checksum, and stored in safetensors rather than pickle-based formats, because a pickle file is arbitrary code execution with a .bin extension. Record the model hash, the tokenizer hash, the chat template and the inference server version in a deployment manifest, and treat any change to that manifest as a release.
Logging, audit and the privacy trap
Log the metadata of every request: timestamp, request id, tenant, key id, model, route, input and output token counts, latency to first token, total latency, status code and guardrail verdicts. That is enough to detect abuse, attribute cost and debug production without storing the content of what users typed. If you must store prompts and completions, make it opt-in per tenant, encrypt at rest with a key the application does not hold, set a retention period measured in days rather than months, and restrict access to a named group with audited queries.
The privacy trap is easy to fall into because debugging wants full prompts. A common compromise is to store a redacted version by default and the full text only for a sampled percentage, with a documented reason and an automatic deletion job. Hash user identifiers rather than storing emails in the log line, and keep the mapping in a separate access-controlled store. If your observability vendor receives prompts, that vendor is a subprocessor and belongs in your data processing agreement and your data map.
Alert on shapes rather than content: spikes in 401s, a single key producing most of the 429s, token spend deviating from the trailing baseline, unusually high max_tokens values, repeated identical prompts that suggest scraping or cache-busting, and request patterns that hit the context ceiling repeatedly.
Cost controls and caching
Give every key a budget and decide in advance whether exceeding it throttles or blocks. A hard stop protects the invoice and creates an outage for the tenant; a soft limit with alerting protects the relationship and risks the invoice. Most operators want a soft limit at 80 percent and a hard limit at 100 percent, with an override process that a human can invoke. Report spend per tenant, per model and per route daily, because the first sign of a compromised key is usually a cost anomaly rather than a security alert.
Caching is a cost control with security implications. Exact-match cache keys must include the tenant, the model version and every parameter that affects output; a key on the prompt alone will serve one tenant's answer to another. Prefix caching is scoped to a request but still leaves data in GPU memory, so it is not tenant isolation. Treat a semantic cache as a data store with the same access controls as the vector index.
Tests that prove the controls work
- Unauthenticated probe: every route returns 401 without a credential, including metrics, docs and health endpoints that someone helpfully exposed.
- Cross-tenant probe: a valid key for tenant A cannot read tenant B's documents or adapter, and editing a tenant_id in the body changes nothing.
- Quota probe: a burst of concurrent long requests is rejected at the configured concurrency, not accepted and then timed out.
- Body probe: oversized payloads return 413 and over-length prompts return 400, neither reaching the model.
- Egress probe: a tool configured with a URL pointing at the metadata service fails, and DNS resolution outside the allowlist fails.
- Injection smoke test: a document containing an instruction to call an unauthorised tool produces a blocked action and an audit entry, not a successful call.
The trade-offs worth stating out loud
Every control here costs something. Token reservation adds a tokenization pass and some latency. Output moderation adds hundreds of milliseconds on a streaming path where users notice. Full prompt logging makes incidents easy to investigate and turns your log store into a regulated data repository. Fail-closed guardrails protect compliance and manufacture outages when a classifier has a bad day.
The gateway itself is a single point of failure and a high-value target, so run it highly available, keep its configuration in version control, and test the restore path. If the shared rate-limit store is unavailable, decide now whether the gateway fails open and risks the GPU or fails closed and risks availability; both are defensible, and neither is defensible if it is discovered during the incident.
The end state to aim for is a deployment where the model server is a private, replaceable compute component with no ambient authority; the gateway holds identity, quota and policy; the guardrails are versioned alongside the prompt; and the logs are rich in metadata and poor in content. That architecture survives a compromised key, a malicious document and a bad model release, which is more than can be said for a public port with a static key.
Key points
- Treat the inference server as private compute: no public listener, no egress, no credentials, mTLS from the gateway only.
- Use a gateway for identity and policy, because a single static API key is not a multi-tenancy model.
- Resolve tenant and entitlements from the credential, never from the request body, and allowlist models per key.
- Limit requests, input tokens, output tokens and concurrency together, with reservation-based admission and a shared counter store.
- Keep guardrails outside the model, version them, and choose fail-open or fail-closed per route in writing.