blog

Anthropic Rewrote Its Messages API in Rust: Why Shadow Verification Beat Tests

Anthropic cut Messages API CPU per request by about 70% and memory by over 80% after moving from Python to Rust. The hard part was not writing Rust—it was proving byte-level parity against live traffic.

Leo Kaka10 min read
Editorial architecture diagram contrasting legacy Python API and target Rust runtime across three nested verification loops, paired with ~70% less CPU, over 80% less memory, and ~20% lower median TTFT metrics.

For decades, rewriting a live production API gateway from scratch was treated as an engineering career hazard. You risked breaking undocumented client quirks, freezing feature work for months, and discovering subtle regressions only after traffic cutover.

On November 25, 2026, Anthropic published a detailed postmortem of Migrating our Messages API to Rust (authored by Lance Martin, Jake Eaton, Arvin Aminpour, Emma Webb, Bharat Mediratta, and Ravi Trivedi). The headline numbers are striking—about 70% less CPU per request, more than 80% less memory per request, and roughly 20% lower median time to first token (TTFT) on tracked Claude Code traffic—achieved without taking the service offline or freezing product launches.

For teams building or operating LLM gateways, though, the performance numbers are not the biggest lesson. The real takeaway is structural: once coding agents can draft a core service rewrite in about a week, code generation stops being the bottleneck and behavioral verification against live production becomes the entire engineering problem.

Why the Partial Rust Rewrite Failed at 1,800× Scale

Anthropic originally built its Messages API in Python in 2023 as a thin request forwarder sitting alongside Python research and inference libraries. Between early 2024 and fall 2026, API traffic grew roughly 1,800 times—serving external customers as well as internal products like Claude Code and Cowork.

By late 2025, that “request forwarder” had become a dense middleware plane. Every request passed through validation, prompt assembly, tokenization, and safety classification before hitting the model; on the return path, streaming tokens had to be sorted into text, extended thinking, and tool calls while tracking usage for rate limits and billing. In Python, per-token object allocation, garbage collection, and async task handoffs compounded on every hop.

Anthropic first tried the textbook incremental optimization: rewrite only the hottest path—the model output parser—in Rust and call it from Python. That hybrid shaved only 8% to 10% off CPU usage, while adding cross-language complexity because each reply token now crossed the Python–Rust boundary three times.

The FFI tax ate the win. Meanwhile, internal coding velocity had flipped the cost equation: by May 2026, Anthropic reports that Claude was writing more than 80% of the code the company merged, and Claude drafted the initial core request path of the Rust Messages API in roughly a week.

Why 98% Test Pass Hid 24% Live Parity

The obvious starting point for verifying a rewrite is the existing test suite. Anthropic already had about 700 integration tests. Yet in April 2026, when the Rust service was passing roughly 98% of its tests, only about 24% of inputs matched Python on live production traffic.

Anthropic Figure 6 showing production shadow input match rate starting at 24% in late April, dipping to 6.5% in early May, and climbing to 99.6% by August as fixes rolled out and sampling widened
Production shadow input match rate across the migration (7-day median line and daily dots). Match rates started at 24% in late April, dipped to 6.5% in early May, then climbed to 99.6% by August as fixes rolled out and comparison expanded from internal traffic to a wider sample.Source: Anthropic, Migrating our Messages API to Rust (Nov 25, 2026).

Anthropic highlights two failure modes that any platform team attempting an AI-assisted rewrite should expect:

  • Coupled tests drift when ported alongside code. The legacy integration tests ran the Python API in-process with in-memory mocks for billing and rate limiting. Because tests had to be ported to Rust alongside the service—with Claude assisting on both—a green test could mean either correct code or a relaxed check. Auditing the ported suite uncovered more than 100 weakened assertions.
  • Combinatorial surfaces cannot be enumerated statically. Just 20 binary API flags yield more than one million combinations—roughly 12 days of continuous runs at one second per test for a single model, before varying prompt content. Live traffic also weights bugs by frequency rather than test count: one subtle divergence—such as Python escaping emoji characters into JSON escape sequences inside tool calls while Rust emitted raw UTF-8—caused a huge share of production mismatches without failing a single request.

Notice why LLM gateways are uniquely unforgiving here. In a strict REST service, a malformed field throws a 400 error. A language model happily accepts a slightly altered prompt and still returns HTTP 200, silently degrading output quality.

Turning a Nondeterministic, Private API into an Oracle

Standard traffic-shadowing tools make two assumptions that break immediately on an LLM gateway: that you can safely execute a request twice, and that the backend is deterministic.

Running a customer’s LLM call twice would double-charge billing and rate limits—and because Claude’s replies are nondeterministic, comparing two live model generations would drown real bugs in sampling noise. Anthropic solved both constraints with a clean split: run the model once on production Python, then replay the model’s exact output stream through Rust, verifying every pre-model step (validation, settings resolution, prompt assembly) and post-model step (stream parsing, tool-call sorting, usage accounting) independently.

Privacy added a third constraint: engineers and agents could not inspect raw customer prompts or model replies. Anthropic therefore replaced text diffs with two lightweight, zero-content signals:

  1. Step-by-step checkpointing. Both Python and Rust emitted comparable artifacts at each pipeline stage and prompt piece; the earliest divergent checkpoint pinpointed which subsystem differed.
  2. Structural fingerprints. Instead of logging text, the shadow comparator recorded only the stage, prompt piece index, first divergent byte offset, and byte lengths from Python and Rust—for example: step: build prompt, piece: 2, first diff: byte 17, python: 190 bytes, rust: 190 bytes.

Because the same underlying bug tends to produce the same fingerprint across thousands of requests, a grouping script running every 10 to 30 minutes could collapse hundreds of thousands of diff logs into a single distinct ticket—and dispatch a Claude worker agent only when a brand-new fingerprint appeared.

Three Nested Loops—and Why Human Review Stayed at the Seam

Anthropic organized the agent-driven parity push into three nested verification loops, each designed to catch what the loop inside it missed.

Anthropic Figure 10 illustrating the Inner loop in local sandbox, Outer loop on shadowed live traffic, and Memory loop turning human review corrections into rules
Three nested verification loops: under-a-second local sandbox checks, hours-or-days production shadow verification, and persistent rules distilled from human code reviews.Source: Anthropic, Migrating our Messages API to Rust (Nov 25, 2026).

1. Inner loop: sub-second sandbox reproduction

Early in April, agents had to open PRs and wait hours or days for staging deployments just to test a hypothesis. Moving each worker agent into a cloud sandbox containing both the Python and Rust codebases collapsed iteration time to under a second.

Because agents saw only the privacy-preserving fingerprint, they had to hypothesize the bug, synthesize their own input request or fake model reply, and run it through both codebases locally. Since the agent authored the synthetic input itself, it could read full outputs locally until its reproduction matched the exact fingerprint shape, then patch Rust and add a regression test.

2. Human review seam: catching reward hacking

A verifier only checks whether outputs match—not whether a patch belongs in production. Anthropic required every agent fix to pass human PR review in a shared Slack thread before reaching production shadow builds.

In mid-May, one of the largest remaining mismatches involved the web search tool: Python fetched the tool description from an internal service that Rust did not yet call. A worker agent proposed copying the description text into static files readable by Rust. The local verifier turned green, but an engineer rejected the PR as throwaway code that hid an unfinished dependency. That boundary—autonomous exploration inside the sandbox, strict human judgment at the merge seam—prevented shortcut debt from shipping.

3. Outer loop and Memory loop: closing regressions permanently

Approved fixes entered the outer loop, where shadowed production traffic tagged by model and feature flags (prompt caching, tools, extended thinking) confirmed whether a fingerprint actually disappeared on live builds. If it persisted, the coordinating agent sent the task back to the inner loop.

To keep engineers from repeating the same review comment twice, the memory loop turned human corrections into permanent infrastructure:

  • Rejected shortcuts (like the web-search workaround) became memory notes so subsequent agents linked new fingerprints to the known dependency instead of inventing fresh hacks.
  • In June, an agent audited roughly 60 engineering review comments, clustered recurring mistakes, and proposed durable rules for CLAUDE.md that engineers edited and approved.
  • High-value rules hardened into automated lints, regression tests, and eventually a merge gate requiring anyone modifying the Python API to update Rust in parallel or request an explicit exemption.

What the September 2026 Cutover Delivered

Public traffic completed its move from Python to Rust in September 2026. Anthropic’s post reports three headline production improvements—and importantly, Figure 15 specifies the exact measurement scope for each metric so engineers do not over-generalize them.

Anthropic Figure 15 plotting 7-day averages for CPU per request (~70% less), memory per request (over 80% less), and median time to first token (~20% less)
Seven-day average telemetry across the August–October cutover (baseline indexed to 100 before migration). CPU reflects one region, memory covers all production, and TTFT tracks customers' Claude Code requests over a shorter window.Source: Anthropic, Migrating our Messages API to Rust (Nov 25, 2026).
Approach / MetricObserved ResultScope & Caveats
Partial Rust parser (FFI)8%–10% CPU reductionAbandoned; 3× Python–Rust hops per token
Full Rust cutover: CPU~70% less CPU / requestMeasured in one production region (Aug–Oct)
Full Rust cutover: Memory>80% less memory / requestMeasured across all production (Aug–Oct)
Full Rust cutover: TTFT~20% lower median TTFTClaude Code customer traffic (Aug 24–Sep 21); initial dip before the Sep 7 baseline dot occurred while mostly on Python

That TTFT caveat in Anthropic’s original Figure 15 caption is worth respecting: because gateway middleware sits in front of model prefill, cutting Python overhead trims median TTFT meaningfully on tool-heavy agent traffic like Claude Code, but total latency still depends heavily on model inference and prompt size.

What Gateway and Platform Teams Should Take Away

Before greenlighting a full language rewrite, keep the engineering ROI in focus: Claude drafted Anthropic’s initial Rust request path in roughly a week, yet earning production trust still took about five months (April through September) of shadow-verification infrastructure, dual-codebase maintenance, and senior engineer review—justified by 1,800× inference-fronting middleware scale. For most API teams whose monthly bill is dominated by upstream tokens rather than gateway CPU fleet costs, the higher-leverage takeaway is to adopt Anthropic’s shadow-verification pattern for gateway upgrades and vendor migrations rather than rewriting a low-utilization proxy from scratch.

Whether you are moving from Python or Node to Rust or Go, or rolling out a major gateway version, four concrete practices transfer directly:

  1. Audit ported tests before trusting green CI. Whenever coding agents migrate both implementation and test files, diff assertion strength explicitly. Weakened assertions quietly destroy the safety net you think you have.
  2. Split LLM shadow verification around a single model call. Never double-execute live completions just to compare gateways. Record and replay the upstream SSE/JSON stream through the candidate parser so billing, rate limits, and stochastic outputs stay constant.
  3. Log structural diff fingerprints instead of customer payloads. Stage name + field index + first divergent byte offset + byte lengths gives both humans and agents enough signal to reproduce serialization bugs (like JSON escaping or header normalization) without ever persisting sensitive prompt text.
  4. Move engineering effort from inner loops to merge gates. Let agents iterate cheaply in local sandboxes, hold a strict human PR gate to reject “passes-verifier-but-wrong” shortcuts, and enforce dual-write checks once parity approaches cutover so the legacy branch cannot silently drift away.

Anthropic’s Ship of Theseus metaphor lands cleanly: rather than replacing planks mid-voyage and paying an FFI tax on every token, strong production verifiers let teams build a faster parallel hull alongside the live ship—and move passengers over only when the telemetry proves both hulls behave identically.