
Anthropic moved its Messages API from Python to Rust. Claude wrote a first version of the core request path in about a week, and the hard part was proving the new service behaved like the old one. The way they did it is reusable on any rewrite.
What happened
Anthropic built the Messages API in 2023 in Python, and one engineer called it "basically a request forwarder." From early 2024 to fall 2026, API traffic grew roughly 1,800 times.
The team ported the service to Rust. Public traffic moved to the new service in September 2026, "without ever taking the service offline or freezing feature development," in Anthropic's words.
Claude wrote a first version of the API's core request path in about a week. The main effort was proving the port matched production.
Anthropic names three reasons verification was hard: the Python API kept changing during the migration, Claude's replies are nondeterministic, and the team couldn't read customer requests.
Why the tests weren't enough
Anthropic had about 700 integration tests, but they fell short in two ways: they were coupled to Python, and they did not cover the full input space.
A passing test could mean the port was correct, or that the test had been loosened to let incorrect behavior through. An audit of the ported tests found more than 100 weakened assertions. Twenty on/off options alone create over a million possible combinations.
The numbers below come from Anthropic's post and its chart of the share of live inputs where Rust matched Python:
When | Result |
|---|---|
April 2026 | Rust passes about 98% of tests, but only 24% of live inputs match |
Early May | Live match rate drops to 6.5% |
August | Live match rate reaches 99.6% |
[!NOTE] How to read these numbers: These are input-match rates; Anthropic compared replies separately. The chart is a seven-day median, the comparison widened from Anthropic's own traffic to a wider sample, and six misleading days were left out. Read it as a trend rather than a perfectly controlled time series.
Production traffic catches cases that hand-written tests miss. It also weights discrepancies by how often real users encounter them: each test case counts once, but a common bug appears in every request that triggers it.
One example from the post: Python escapes some characters, such as emoji, in JSON tool calls, while Rust writes them as-is. The prompts can therefore differ by a few bytes.
The verification pattern
The old service acted as the reference for the new one. The approach breaks down into five parts:
Shadow the traffic. Production requests ran through both implementations, and the results were compared.
Replay the model once. A request had to count only once toward a customer's limits and bill, and Claude's replies are nondeterministic. So Anthropic ran the model once and replayed that output to Rust.
Compare stage by stage. Checkpoints before and after the model call show where the versions first diverge. Results had to match exactly, because Claude accepts almost any prompt and a small deviation can change the reply without raising an error.
Log diffs without content. Each record holds the step, the piece of the prompt, the first differing byte, and both lengths, never request text.
Group by fingerprint. The step, the piece, where the diff starts, and the length difference together identify a bug. One bug could produce hundreds of thousands of near-identical records, so a script ran every 10 to 30 minutes, grouped them, and alerted a coordinating agent only on new kinds. The coordinator assigned a worker agent to each and opened a Slack thread for engineers to follow.
The agents worked in three loops. The fast inner loop ran checks in sandboxes without calling the model. The outer loop compared Rust deployments with and without each fix on shadowed live traffic. A memory loop stored lessons for later agents.
The verification loop
The process can be summarized as a repeated cycle: compare both implementations, group the differences, fix the largest issue, then verify the change locally and against shadowed traffic.
flowchart TD
A[Production traffic] --> B[Shadow old and new services]
B --> C[Replay one model output]
C --> D[Compare parse, prompt, and format]
D --> E[Record metadata-only differences]
E --> F[Group by fingerprint]
F --> G[Agent fixes a discrepancy]
G --> H[Fast sandbox check]
H --> I[Compare Rust deployments on shadow traffic]
I -->|New differences remain| B
J[Memory of earlier fixes] -. informs .-> G[!WARNING] Important distinction: Parity proves that the new service behaves like the old one; it does not prove that the old behavior is correct. Any deliberate behavior change therefore needs to be specified and approved separately.
What the agents got wrong
The failure modes are the most reusable part:
Slow feedback. Early agents guessed a root cause, opened a PR, and waited for a staging deploy, so each hypothesis took hours or days. A sandbox with fast local checks cut that to under a second.
Gaming the verifier. In mid-May an agent proposed copying the web search tool's description into files Rust could read. The prompts then matched and the local check passed, but an engineer rejected it: Rust had to call the internal service before launch anyway. Anthropic's lesson is that a verifier says whether outputs match, not whether a fix is good enough to ship.
Guessing Python's behavior. After one agent guessed, an engineer made it a rule to port exactly what Python did. An agent then checked the code against that rule and found seven more places that relied on guesses.
[!TIP] How the team mitigated these problems: Human review of each fix before it left the sandbox, rules added to
CLAUDE.md, and permanent tests, lints, and a merge check requiring a matching Rust change (or an exemption) for any Python change.
Reading the performance numbers
Anthropic reports about 70% less CPU per request, over 80% less memory, and about 20% lower median time to first token (TTFT). Scope matters:
Metric | Scope (from Anthropic's chart notes) |
|---|---|
CPU per request, about 70% lower | One region, August to October |
Memory per request, over 80% lower | All of production, August to October |
Median TTFT, about 20% lower | Customers' Claude Code requests, about September 7–21, measured between two marked points. A separate fall before the first point came while almost all of those requests were still on Python, and it is not counted in the 20%. |
[!NOTE] Scope matters: The charts are indexed to 100 (about the level just before the move), so you can't derive absolute savings from them. The measurements also have different scopes and should not be read as three directly comparable experiments.
An earlier podcast interview with Anthropic's Katelyn Lesse was reported as giving a 40–50% CPU reduction. The later engineering post reports about 70%.
The public accounts do not establish that the figures use identical baselines, workloads, or measurement windows. It is safer to report them as different figures rather than treat one as a correction of the other.
One more lesson from the post: an earlier partial rewrite of just the output parser (March 2026), called from Python, cut CPU by only 8% to 10%. Each token crossed the Python/Rust boundary three times, and the gain didn't justify the added complexity.
[!TIP] The practical lesson: Port whole paths, not slices.
Try it: a toy shadow-diff harness
Below is a standard-library demo of the pattern. Save it as shadow_diff_demo.py and run python3 shadow_diff_demo.py. It is my toy, not Anthropic's code; the bugs, traffic mix, and numbers are invented.
How the demo works
The old service is the reference, and the port starts with four seeded bugs. shadow() calls the fake model once using the old prompt, reuses that output for both formatters, and compares the parse, prompt, and format stages in order. It returns metadata for the first divergence, not request or response text.
The fingerprint uses the stage, first differing byte, and length delta. Anthropic's system also tracked which piece of the prompt differed; this smaller demo leaves that dimension out. Offsets are measured on UTF-8 bytes rather than Python characters, so a multibyte character is counted correctly.
An allowlist restricts each diff record to structural metadata. That keeps payload text out of the records, although metadata minimization is not, by itself, a complete privacy or security program.
The code
#!/usr/bin/env python3
"""Toy shadow-traffic diff harness (standard library only).
Illustrates a verification pattern for a service rewrite: treat the old
service as the oracle, replay one model output to both versions, compare each
stage, keep diff records free of request text, and group records by fingerprint.
This is a teaching toy. The bugs, traffic mix, and numbers are invented.
Run: python3 shadow_diff_demo.py
"""
import hashlib
import json
import random
from collections import Counter
# ---- the oracle: the old service ------------------------------------------
def old_parse(r):
return {
"system": r.get("system", ""),
"temperature": r.get("temperature", 1.0),
"stop": r.get("stop", []),
"messages": r["messages"],
}
def old_prompt(p):
body = "\n\n".join(f"{m['role']}: {m['content']}" for m in p["messages"])
return p["system"] + "\n\n" + body if p["system"] else body
def old_format(out, p):
for s in p["stop"]:
if s in out:
out = out[: out.index(s)]
return json.dumps({"text": out})
# ---- the port: starts with four bugs, each switched off when "fixed" -------
BUGS = ("strip_system", "default_temp", "join_newline", "stop_inclusive")
def new_parse(r, bugs):
system = r.get("system", "")
if "strip_system" in bugs:
system = system.strip() # old service keeps trailing whitespace
temp = r.get("temperature", 0.7 if "default_temp" in bugs else 1.0)
return {
"system": system,
"temperature": temp,
"stop": r.get("stop", []),
"messages": r["messages"],
}
def new_prompt(p, bugs):
sep = "\n" if ("join_newline" in bugs and len(p["messages"]) > 2) else "\n\n"
body = sep.join(f"{m['role']}: {m['content']}" for m in p["messages"])
return p["system"] + "\n\n" + body if p["system"] else body
def new_format(out, p, bugs):
for s in p["stop"]:
i = out.find(s)
if i != -1:
out = out[: i + (len(s) if "stop_inclusive" in bugs else 0)]
return json.dumps({"text": out})
# ---- fake model: called ONCE per request, its output replayed to both ------
def model(prompt):
return f"reply-{hashlib.sha256(prompt.encode()).hexdigest()[:6]} done."
# ---- shadow comparison -----------------------------------------------------
def canon(p):
return json.dumps(p) # stable key order for this fixed dictionary
def first_diff(a, b):
"""Return the first differing byte offset, or None when byte strings match."""
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
return i
return None if len(a) == len(b) else min(len(a), len(b))
def shadow(r, bugs):
"""Return a diff record for the FIRST diverging stage, or None if all match."""
po, pn = old_parse(r), new_parse(r, bugs)
prompt_o, prompt_n = old_prompt(po), new_prompt(pn, bugs)
out = model(prompt_o) # one model call; replay its output to both formatters
stages = [
("parse", canon(po), canon(pn)),
("prompt", prompt_o, prompt_n),
("format", old_format(out, po), new_format(out, pn, bugs)),
]
for step, old_value, new_value in stages:
old_bytes = old_value.encode("utf-8")
new_bytes = new_value.encode("utf-8")
diff_at = first_diff(old_bytes, new_bytes)
if diff_at is not None:
# Structural metadata only: no request or response content or hash.
return {
"step": step,
"first_diff_byte": diff_at,
"len_old": len(old_bytes),
"len_new": len(new_bytes),
}
return None
def fingerprint(rec):
# A compact grouping key; the real system also tracked the prompt piece.
return (
rec["step"],
rec["first_diff_byte"],
rec["len_new"] - rec["len_old"],
)
def traffic(n, seed=7):
rng = random.Random(seed)
words = ["hi", "what is TCP?", "summarize this", "explain idempotency"]
for _ in range(n):
msgs = [
{"role": rng.choice(["user", "assistant"]), "content": rng.choice(words)}
for _ in range(rng.choice([1, 1, 1, 2, 3, 4]))
]
r = {"messages": msgs}
if rng.random() < 0.6:
r["system"] = "You are helpful.\n"
if rng.random() < 0.3:
r["temperature"] = 0.2
if rng.random() < 0.1:
r["stop"] = ["done."]
yield r
# The hand-written "test suite": explicit settings, short, tidy inputs.
CANNED = [
{"messages": [{"role": "user", "content": "hi"}], "temperature": 0.5},
{"messages": [{"role": "user", "content": "what is TCP?"}], "temperature": 1.0},
{"system": "You are helpful.", "messages": [{"role": "user", "content": "hi"}], "temperature": 0.2},
{"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}], "temperature": 0.7},
{"messages": [{"role": "user", "content": "summarize this"}], "temperature": 0.3},
]
def diagnose(bugs, reqs, target_fingerprint):
"""Ablation: find a single fix that removes this fingerprint on this traffic."""
for bug in bugs:
remaining = tuple(candidate for candidate in bugs if candidate != bug)
observed = {
fingerprint(rec)
for request in reqs
if (rec := shadow(request, remaining)) is not None
}
if target_fingerprint not in observed:
return bug
raise RuntimeError("no single fix explains this fingerprint")
def main():
# A multibyte character differs at byte 3, not character index 0.
assert first_diff("\U0001F600".encode("utf-8"), "\U0001F601".encode("utf-8")) == 3
requests = list(traffic(5000))
passed = sum(shadow(request, BUGS) is None for request in CANNED)
print(f"hand-written tests: {passed}/{len(CANNED)} pass against the buggy port\n")
assert passed == len(CANNED)
bugs, rates, round_no = BUGS, [], 0
while True:
records = [record for request in requests if (record := shadow(request, bugs))]
rate = 100 * (len(requests) - len(records)) / len(requests)
rates.append(rate)
groups = Counter(fingerprint(record) for record in records)
print(
f"round {round_no}: live match {rate:5.1f}% diff records {len(records):4d} "
f"fingerprints {len(groups)}"
)
for (step, offset, delta), count in groups.most_common(3):
print(
f" {count:5d} x step={step:<6} first_byte={offset:<4} "
f"length delta={delta:+d}"
)
if len(groups) > 3:
print(f" ... {len(groups) - 3} smaller groups")
if records:
# Strict allowlist: diff records contain only structural metadata.
allowed = {"step", "first_diff_byte", "len_old", "len_new"}
assert all(set(record) == allowed for record in records)
assert len(records) > 10 * len(groups)
if not groups:
break
largest_group = groups.most_common(1)[0][0]
fix = diagnose(bugs, requests, largest_group)
print(f" -> fix the biggest group: {fix}\n")
bugs = tuple(bug for bug in bugs if bug != fix)
round_no += 1
assert rates[0] < 15 and rates[-1] == 100.0
assert all(after >= before for before, after in zip(rates, rates[1:]))
print("\nall checks passed")
if __name__ == "__main__":
main()Results from 5,000 synthetic requests
All five hand-written tests pass against the buggy port. The shadow comparison tells a different story: only 7.1% of the 5,000 synthetic requests initially match. Each round fixes the largest fingerprint group.
Round | Live match rate | Diff records | Fingerprints | Largest group fixed |
|---|---|---|---|---|
0 | 7.1% | 4,645 | 17 |
|
1 | 17.6% | 4,122 | 31 |
|
2 | 59.3% | 2,034 | 29 |
|
3 | 66.7% | 1,667 | 28 |
|
4 | 100% | 0 | 0 | All seeded bugs fixed |
The fingerprint count rises from 17 to 31 after the first fix. That is expected: fixing an early parsing discrepancy can expose later differences that were previously hidden behind it. By the final round, all four seeded bugs are fixed and all 5,000 requests match.
The table summarizes the run; executing python3 shadow_diff_demo.py prints the three largest fingerprint groups in each round as well as the final assertions. The full output is useful when debugging, but the round-by-round summary is easier to scan in an article.
The assertions check four things: the hand-written tests pass, diff records contain only allowlisted fields, the match rate never falls between rounds, and multibyte characters produce correct UTF-8 byte offsets.
The numbers are synthetic and illustrate the mechanics; they are not a reproduction of Anthropic's production results.
Takeaways
The demo illustrates the mechanics; the broader engineering lessons are:
You can't test your way to equivalence. Keep the old service as the reference and diff it against production-shaped traffic.
Compare per stage. The first divergence tells you where to look.
Replay nondeterministic outputs. Call the model once and feed both implementations the same result.
Fix by group size, and expect new groups. Early bugs mask later ones.
Keep diff records payload-free, so you can run this on production data. Protect the metadata with appropriate access and retention controls.
Protect the verifier. Whoever or whatever does the fixing will take the cheapest route to green, so lock down tests and assertions and retain human review for design judgment.
Comments0
Join the discussion by logging into your account.
No comments yet. Start the conversation.