Migrating a Core API From Python to Rust: A Cost Reduction Practice

    This article examines why an AI infrastructure team migrated its core messaging API from Python to Rust and cut CPU usage by roughly 70%. It explains where Python's cost structure breaks down under extreme traffic growth, why partial rewrites deliver only 8%–10% gains, and how full migration removes cross-language boundary overhead. It also covers the real bottleneck of AI-assisted coding: proving semantic equivalence through differential testing, shadow traffic, property testing, and performance gates, along with a practical decision checklist for teams.

    1. A Counterintuitive Engineering Decision

    In AI and data-intensive industries, switching the implementation language of a core API from Python to a systems language is an unusual choice. The reasons are easy to understand: model training, inference scripts, data processing, and application frameworks are almost all built around Python, with a rich ecosystem, fast iteration, and easy hiring. So when an AI infrastructure team publicly stated that its external messaging API had been fully migrated from Python to Rust, with CPU usage dropping by about 70%, many developers’ first reaction was: is this a “going against the trend” move that trades development efficiency for performance?

    The real value worth discussing does not stop at the old topic of “systems languages are faster than interpreted languages.” Two more critical questions are:

    • When traffic grows thousands of times within a two-to-three-year window, exactly which part of the existing service’s cost structure breaks down;
    • When code can be generated in large volumes by intelligent coding tools, how to rigorously prove that the new implementation is completely semantically equivalent to the old one.

    The second question is precisely the real bottleneck many teams encounter after adopting AI-assisted coding: writing code has become faster, but “proving the code is correct” has not become faster, and may even have become harder.

    2. Why the Python Service Could No Longer Hold Up

    According to the public technical retrospective, this external messaging API was initially built in Python in 2023, positioned only as a lightweight forwarding layer; it then gradually evolved into a complex system, sharing several internal libraries with the research and inference teams. From early 2024 to fall 2026, traffic grew by about 1,800x.

    At this scale, any tiny interpreter overhead per request, temporary object allocation, memory reclamation, and scheduling costs are amplified into real bills and tail latency. There is an easily overlooked detail here: Python is not “too slow to use”; the problem is that the bottlenecks of this kind of service are highly concentrated in a few specific areas:

    1. Encoding and decoding of requests and responses, especially serialization and deserialization of large JSON payloads;
    2. Per-token processing of streaming output, where every token goes through the full parse, validate, and callback chain;
    3. Allocation and reclamation of large numbers of short-lived small objects, causing GC pressure and memory bandwidth consumption;
    4. Context switching and lock contention under a single-process concurrency model.

    These are exactly the scenarios where systems languages have an advantage: memory layout determined at compile time, predictable stack allocation, no GC pauses, and finer-grained control over the async runtime.

    But the counterargument must be given: if the business does not have particularly demanding performance and cost constraints, a mature interpreted web framework is already sufficient, and a rash migration means extra manpower investment, maintenance costs, and the risk of reintroducing defects. A more pragmatic path is to profile performance first, use flame graphs and layer-by-layer timing statistics to locate real hotspots, and then decide whether to optimize algorithms, adjust the concurrency model, or replace the implementation language. Most small and medium-sized teams will choose the former. An Anthropic-style decision is more like “scale backed the problem into a corner” than a universal best practice.

    3. Why Partial Rewrites Only Yield 8%–10%

    The team’s first step was not a full rewrite, but implementing only the small output-parsing segment in Rust, leaving the rest in Python and calling across the language boundary. As a result, CPU usage dropped by only about 8% to 10%.

    This result is highly illustrative. Every token has to cross the language boundary once, and a single response typically crosses back and forth three times (entering the parser, returning intermediate results, and handing back to the main flow). The fixed overhead of cross-language calls, data copying, and serialization costs offset most of the theoretical gains.

    A general rule can be abstracted: the upper limit of partial replacement gains depends on the proportion of the replaced part in total time consumption and its interaction frequency with surrounding code. When hotspots are scattered and interactions are dense, replacing a single point is almost ineffective. Schematically, if each cross-boundary call is accompanied by a struct-to-dict conversion, the cost looks roughly like this:

    1. # Counter-example: high-frequency cross-language calls, boundary cost eats the gains
    2. for token in stream:
    3. raw = native_parse(token) # cross-language call + data conversion
    4. obj = dict(zip(KEYS, raw)) # construct Python object again
    5. await emit(obj)

    A more reasonable approach is to raise the boundary from “once per token” to “once per response” or “once per batch,” letting the native side complete the entire stateful processing and return only at the final result:

    1. // Sink the stateful loop as a whole; the boundary is crossed only once
    2. #[no_mangle]
    3. pub extern "C" fn parse_stream(buf: *const u8, len: usize) -> *mut Result {
    4. let mut state = Parser::new();
    5. for chunk in unsafe { std::slice::from_raw_parts(buf, len) }.chunks(4096) {
    6. state.feed(chunk); // state stays on the native side
    7. }
    8. Box::into_raw(Box::new(state.finish()))
    9. }

    4. Full Migration: Reducing Boundary Cost to a Single Crossing

    After confirming that bottlenecks were spread across the entire chain, the team chose a full rewrite: request ingress, authentication, parameter validation, encoding/decoding, and streaming forwarding all run within the same runtime, completely eliminating the cross-language boundary. This is the structural reason for the roughly 70% CPU drop—the gains do not come from “a piece of code becoming faster,” but from shorter object lifetimes, compact memory layout, autonomous and controllable async scheduling, and the disappearance of fixed per-request overhead.

    Engineering points during migration typically include:

    • Contract first: write external behavior (status codes, error structures, field optionality, streaming chunk semantics) as executable contracts, not documentation descriptions;
    • Dependency convergence: libraries shared between the original system and the research/inference sides need stable boundaries abstracted out, avoiding carrying internal implementation details into the new service;
    • Observability alignment: log fields, metric definitions, and trace identifiers must remain consistent, otherwise old and new versions cannot be compared;
    • Canary release and rollback: gradually shift traffic by proportion, keeping a one-click rollback path.

    5. The Real Difficulty: Proving the New and Old Implementations Are Equivalent

    When code can be generated in large volumes by AI, capacity is no longer the bottleneck; verification capability is. A viable approach is to make “equivalence” part of an automated pipeline:

    1. Differential testing: send the same batch of real requests to both old and new implementations, comparing responses field by field; for streaming scenarios, compare the concatenated full content and the semantic equivalence of chunk boundaries.
    2. Shadow traffic: mirror a copy of production traffic to the new implementation, comparing only without returning, observing long-tail and anomaly distributions.
    3. Property testing and randomization: randomly generate parameter combinations, boundary lengths, and abnormal inputs to cover branches that are hard to enumerate manually.
    4. Contracts and snapshots: incorporate error codes, error message templates, and field order stability into snapshots to prevent compatibility breaks that “look fine.”
    5. Performance regression gates: include CPU, memory, and tail latency in continuous integration threshold checks to avoid optimizations being swallowed by subsequent commits.

    It needs to be emphasized that AI-generated code significantly increases the proportion of implementations that “look reasonable but have subtle deviations,” such as different error handling order, different Unicode truncation positions, and different null semantics. These differences are extremely easy to miss in manual review; only mechanical comparison can catch them.

    6. A Decision Checklist for Teams

    • Profile first, then talk about rewriting: a rewrite without quantitative data support is likely to be a net negative;
    • Partial replacement only works when “hotspots are concentrated and interactions are few”; otherwise, prioritize raising the call granularity;
    • Migration gains mainly come from eliminating boundaries and fixed overhead, not from algorithmic optimization of a single code segment;
    • Verification investment should be no less than implementation investment; differential testing and shadow traffic are the minimum configuration;
    • If the team is limited in size, it can leverage general cloud capabilities such as container platforms, log services, and monitoring/alerting to handle canary release and observability, focusing energy on proving equivalence.

    The conclusion is not romantic: language migration is not a performance silver bullet, but a comprehensive rebalancing of cost structure, engineering constraints, and verification capability. Before scale reaches the critical point, optimizing hotspots is usually more cost-effective; once the critical point is crossed, whether the verification system can keep up determines whether the migration is a gain or a liability.