EXPLAINER16 min read

Rust AI API Gateway: Lessons from Anthropic

A practical guide to when Rust helps an AI gateway, what belongs on its hot path and how to prove a migration is safe.

P
PADISO teamPublished 13 Nov 2026

The case for a rust ai api gateway is strongest when the gateway itself is consuming meaningful CPU or memory, or adding measurable delay to streamed responses. Rust can reduce that runtime overhead, but it cannot make an upstream model generate tokens faster, and a rewrite is only worthwhile if production measurements justify it. We explain the architecture, the trade-offs and a safer way to migrate, using the Anthropic API migration as a reported example.

What is an AI API gateway, and why does its latency matter?

An API gateway is the service between an application and the systems it calls. An AI gateway takes requests from applications or agents, applies shared rules, then forwards them to one or more model providers. It can handle authentication, model selection, rate limits, usage records, safety checks and streaming responses.

Without a gateway, each product team may implement those tasks separately. That can make provider changes, security reviews and cost reporting harder. A gateway gives the organisation a place to apply common controls. It also adds another service to the request path, so its overhead must be measured rather than assumed to be negligible.

A typical request travels from a client SDK to the gateway, then to a provider such as Anthropic, OpenAI or a cloud-hosted model. The provider returns a response, often as a stream of small events. The gateway forwards those events to the client while doing any required checks and recording usage.

The model usually accounts for the largest share of request time, but the gateway still matters. Delays in authentication, parsing, routing, queueing or stream forwarding can add to the time a user waits. At high concurrency, the gateway can also become a capacity bottleneck even if its delay on one request looks small.

Before changing languages, measure the part you own. AI strategy and solutioning can help frame this as a cost, latency and operational decision, rather than a language preference.

What do TTFT and inter-token latency mean?

Time to first token, usually shortened to TTFT, is the time between sending a prompt and receiving the first generated output. It includes more than model computation. Network travel, gateway authentication, request validation, routing and the model's initial processing can all contribute.

Inter-token latency, sometimes called time per output token, is the gap between successive pieces of generated output. In a streaming response, the client sees a sequence of events rather than waiting for one complete answer. A gateway that adds buffering or spends too long processing each event can make that stream feel uneven.

These measures answer different questions. A high TTFT may come from the gateway, the network or the provider. Slow or irregular streaming may point to event handling, upstream generation or buffering. Measure each segment before attributing the cause. Engineering research on LLM inference latency highlights the value of isolating these distinct processing stages.

Most importantly, Rust does not reduce the model's inference time by itself. It may reduce the time spent by your gateway before the first token and between stream events. That distinction should be explicit in any performance claim.

Why can a Python gateway become a bottleneck?

Python is widely used for web services and is a sensible choice for many gateways. Fast development, familiar libraries and a large ecosystem can matter more than raw efficiency. The issue arises when a service handles a large number of concurrent connections and performs frequent work on every small stream event.

A Python service can parse JSON, call an upstream provider and forward a stream effectively. Under heavy load, however, it must continually create and release objects, move data between libraries and schedule work on its event loop. That work competes for processor time with the request handling itself.

The Global Interpreter Lock, or GIL, is a Python runtime mechanism that limits multiple threads from executing Python bytecode at the same time within one interpreter. It does not mean Python cannot serve concurrent network requests. Asynchronous I/O and multiple processes can handle many waiting connections. It does mean CPU-heavy Python work does not automatically scale across threads in one process.

An event loop is the scheduler that runs asynchronous tasks while network operations wait. It can keep many connections active without allocating one operating-system thread per connection. But if the loop spends too long parsing or serialising event data, other connections wait for their turn. That delay is often described as event-loop lag or starvation.

A streaming gateway has a lot of small operations. Each incoming event may need to be decoded, inspected, accounted for and forwarded. This is different from a service that receives one request, performs a short task and returns one response. At enough connections and events, repeated allocation and serialisation can consume substantial CPU and memory.

Python's garbage collector manages memory occupied by objects that are no longer needed. Frequent short-lived objects are not automatically a problem, but high-volume object creation can add overhead. A garbage collection pause or processor contention may also affect tail latency, which means the slowest portion of requests, often tracked as p95 or p99. Those measures describe the time below which 95% or 99% of requests complete.

This is not a claim that Python is categorically unsuitable. It is a reason to measure its cost in your specific workload. A gateway forwarding modest traffic with low CPU use may have no meaningful need to change languages.

Why does streaming change the calculation?

In a non-streaming API, the gateway can receive a full response and return it as one payload. In a streaming API, it must keep a connection open and relay chunks as they arrive. That increases the number of active connections and the frequency of small writes.

A Server-Sent Events stream, or SSE, is a standard way for a server to send a sequence of named or plain-text events to a client over an HTTP connection. Many model APIs use an SSE-like format for streaming. The gateway must preserve event boundaries, handle disconnects and avoid adding unnecessary buffering.

For an agent, a delay between events can have a knock-on effect. The agent may be waiting for a tool call or deciding what to do next. But a slow stream could still originate upstream. Record timestamps at the client, gateway and provider boundary so the team can distinguish those causes.

What did Anthropic's Rust migration report show?

Anthropic's engineering post, published on 25 November 2026, describes a migration of its Messages API from Python to Rust. According to the post, traffic had grown substantially since the API began as a lightweight request forwarder. The service had taken on more work, including validation, prompt preparation, safety checks, stream parsing and usage accounting.

Anthropic reported a roughly 70% reduction in CPU use per request and a reduction of more than 80% in memory footprint after the migration. It also reported about a 20% improvement in median TTFT for Claude Code over the stated measurement period. These are results from Anthropic's own system and workload, not a guarantee of what another company's gateway will achieve. See Anthropic's migration account for its scope and methodology.

The important lesson is not simply that Rust is faster. The migration shifted a growing, latency-sensitive request path into a runtime designed for efficient concurrent work. It also removed repeated movement between Python and native code by keeping the request and stream processing in one language.

That distinction matters because a partial rewrite can leave the expensive boundaries intact. Anthropic reported that an early attempt to move a parser into Rust through a Python extension reduced CPU use by only 8% to 10%. In that design, stream data crossed the language boundary multiple times per token. Converting and transferring small pieces of data can consume some of the benefit gained by faster native code.

A foreign function interface, or FFI, is the mechanism that lets code in one language call code written in another. FFIs are useful, especially for bounded tasks such as processing a whole document or running a batch calculation. They are less attractive when an application repeatedly crosses the boundary for tiny pieces of a hot stream.

The practical rule is to profile the end-to-end path. If JSON parsing accounts for a large share of CPU, a native parser might help. If every event still has to be copied into and out of Python objects, the surrounding design may dominate the savings. Benchmark the complete request and stream, not a single function in isolation.

How should you read third-party gateway benchmarks?

A July 2026 LiteLLM benchmark reported a p99 added latency of 257.7 milliseconds for its Python proxy and 0.7 milliseconds for its Rust gateway beta. It also reported peak worker memory of 329.5 MB versus 21.8 MB and different infrastructure-cost estimates per million requests.

Those figures are a useful signal that gateway implementation can affect resource use and overhead. They are not a universal prediction. Results depend on the test setup, versions, hardware, request shape, concurrency, streaming behaviour and what the benchmark counts as gateway-added latency. The reported p99 values should not be compared to provider inference time or treated as a forecast for your production environment. Independent AI gateway benchmarks on latency and throughput also demonstrate how results vary across concurrency profiles.

Use benchmark results to decide what to test, not what to promise. Reproduce the relevant workload with your own routing rules, authentication, payload sizes, provider connections and concurrency. Measure both latency and cost under a load profile that resembles actual traffic.

What belongs in a Rust AI API gateway?

Rust is a compiled systems language. A compiler turns the source code into a native executable before it runs. Rust's memory-safety rules help developers manage access to memory without a garbage collector. The language does not remove all runtime costs or make bugs impossible, but it offers tools for building efficient services with controlled memory ownership.

A common Rust web-service stack combines Tokio, an asynchronous runtime, with Axum, a web framework. An asynchronous runtime schedules tasks that are waiting on network or other I/O. Axum provides routes and request handling. Tower supplies composable middleware layers, which are reusable steps such as timeouts, authentication or request tracing.

A gateway design should separate the major responsibilities:

  1. Ingress and request parsing. Accept HTTPS requests, enforce body limits, parse the request and reject malformed input early.
  2. Identity and policy. Authenticate the caller, identify its tenant and apply permissions. A tenant is a customer, business unit or application whose access and usage are managed separately.
  3. Quota and rate controls. Apply request limits and, where appropriate, token or spend limits. A rate limit restricts how often a client can call the service over a period.
  4. Routing. Resolve a model alias to an approved provider and model. Apply a fallback only when the product and compliance rules allow it.
  5. Upstream connection management. Reuse provider connections where supported, set timeouts and handle provider errors without losing the original context.
  6. Streaming. Forward events promptly, preserve framing and detect client or provider disconnects.
  7. Accounting and observability. Record request IDs, selected route, timings, status and usage data needed for support, billing and capacity planning.

A model alias such as support-fast can let an application request a capability without hard-coding a provider model name. The gateway can map that alias to an approved route. Keep this mapping explicit and versioned. Silent changes to model behaviour can affect quality, cost and contractual expectations.

Zero-copy means passing references to existing data buffers instead of repeatedly making new copies. Rust libraries such as bytes can help manage byte buffers efficiently. Zero-copy is not magic: it only helps where the data can safely remain in its existing representation. If the gateway must inspect and transform content, some processing and allocation remain necessary.

A Rust implementation might use Axum and Tower for request routing and middleware, Tokio for asynchronous work, and an HTTP client such as reqwest for upstream calls. These are design options, not a required product recipe. Choose libraries based on current maintenance, security posture, operational familiarity and fit with your provider APIs.

What should happen on the streaming hot path?

The hot path is the part of the system executed for nearly every request or event. In a gateway, it typically includes request checks, route selection, upstream writes and stream forwarding. Keep expensive or blocking work off that path where possible.

For each stream, the gateway should aim to:

  • Preserve event boundaries and ordering.
  • Forward output as soon as policy allows, without collecting the entire response first.
  • Apply clear limits to payload size, connection duration and buffering.
  • Handle cancellation when either side closes the connection.
  • Record timing and byte counts without logging sensitive prompt or response content by default.
  • Make token and cost accounting accurate enough for the intended business use.

Some controls need to inspect content. For example, a safety check may require examining the prompt or output. That requirement should be designed deliberately, because buffering an entire response can add latency and memory use. Decide whether a control can run before the stream, on each event, asynchronously after delivery, or in a separate workflow. The answer depends on risk and the consequences of releasing content before review.

Avoid promising that the gateway has no per-token overhead. Every forwarded event requires some work. The objective is to keep the added work small, bounded and observable, while preserving the controls the business needs.

How do you migrate without risking production traffic?

A safe migration is a verification project before it is a rewrite project. The main risk is not whether Rust can compile or serve a request. It is whether the new implementation handles the real range of inputs, provider behaviour, errors and edge cases in the same way as the existing service. As engineering analyses show, the real work in AI-driven migrations lives in establishing that verification discipline.

Anthropic described a gap between its integration tests and production traffic. Its post says that early test coverage appeared strong, but those tests represented only a fraction of production inputs. The team later reached 99.6% parity in its stated checks. The exact percentages are specific to that migration, but the broader point is widely applicable: successful test runs do not prove that test data resembles live use.

A practical migration can proceed in stages:

1. Establish a baseline

Capture the current service's CPU and memory per request, throughput, connection count, event-loop lag, error rate and latency. Separate gateway time from upstream time. Measure median as well as p95 and p99, and include a representative streaming workload.

Also measure cost in a way that reflects your infrastructure. Include the gateway's compute and memory, but do not confuse this with model inference spend. A more efficient proxy may lower its own hosting cost without changing the price of model tokens.

2. Write down behaviour before implementation

Create a behavioural contract for the gateway. Include validation rules, provider-specific request formats, error mappings, retries, timeouts, cancellation, usage accounting and any safety rules. Record which behaviours must be identical and which differences are intentional.

Build fixtures from known cases, not only from ideal requests. Include malformed payloads, tool calls, empty or interrupted streams, provider errors, timeouts and client disconnects. Keep sensitive data out of fixtures unless there is a controlled, approved reason to use it.

3. Implement a narrow slice

Start with a coherent path, such as one provider and one request type, rather than rewriting every feature at once. Keep the old service available. Confirm that the new path meets the behavioural contract, then expand its coverage.

A partial native component can still be appropriate for a bounded operation. But do not assume it will solve a bottleneck in the overall stream. Measure language-boundary crossings and data copies as part of the design.

4. Shadow production traffic

Shadowing means sending a copy of live requests to a candidate implementation while the existing service remains responsible for the customer response. The candidate can process the request and its result can be compared with the production path, without changing what the customer sees.

For inference services, making a second model call just to compare gateways can create duplicate cost and nondeterministic output. A safer pattern is to invoke the model once, then replay the same upstream response through both parsers or downstream handling paths. Compare what each gateway would construct and emit.

Anthropic's migration account describes an oracle-style verification pattern: compare the request prepared by each implementation, then compare their handling of the same model output. An oracle in this context is a trusted reference result used to judge a candidate. The old service is not automatically correct in every respect, but it can serve as a behavioural reference while differences are investigated.

5. Compare structure, not customer text

A diff is a comparison that identifies differences between two results. In a sensitive gateway, you may not need to store prompts or generated text to identify most implementation mismatches. Record structural facts such as the processing step, byte offset, error category or event type. Hashing a difference fingerprint can help group recurring cases without putting customer content in a log.

This approach still needs privacy and security review. Hashes can sometimes be linkable or reveal information depending on the data and method. Set access controls, retention rules and a clear policy for any sampled payloads.

6. Expand traffic by measured stages

After shadow results are understood, route a small, controlled share of eligible traffic to the new implementation. Watch errors, latency, provider failures, usage accounting and customer reports. Increase traffic only when the relevant checks pass and a rollback is available.

Keep the old path deployable until the new one has run through the conditions that matter to the business. A rollback plan should say who can trigger it, what signal triggers it and how to return traffic safely. A switch that exists only in a design document is not a rollback plan.

Migration stage What to compare Safe decision to proceed
Baseline CPU, memory, gateway latency, stream timing and errors The bottleneck is measured and material
Behaviour tests Validation, errors, tools, accounting and edge cases Required behaviours match or differences are approved
Shadow traffic Request construction and processing of the same model output Mismatches are understood, not merely counted
Limited live traffic Customer-visible errors, latency and usage records Operational checks pass and rollback works
Broader rollout Capacity, provider failures and support signals Results remain acceptable at representative load

When is rewriting in Rust worth it?

A Rust gateway is more likely to make sense when several conditions are true:

  • The gateway is a meaningful share of end-to-end latency or infrastructure use.
  • Streaming traffic and concurrent connections create sustained pressure.
  • Profiling identifies request processing, serialisation or memory use as a real constraint.
  • The service has stable responsibilities that can be specified and tested.
  • The organisation can support Rust in production, including hiring, on-call, builds and security updates.

Keeping Python is often sensible when the gateway is small, the upstream model dominates latency, the service is changing rapidly or the team lacks Rust production experience. You might first improve connection reuse, remove unnecessary body transformations, tune worker deployment, reduce duplicate checks or simplify middleware. Those changes can be easier to validate than a rewrite.

Do not make the decision based on a language benchmark alone. A gateway is not just a parser. It is an operational product with policies, provider quirks, failure modes and audit needs. A new implementation that is fast but behaves differently can create more risk than it removes.

For a gateway used by agents, the design also needs clear tool permissions, retries and records of what happened. Our guide to AI agents and automation covers the wider production concerns around agent workflows. For a broader platform decision, see enterprise architecture and platform engineering.

Common mistakes when building a Rust gateway

Treating every gateway delay as model latency. A low TTFT might reflect a faster gateway, a provider-side change or a different workload. Instrument the stages separately and report the scope of the measurement.

Moving code to Rust without moving ownership of the data. A small Rust parser may still receive and return Python objects for every event. Decide where bytes are parsed, transformed and held, and avoid unnecessary crossings in the hot path.

Buffering a whole stream to make processing easier. This can delay the first output and increase memory use for long responses. Buffer only what a control requires, and set a maximum size and time.

Retrying requests without considering side effects. A provider request may already be running when a connection fails. Blind retries can duplicate work, cost or tool actions. Define which errors are retryable and how to handle uncertain outcomes.

Assuming provider APIs behave identically. Providers can differ in event formats, tool-call representation, error handling and usage fields. A shared interface should not hide differences that matter to correctness or billing.

Logging prompts and completions to debug mismatches. These may contain personal, confidential or commercially sensitive information. Prefer structural diagnostics and controlled access to any content that is genuinely needed.

Optimising before setting an acceptance threshold. Decide in advance which measures matter and what change would justify the engineering and operational cost. Include correctness and reliability, not only CPU use.

Where does PADISO fit?

A gateway migration needs both an architecture decision and a safe delivery plan. At PADISO, our platform engineering team can assess the request path, identify the actual bottleneck and design the migration and verification approach. The first step is to map the current flow and agree on the measures that would justify a change.

To decide whether an AI gateway or another AI investment should come first, take the PADISO AI readiness test.

WANT TO TALK THROUGH YOUR SITUATION?

Talk it through with us. Thirty minutes, no slides.

P
Written by the PADISO TeamSydney-based technology leaders who build what they advise on. Seven years of fractional CTO, architecture and AI work for enterprise, government and private equity.

Keep reading

All posts →

Let's talk.

Tell us what you are weighing up, whether it is a build, a roadmap or a deal. You will leave the call knowing your next step.

Book a 30-min callhi@padiso.co