Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

AI + Rust: When Does Rewriting Legacy Software Pay Off?

Anthropic migrated its Messages API from Python to Rust, cutting per-request CPU by 70% and memory by over 80%, but the migration took months despite AI writing the first version in a week; the article analyzes runtime savings, cross-language overhead, verification challenges, and break-even calculus for AI-assisted rewrites.

Background: Anthropic's Messages API Migration

Anthropic moved its Messages API from Python to Rust. The migration delivered roughly 70% less CPU per request, over 80% less memory, and about 20% lower median time-to-first-token (TTFT). However, while Claude produced a working core request path in about a week, fully taking over production traffic required several more months. The article examines whether AI-assisted rewrites of legacy systems are economically justified by comparing ongoing runtime savings against the upfront and ongoing migration investment.

Runtime Cost Analysis

Traffic Amplification

The Messages API began as a thin Python wrapper around model calls. Over time it accumulated request validation, prompt assembly, tokenization, safety classification, response parsing, usage accounting, and streaming logic. Each step creates objects, manipulates strings, and allocates memory. At low traffic this overhead is negligible, but by autumn 2026 Anthropic's own-platform API traffic had grown ~1,800× compared to early 2024, turning per-request overhead into a major cost driver.

Rust's ownership, borrowing, and lifetimes shift many checks to compile time, eliminating the need for a runtime garbage collector. Developers can also control allocation, reuse buffers, and avoid unnecessary copies. However, Rust code can still allocate heavily if written carelessly; the language enables efficiency but does not guarantee it.

Cross-Language Overhead

Anthropic initially migrated only the model-output parsing to Rust, calling it from Python. This yielded an 8–10% CPU reduction, but every output token crossed the Python/Rust boundary three times, adding call overhead and a new integration layer to maintain. The team concluded the marginal gain did not justify the added complexity.

Expanding the Rust boundary to cover pre- and post-model processing removed the per-token language crossings. The article illustrates the same principle with the open-source project rust-anything, which ports Prettier to Rust. Calling the Rust formatter via a JS/Rust bridge for each file was slower than the original JavaScript because the entire document had to be serialized to JSON and back. When Rust handled the whole formatting pipeline, speedups appeared: on an Apple M4, Node 24.15.0 with Prettier 3.6.2 versus a Rust release build showed:

Cold start (new process per file): 18.8× and 19.8× faster.

Warm process (20 iterations per file): ~4.2× faster in both runs.

The gap between cold and warm runs largely reflects startup overhead: Node ~55 ms vs Rust ~3 ms per process launch.

Translating Resource Savings to Money

The 70% CPU and 80% memory reductions apply only to the API layer; model inference costs are unchanged. TTFT improvement is ~20% because the API portion is only part of the critical path. Measurements came from one region (CPU), production-wide memory, and a short window of Claude Code requests (TTFT), using seven-day averages.

If a module consumes 10% of total CPU and becomes 70% more efficient, overall service CPU drops ~7%. Savings may not immediately reduce instance counts because of memory/network limits, reserved headroom, or annual commitments. The first financial benefit is often higher throughput on existing hardware; the next capacity expansion then requires fewer machines. CPU and memory gains may overlap on the same instances, so the bill reflects the combined effect only once. Realized savings appear gradually as the new implementation takes live traffic.

Migration Cost: Verification and Incremental Takeover

Shadow Traffic Reveals Gaps

In April, the Rust version passed ~98% of tests, yet when fed the same production inputs, only ~25% of requests produced identical processing results. The ~700 integration tests were tightly coupled to Python internals (in-process mocks for billing, rate limiting, etc.) and could not be reused directly. Claude rewrote tests, but review found 100+ assertions had been weakened. A passing test might mean the bug was fixed or the check was relaxed.

Combinatorial explosion compounds the problem: 20 feature flags yield over 1 million combinations; testing each for one second would take ~12 days, not counting model and prompt variations. One subtle difference: Python escaped certain characters (e.g., emoji) in tool-call JSON, while Rust emitted them raw. The parsed values were equal, but the byte sequences fed to the model differed, potentially altering downstream behavior.

From Production Diffs to Local Fixes

To isolate discrepancies, Anthropic built a shadow environment: the old service handled live requests while Rust processed the same inputs on the side. The model ran once; its output was replayed to the Rust path. This allowed comparison of request parsing/prompt construction (pre-model) and token-to-response assembly (post-model) without worrying about sampling variance. Billing and quota enforcement were also mirrored to ensure each request was counted once.

Engineers logged the processing step, prompt segment, byte offset, and length where outputs diverged, then grouped similar records. A single defect could generate hundreds of thousands of near-duplicate logs; clustering prevented repeated Agent investigations.

Agents then constructed local inputs to reproduce each divergence. Input-side checks (no model call) completed in under a second; output-side checks used a scripted mock model (e.g., returning a tool call). Because the data was synthetic, Agents could inspect full state, iterate fixes, and produce regression tests that failed before the fix and passed after.

Example: the web-search tool description was fetched from an internal service in Python but missing in Rust. An Agent copied the text locally to make outputs match, but engineers rejected the workaround because the copy would stale. Proper integration took weeks; the rejection rationale was recorded so future Agents recognized the same unresolved issue.

Post-deployment validation grouped requests by model, prompt caching, tools, extended thinking, etc., comparing error rates before and after each fix to avoid false confidence from traffic shifts.

Incremental Takeover by File (Prettier Case)

rust-anything

adopted a file-level fallback strategy: supported files are formatted entirely by Rust; unsupported syntax or configuration triggers an Unsupported return, and the original Prettier handles the file. The Rust path must also replicate original stdout, stderr, and exit codes, including error cases.

Of 17,224 recorded runs, 15,861 (92.1%) were fully handled by Rust; 7.9% fell back. After the corpus passed, the author generated more inputs and configurations, comparing outputs byte-for-byte, and deliberately introduced bugs to verify test sensitivity. This uncovered ~75 additional differences, such as CSS column positions calculated in UTF-16 code units vs bytes (breaking on non-ASCII), and invalid inputs that the original rejected but the port accepted. Each was fixed or routed to fallback.

Break-Even Calculation

Runtime savings begin only after traffic cutover, while engineering investment (writing code, building verification harnesses, maintaining dual implementations) occurs upfront. A hypothetical example: 300,000 CNY total migration cost, 40,000 CNY/month resource savings, 10,000 CNY/month extra maintenance → ~10 months to break even. Actual figures depend on traffic growth, deferred features, and the cost of reproducing the legacy environment. For low-frequency internal tools, the engineering effort may exceed lifetime infrastructure savings.

Anthropic's situation combined two shifts: traffic growth amplified the old implementation's cost, while AI reduced the labor to write and debug the new one. The Prettier port demonstrates an alternative cadence: accelerate supported files first, gradually expand coverage, and accept the ongoing cost of keeping the original.

Previously, rewrite decisions relied on rough estimates. Now teams can build a complete critical path, run old and new side-by-side, measure cross-language overhead, catalog behavioral mismatches, and quantify engineer time per fix cycle. This empirical foundation makes the go/no-go decision for the remaining migration far more concrete.

References

Anthropic: Migrating our Messages API to Rust , 2026-11-25 (https://www.anthropic.com/research/migrating-api-to-rust)

rust-anything: Real-world runs, Prettier case study and benchmarks. Commit 6617916717e9ce0fc2863cc49a90c5a1ebb7da1b (https://github.com/erkamyaman/rust-anything/blob/6617916717e9ce0fc2863cc49a90c5a1ebb7da1b/docs/real-world.md#prettier)

rust-anything: Checking the port against Prettier beyond the corpus (https://github.com/erkamyaman/rust-anything/blob/6617916717e9ce0fc2863cc49a90c5a1ebb7da1b/demo/real-world/prettier-rs/equiv/README.md)

The Rust Programming Language: What Is Ownership? (https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html)

Elon Musk: Original post and follow-up on memory management, 2026-11-10 (https://x.com/elonmusk/status/2120094207604035595; https://x.com/elonmusk/status/2120220004578963572)

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

performance optimizationPythonAI-assisted developmentRustAnthropicAPI migrationcost-benefit analysislegacy rewrite

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion