How to shadow test a Python to Rust rewrite: Anthropic's method, tried on 5,000 requests
Short answer
To shadow test a Python to Rust rewrite, send the same requests through both versions, compare the result at every step (not just the final output), and log only the shape of each difference: which step, which piece, the byte where it starts, and both lengths. Group those records by fingerprint, fix one fingerprint at a time, and repeat until nothing is left. That is how Anthropic moved its Messages API to Rust, with Claude agents fixing the differences, and ended up with about 70% less CPU per request and about 20% faster median time to first token. We rebuilt the method at small scale this morning. Our hand-written tests found 1 of the 4 bugs; 5,000 shadowed requests found all four.
Anthropic posted about the migration on X at 16:26 UTC on November 25 (20:26 Dubai time): "We recently migrated our Messages API from Python to Rust." When we checked the X API at about 10:25 Dubai time on November 26, the post had 2,739,691 views, 10,434 likes and 5,016 bookmarks. X posts mentioning Anthropic with Rust or the Messages API jumped from 41 on November 24 to 455 on November 25, and 438 more by 06:25 UTC the next day.
The news sites covered the headline numbers. The part worth copying is the method, so this guide walks through it and shows what happened when we tried it on a toy service of our own.
What did Anthropic actually do?
According to Anthropic's engineering post (published November 25, 2026), the Messages API was written in Python in 2023. Traffic grew roughly 1,800 times from early 2024 to fall 2026, and Python's overhead on every token started to hurt. A partial fix, rewriting only the output parser in Rust and calling it from Python, cut CPU by about 8% to 10%, but each token then crossed between the two languages three times.
So they rewrote the whole request path. Claude wrote a first version of the core path in about a week. The hard part was proving it behaved like the old one. Public traffic moved to Rust in September 2026, without taking the service offline or freezing feature work.
| Number from Anthropic's post | Value |
|---|---|
| CPU per request after the move | About 70% lower |
| Median time to first token | About 20% lower |
| Existing integration tests | About 700 |
| Weakened assertions found in ported tests | More than 100 |
| Rust tests passing in April 2026 | About 98% |
| Inputs matching on production traffic in April | About a quarter |
| Share of merged code written by Claude, May 2026 | More than 80% |
Why weren't the tests enough?
Two reasons, both from the post. The tests ran the Python service inside the test process, so they had to be ported along with the code, and a ported test can quietly check less than the original. Anthropic found more than 100 weakened assertions that way. And tests only cover the cases someone thought of: the post notes that just 20 on/off options make over a million combinations, about 12 days of tests at a second each, for one model.
That is how you get 98% of tests passing while only about a quarter of real inputs match. One example they give: when Python writes JSON for tool calls, it escapes characters like emoji into text codes, and the Rust port wrote them as-is. The prompts differed by a few bytes, nothing errored, and the model just saw slightly different input.
When a test suite is strong enough, it can be the judge. The post points to Bun's move from Zig to Rust, where the TypeScript test suite could check both versions. When it isn't, the old system itself becomes the judge. That's shadowing.
How do you shadow test a rewrite, step by step?
- Pick checkpoints both versions share. Anthropic compared each step: accept or reject, resolve settings, build the prompt, and within the prompt, piece by piece. The first step that differs tells you roughly where the bug lives.
- Remove randomness from the comparison. Claude's replies differ from run to run, so Anthropic ran the model once and replayed the same output into the Rust version. Most diff tools learn what varies by running old code twice and ignoring it, which would have hidden real bugs.
- Record the shape, not the content. They couldn't read customer requests, so each record held the step, the piece, the byte where the first difference starts and both lengths. Their example: step build prompt, piece 2, first diff byte 17, 190 bytes on both sides.
- Group records into fingerprints. One bug leaves the same fingerprint on every request it touches. A script ran every 10 to 30 minutes, grouped records and alerted a coordinating Claude agent only when a new kind showed up. The coordinator gave each new kind to its own worker agent, with a Slack thread where engineers could watch and steer.
- Fix in a fast inner loop. Each agent worked in a cloud sandbox with both codebases. A local input check built the prompt in both versions and compared them in under a second, without calling the model. The agent guessed the cause, wrote its own request to trigger it, and edited the Rust until both matched, then added a test that failed on the old code.
- Confirm in an outer loop. After human review, the fix shipped and shadowed traffic showed whether its fingerprint disappeared. If not, the agent went back to the sandbox with the new evidence.
- Keep a memory loop. Corrections became rules every later agent read, plus tests, lints and a merge check that made anyone changing the Python code make the matching Rust change. In June an agent grouped about 60 review comments into proposed rules for CLAUDE.md, which an engineer edited and approved.
Get the AI tools worth your time
Era of Minds by Salman Ahmed: one short email with the AI tools and news that actually matter. Free.
You're in. Check your inbox.
Confirm your email and your 50 AI prompts are on their way.
Free. Unsubscribe anytime.
We tried it: 5,000 requests through Python and a Rust port
To see how much of this holds up outside Anthropic, we built a tiny version on our own machine on November 26. The "production" service is a 20-line Python function that validates a request, resolves settings (temperature, max tokens) and builds a prompt from a system line, a JSON tools list and the messages. Then we wrote a first-draft Rust port the way a quick port usually looks: serde_json for JSON, {} formatting for numbers, trim() for whitespace.
Our shadow harness sends each request to both, compares at three checkpoints (validate, settings, prompt piece by piece) and stores only step, piece, first differing byte and both lengths. We grouped records by step, piece and whether Rust's output was shorter, longer or the same length. Inputs: 27 hand-written test cases, and 5,000 synthetic requests with a realistic mix (30% with no temperature set, 10% with whole-number temperatures, half with tools, some tool descriptions with emoji or accented words, a rare stray control character). The traffic is generated by us, not real users, and we say so.
| Round | Tests matched (27) | Traffic matched (5,000) | Fingerprints in traffic |
|---|---|---|---|
| 0: first-draft port | 15 (55.6%) | 1,805 (36.1%) | 4 |
| 1: fixes we guessed from the fingerprints | 15 (55.6%) | 2,294 (45.9%) | 2 |
| 2: two more fixes | 27 (100%) | 5,000 (100%) | 0 |
The four bugs behind the round 0 fingerprints, all real behavior differences between Python and Rust that we confirmed on the box:
- JSON key order. Python's
json.dumpskeeps keys in the order they came in.serde_jsonwithout itspreserve_orderfeature sorts them. Same length, different bytes, first difference at byte 10 of the tools piece. This was the only bug our tests caught. - Emoji and accents. Python escapes non-ASCII by default, so 🌦️ becomes
\ud83c\udf26\ufe0f. Rust wrote it raw, so Rust's piece came out shorter. This is the same bug Anthropic describes. - 1.0 versus 1. When the request had no temperature, Python's default printed as
1.0and Rust's as1. 1,473 records, and none in our tests because every test set a temperature. - A stray control character. Python's
strip()removes the unit separator\x1f; Rust'strim()doesn't. Only 19 requests had it, and 8 records showed it in round 0.
Round 1 taught us the most. We fixed escaping, whitespace and the 1.0 formatting, and match rose only to 45.9%. Two things happened. First, 516 more key-order records appeared, because those requests had stopped at the earlier settings difference in round 0. Anthropic saw the same thing: fixing one fingerprint revealed others behind it. Second, our 1.0 fix was a bad guess. It also turned whole-number temperatures sent as 0 or 1 into 0.0 and 1.0, where Python keeps them as integers, and that created a new fingerprint on 476 requests. The fingerprint told us right away. Round 2 turned on preserve_order and kept the integer/float distinction, and both the tests and the traffic matched 100%.
That is a toy, not Anthropic's system. But the pattern held: tests written by someone who knows the code pass on exactly the cases that person imagined, and a pile of realistic requests finds the rest.
What does the core of a shadow harness look like?
This is the comparison and fingerprint part of our harness, cut down. It works for any two implementations that can return their intermediate results:
def first_diff(a, b):
a, b = a.encode(), b.encode()
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
return i, len(a), len(b)
return min(len(a), len(b)), len(a), len(b)
def compare(py, rs): # py, rs = dicts of checkpoint results
for step in ("validate", "settings"):
if py.get(step) != rs.get(step):
return {"step": step}
for k, (a, b) in enumerate(zip(py["prompt"], rs["prompt"])):
if a != b:
i, la, lb = first_diff(a, b)
return {"step": "build_prompt", "piece": k,
"first_diff_byte": i, "python_bytes": la, "rust_bytes": lb}
return None # match
def fingerprint(r):
d = r.get("rust_bytes", 0) - r.get("python_bytes", 0)
return (r["step"], r.get("piece"), "shorter" if d < 0 else "longer" if d > 0 else "same")
Count records with collections.Counter(fingerprint(r) for r in records), hand the biggest group to whoever (or whichever agent) fixes it, and run again. Note that the record holds no request text, which is what let Anthropic do this on traffic it wasn't allowed to read.
Where do Claude agents fit, and where do humans?
Anthropic's answer: humans decide what counts as correct, agents decide how to get there. Early on, engineers ran Claude inside the inner loop themselves. Later they moved to reviewing fixes at the seam between loops, and finally to writing the rules and checks agents worked within.
The review gate mattered. In mid-May, one of the biggest remaining differences was a missing web search tool description that Python fetched from an internal service. An agent proposed copying the text into files Rust could read. The prompts matched and the local check passed, but an engineer rejected it as throwaway code, since Rust would need to call the real service before launch anyway. A verifier rewards matching outputs, so an agent will find the cheapest way to match. The agent saved the rejection to memory, and later agents linked new records from the same bug to that note instead of writing another shortcut. Another rule, "port exactly what Python did," led an agent to find seven more places where the port had guessed.
If you want to see the same "let a checker judge the AI's work" idea in a different field, our guide on verifying the Riemann Hypothesis Lean proof yourself uses a proof assistant as the verifier. For a reality check on what "a team of Claude agents rebuilt it" claims usually mean, see the Supabase "12 Claude agents" joke, explained. And if the memory loop interests you, how to use Claude dreaming covers Anthropic's feature for agents that review and tidy their own memory.
When should you shadow test instead of relying on tests?
- Live services where users rely on quirks. If nobody can write down every behavior, the old system is your spec.
- Outputs that don't fail loudly. Anthropic's point about prompts: a few wrong bytes don't throw an error, they just change the answer. The same goes for serialized data, invoices or search ranking.
- Code you can't freeze. The Python API kept shipping features during the migration, so parity was a moving target. Shadowing measures parity against today's code, not last month's.
- Not needed when the old and new versions can share one strong external test suite, like Bun's, or when the code is small enough to check by hand.
Two cautions from the post: make sure a shadowed request counts only once toward billing and rate limits, and replay the model's output instead of calling the model twice. We would apply the same replay rule to anything else random in your service, like clocks or ID generators. And if you run Claude Code on a port like this, Claude Code Code Mode lets Claude batch several tool calls into one step, which helps when an agent is running many quick checks.
Get the AI tools worth your time
Era of Minds by Salman Ahmed: one short email with the AI tools and news that actually matter. Free.
You're in. Check your inbox.
Confirm your email and your 50 AI prompts are on their way.
Free. Unsubscribe anytime.
FAQ: shadow testing a Python to Rust rewrite
What is shadow testing?
Shadow testing, also called shadowing, means sending the same real requests to the old and new versions of a system and comparing what each one produces, while users only ever get the old version's answer. Anthropic used it to check that its Rust Messages API behaved like the Python one on production traffic before moving users over.
How did Anthropic migrate the Messages API to Rust?
Claude wrote a first version of the core request path in about a week. Anthropic then shadowed production traffic through both versions, compared results at each step, recorded only the shape of each difference, grouped records by fingerprint, and had Claude agents fix one fingerprint at a time in sandboxes, with engineers reviewing fixes. Public traffic moved to Rust in September 2026.
How much faster is Anthropic's Rust Messages API?
Anthropic's November 25, 2026 post says the Rust version uses about 70% less CPU per request and cuts median time to first token by about 20%. An earlier partial rewrite that only moved output parsing to Rust had cut CPU by about 8% to 10%.
Why weren't Anthropic's tests enough to verify the Rust rewrite?
In April 2026 the Rust API passed about 98% of its tests, but only about a quarter of inputs matched on production traffic. The roughly 700 integration tests had to be ported along with the code, which left more than 100 weakened assertions, and tests only cover combinations someone thought to write.
What is a diff fingerprint?
A fingerprint is the shape a bug leaves on every request it affects: the step where outputs first differ, the piece of the output, where the difference starts and how the lengths compare. Grouping records by fingerprint turns hundreds of thousands of mismatches into a short list of distinct bugs, without reading any request text.
Does Python json.dumps escape emoji?
Yes, by default. Python's json.dumps has ensure_ascii set to true, so an emoji is written as escape codes like \ud83c\udf26. Rust's serde_json writes the character as-is. Anthropic hit this exact difference in tool-call JSON, and so did our test.
Does serde_json keep JSON key order?
Not by default. Without the preserve_order feature, serde_json stores objects in a sorted map, so keys come out alphabetically, while Python keeps insertion order. In our test that gave same-length, different-byte prompts and was the only bug our hand-written tests caught.
Do I need Claude agents to shadow test a rewrite?
No. The checkpoint, record and fingerprint parts are plain code you can run yourself, and our test used no model at all. Agents help when there are many fingerprints to chase: Anthropic gave each new fingerprint to its own Claude agent and kept humans on review and on deciding what counts as correct.
Sources
- Anthropic: Migrating our Messages API to Rust (engineering post, November 25, 2026, by Lance Martin, Jake Eaton, Arvin Aminpour, Emma Webb, Bharat Mediratta and Ravi Trivedi)
- On X: @AnthropicAI post (November 25, 2026; metrics via X API, November 26, about 10:25 Dubai time)
- Claude Messages API docs
- serde_json documentation (the
preserve_orderfeature) and Python json module documentation (ensure_asciidefaults to true) - Our test: Python 3.13.5, rustc 1.85.1, serde_json 1.x, run on November 26, 2026 (27 tests, 5,000 synthetic requests, three rounds)
Get AI news decoded weekly.
Decoded is a free weekly email from Era of Minds. The AI stories that actually matter, in plain English. Five minutes, no hype.
You're in. Check your inbox.
Confirm your email and your 50 AI prompts are on their way.
Free. Unsubscribe anytime. Free gift: 50 AI prompts that actually work, sent the moment you join. More about Decoded