Rewriting a Core API Service in Rust: A Technical Post-Mortem of an LLM-Assisted Migration

    This article provides a technical post-mortem of rewriting a core API gateway service in Rust with the assistance of large language models (LLMs). It explores the motivations behind migrating from a dynamic language to Rust, focusing on memory safety, strong typing, and garbage collection-free latency. The core challenge of proving behavioral equivalence between the old and new services is addressed through a multi-layered validation system, including integration tests, structural output comparison, and shadow traffic. Additionally, the article details practical strategies for leveraging LLMs in code translation, managing token boundaries, and offers actionable advice for teams considering similar architectural migrations.

    Background: From Request Forwarder to Core Hub

    Many teams experience a similar service evolution: an API gateway or messaging service starts as a thin “forwarding layer”—receiving requests, validating formats, calling backend models, and returning the response as-is. However, as the business grows, this forwarder gradually bloats. Incoming requests must pass parameter validation, parse configurations, and assemble multi-turn conversations into model-readable prompts. This is followed by tokenization, safety classifier filtering, and finally handling streaming outputs, timeouts, retries, and fallbacks. Each iteration adds a layer of logic to the existing dynamic language code until maintenance costs, performance bottlenecks, and type safety hazards erupt simultaneously.

    At this point, the team faces a choice: keep patching, or rewrite entirely with a systems-level language? One AI service team chose the latter, selecting Rust and heavily utilizing their in-house LLM-assisted coding capabilities during the refactoring process. This practice left several technical questions worth exploring in depth.

    1. Why Migrate to Rust?

    Rust is not simply about being “faster”; it brings a systematic set of engineering benefits:

    1. Compiler-guaranteed memory and concurrency safety. The biggest risks in core gateway services under high concurrency are data races, memory leaks, and undefined behavior. Rust’s ownership system intercepts these issues at compile time, rather than triggering 3 AM production alerts.
    2. Type system as documentation. Request/response structures, configuration objects, and middleware signatures are strictly constrained by types. During refactoring, the compiler points out all locations requiring modification, which is a decisive advantage for long-term maintenance.
    3. Stable latency without GC. A gateway service’s tail latency directly impacts all downstream callers. Avoiding garbage collection pauses often improves P99 latency more significantly than increasing throughput.

    Of course, the tradeoffs are equally real: slower development speed, less mature libraries in certain domains compared to dynamic languages, and a team learning curve. Therefore, a migration decision must be based on clear pain points, not just because “everyone else is using it.”

    2. The Hardest Problem: Proving the New Service is Production-Ready

    During the migration, the old service continued handling live traffic while the team iterated on features as usual. This meant the old and new implementations had to maintain behavioral consistency over a long period. This leads to the core question of the entire post-mortem:

    Engineers cannot directly view plaintext customer content (privacy red lines), nor can they expect a model to give the exact same answer twice for the same input (model outputs are inherently non-deterministic). So, how do they prove that “this change didn’t alter behavior”?

    The solution to this problem is a multi-layered validation system:

    Layer 1: Integration test voting. The team used hundreds of integration tests covering various API branches, with each case counting as one vote. By the late stages of migration, the pass rate reached over 98%. The key isn’t the number itself, but the test design: each case must fix randomness, freeze dependency versions, and stub out the non-deterministic parts of the model, validating only the gateway’s own conversion logic—validation, assembly, tokenization, and safety filtering.

    Layer 2: Output equivalence comparison. For responses to real user requests, the team employed a separate comparison method. Instead of requiring byte-by-byte equality, they compared structural equivalence: status codes, response body schema, and whether the sequence of streaming event types matched. This essentially formalizes “semantic equivalence,” avoiding over-assertion on non-deterministic outputs.

    Layer 3: Shadow traffic and canary releases. After tests passed, old and new services routed real traffic proportionally—internal traffic first, followed by a small percentage of external traffic—gradually scaling up the ratio through monitoring (error rate, latency distribution, client retry rate). This layer served as the final safety net.

    The takeaway for general teams is: The success of a language migration is 70% validation system and 30% writing code. Without an automated equivalence check, any rewrite is a gamble.

    3. Tokens Crossing Language Boundaries: The Real Cost of LLM-Assisted Coding

    During this refactoring, LLM-assisted tools took on a massive amount of “translation” work: converting dynamic language business logic into Rust, supplementing tests, and writing migration scripts. Here is an often-overlooked engineering fact: every interaction requires tokens to cross multiple boundaries—original language code, natural language instructions, Rust output, and compiler errors flowing back. Each crossing can introduce understanding bias, and biases accumulate.

    Therefore, the team’s practical experience was:

    • Small-step translation, incremental verification. Translate one module, compile immediately, and run tests immediately. Let the compiler act as the “gatekeeper” for AI output, rather than generating thousands of lines at once and debugging later.
    • Humans handle architecture, AI handles filling. Key decisions like module division, error handling strategies, and concurrency models were driven by engineers; boilerplate code, type definitions, and test case generation were handed over to the model.
    • Use test results to feed prompts. When AI output didn’t meet expectations, the team prioritized feeding the failed test cases and compiler errors directly back to the model, rather than trying to describe the issue repeatedly in natural language.

    In this collaborative model, AI didn’t “replace developers,” but compressed the tedious mechanical migration work by more than half, allowing human effort to concentrate on equivalence judgment and architectural design—precisely the areas that require human judgment the most.

    4. Advice for Teams Considering Similar Migrations

    1. Build tests before rewriting. If the old service lacks sufficient integration test coverage, write tests first to “freeze” the old implementation’s behavior into an executable specification.
    2. Define clear equivalence standards. Byte-by-byte equality is often unfeasible. Design structured comparison schemes in advance (schema validation, event sequence comparison).
    3. Maintain dual-track running capability. While old and new implementations coexist, feature iteration cannot stop. The routing layer must support instant switching and rollback.
    4. Rationally evaluate the boundaries of AI assistance. Let LLMs handle deterministic, verifiable tasks. Compilers and test cases form an automated quality loop.
    5. Benchmark performance expectations. Stress test on your actual workload rather than copying public data; latency distribution and memory footprint often speak louder than peak throughput.

    Conclusion

    Rewriting a core API service in Rust appears to be a language substitution on the surface, but it is fundamentally a rebuild of the validation system and engineering process. When outputs are inherently non-deterministic and inputs are constrained by privacy, “proving behavioral equivalence” becomes the true technical core of the project. Those who successfully complete such migrations win not by writing code faster, but by providing a sufficiently strong chain of evidence before going live.