Migrating a Core LLM API from Python to Rust: A Practical Guide
This article walks through the real-world migration of a high-traffic LLM platform's core API from Python to Rust. It explains why a partial rewrite fell short, how weakened test assertions masked behavioral drift, and how a shadow-comparison strategy—running the model only once—was used to prove equivalence. Readers will find a reusable migration path covering boundary costs, test semantics, behavioral baselines, staged rollout, and observability. The key takeaway: a 70% CPU reduction matters, but verified consistency is what makes the migration trustworthy.
1. Background: Why the Main API Became the Migration Target
The main API of an LLM platform—typically handling chat completion requests—serves both external customers and internal products such as intelligent coding tools and collaborative office assistants. Its responsibilities go far beyond “forwarding a request to the model”: it first performs input validation and authentication, then prepares prompt templates and assembles system instructions and context, followed by tokenization and budget trimming, and finally decomposes the model output into plain text, reasoning traces, and tool-call structures.
From early 2024 to autumn 2026, over roughly two years, the call volume of this API grew to about 1800 times its original level. This shift in scale had two direct consequences:
- The CPU cost per request was amplified into the overall bill, making even a few percentage points of optimization worthwhile;
- The API evolved from a “thin forwarding layer” into a “thick processing layer,” increasing logical complexity, so any rewrite could affect user-visible results.
This is precisely the motivation for the migration—and the source of its risk.
2. Starting with a Partial Rewrite: An Attempt with Insufficient Returns
The team initially did not opt for a full rewrite. Instead, they replaced the hottest and most self-contained piece of logic—output parsing—with a Rust implementation. The benefit was clear: overall CPU usage dropped by about 8% to 10%.
But the cost was equally clear: for every token in a single request, execution had to cross back and forth between two runtimes three times (entering the parser, returning the result, and continuing subsequent processing). Crossing a language boundary means extra serialization/deserialization overhead, two error models, two dependency and build chains, and the need to cross-reference stack traces between two runtimes when troubleshooting.
The conclusion was pragmatic: the gains were not enough to justify the added complexity, so the team pivoted to a full migration. This judgment is worth noting—the threshold for a partial optimization is not “can it speed things up,” but “does the speedup exceed the new boundary cost.”
3. The Real Challenge: Passing Tests Does Not Mean Identical Behavior
The original ~700 integration tests were tightly coupled to the legacy implementation, so migrating the code meant migrating the tests too. During the audit, more than 100 assertions were found to have been loosened: assertions that originally checked specific structures and values had been changed to only check “no error thrown” or “field exists.” The tests still passed, but the checks had become weaker.
In April 2026, the new implementation passed about 98% of the tests, yet on the production request samples used for comparison at the time, only about a quarter of the input-processing results were fully identical to the legacy implementation. It is important to emphasize: this is not a request success rate—the API returned answers as usual, and routine success checks could not detect the differences at all.
The differences were often tiny, but real:
Legacy: {"text":"hi 😀"}New: {"text":"hi \ud83d\ude00"}
Different JSON escaping strategies meant the prompt differed by a few bytes; different bytes could lead to different tokenization results, which in turn could present the model with slightly different context.
4. Acceptance Method: Shadow Comparison with a Single Model Run
Running the same request through both implementations end-to-end for comparison would risk duplicate billing, and since model output is inherently random, two runs would naturally differ and could not serve as a baseline.
A workable approach is to let the model generate only once, “replay” the same output to both implementations, and then compare the processing results before and after the model call stage by stage:
Request -> Legacy (input processing) -> Model call (once only) -> Output└-> New (input processing) -> Output↓Stage-by-stage comparison and difference fingerprints
The existing production service serves as the acceptance baseline. Comparison points include: validation conclusions, prompt byte sequences, tokenization results, and output structure decomposition. Any inconsistency is recorded as a “difference fingerprint,” annotated with request characteristics and stage labels, making it easy to cluster and locate root causes.
5. A Reusable Migration Path
- Quantify boundary costs: measure the overhead of cross-runtime calls first, then decide between a partial rewrite and a full migration.
- Freeze test semantics: prohibit trading green tests for loosened assertions, and include assertion strength as an audit metric.
- Establish a behavioral baseline: use the production implementation as the baseline for shadow comparison, with the model called only once.
- Triage differences and roll out gradually: fix issues by difference type (byte-level, structural, semantic), then progressively shift public traffic.
- Observability as a safety net: use logging services and monitoring alerts to track difference rates, latency, and resource usage over the long term, with automatic rollback on anomalies.
The output of the migration is not just a faster version of the code, but an engineering methodology for “provable equivalence.” The 70% CPU reduction is a result; the consistency that can be verified is what gives true confidence.
