›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Claude Wrote the Rust Rewrite in a Week. Proving It Worked Took Five Months.

November 26, 2026 · 13 min read

AI, Agentic Coding, Rust, Python, C#, Migration, Testing, Claude Code, Architecture

On November 25, Anthropic published a long engineering post about moving the Messages API, the API behind every Claude request, from Python to Rust. The headline numbers are good: about 70% less CPU and more than 80% less memory per request, and median time to first token down about 20%. They did it without taking the service offline.

What makes the post worth reading is the sentence near the top. Claude wrote a first version of the core request path in about a week. Getting to the point where anyone trusted it took about five months: from the first production comparisons in April to public traffic moving over in September. In the authors' words: "Verification, not generation, had become the bottleneck."

Earlier this month I wrote about a Harvard paper that found AI agents raise code output without raising finished work, because review becomes the bottleneck. This post is the same finding from the other side: a team that took the bottleneck seriously and built machinery for it. Here's what they did, a small runnable version of the core trick, and what I'd borrow.

What they migrated, and why

The API started in 2023 as Python, close to the research code around it, and at first it was "basically a request forwarder." By late 2025 every request went through validation, prompt construction, tokenization, safety classification and output handling. Traffic grew about 1,800 times between early 2024 and fall 2026, and Python's per-object overhead showed up at every step.

They tried the cautious route first. In March 2026, Rust took over parsing model output, called from Python. That saved about 8–10% CPU, but every token crossed the Python–Rust boundary three times, and the gain didn't justify the complexity. So they did the full rewrite: Python hands the request off, and Rust does everything around the model call. Public traffic moved over in September.

The post says plainly why a full rewrite became realistic: by May 2026, Claude was writing more than 80% of the code Anthropic merged. Writing the new version stopped being the expensive part. Knowing it was right became the expensive part.

Why the tests weren't enough

They had about 700 integration tests. In April the Rust version passed about 98% of them. On real production traffic, only about a quarter of requests matched what Python produced.

The post gives two reasons, and both apply to most codebases.

  • The tests were written for the old implementation. When the tests were ported, an audit found more than 100 assertions that had been quietly weakened.
  • The input space is enormous. Twenty yes-or-no options make over a million combinations. At one second per test, that's about 12 days for a single model.

Production traffic finds what tests miss. One example from the post: Python escaped certain characters in JSON tool definitions and Rust didn't, so prompts differed by a few bytes. Nothing errored, because Claude accepts almost any prompt. The model just saw slightly different input. Other differences included a 1M context limit read as 200K, a missing tool description, stripped newlines and missing usage fields.

The match rate got worse before it got better. It dropped to about 6.5% in early May, then climbed as fixes landed, and reached 99.6% by August.

Shadowing, when you can't run requests twice or read them

The standard way to prove a rewrite matches the original is shadowing: send the same live traffic through both versions and compare the results. Anthropic had three problems with the textbook version.

  1. Requests can't run twice. Each request counts against a customer's limits and bill exactly once.
  2. The model is nondeterministic. Two runs of the same prompt can differ, so a difference in output doesn't prove a bug.
  3. Nobody may read the traffic. The team couldn't look at customers' requests or replies.

Their answers are the reusable part.

  • Replay instead of re-running. Call the model once, then feed the same model output to both versions. Any difference left is in the API code, not the model.
  • Compare exactly, at every stage. Check the bytes before and after the model call at each step, because small differences don't cause errors. They just change what the model sees.
  • Record the shape of a difference, never its content. For each mismatch they stored a checkpoint: which step, which part of the prompt, the first byte that differed, and each version's length. They also stored a fingerprint: where the difference was and how big the length gap was, so records from the same bug could be grouped without anyone seeing a prompt.

Grouping matters more than it sounds. In live traffic, one common bug shows up in every request it touches, so a single bug can produce hundreds of thousands of near-identical records. A script ran every 10–30 minutes, grouped new records by fingerprint, and alerted a coordinating Claude agent only when a new kind of difference appeared.

The core trick in about 40 lines

Here's a small version of the checkpoint-and-fingerprint idea, so you can see why it works. Two versions of a prompt-building step look the same. The new one has two bugs: it stops escaping non-ASCII characters in the tool JSON, and it drops the trailing newline.

The fingerprint here is my simplification, not Anthropic's scheme. It records the stage plus the kind of byte on each side of the first difference: an escape character, a non-ASCII byte, a newline, or the end of the data. That's enough to group by cause without storing any text.

import json
from collections import Counter
from dataclasses import dataclass

# Two versions of the same prompt-building step. The new one "looks" identical,
# but it stops escaping non-ASCII text and trims the trailing newline.
def build_old(req: dict) -> bytes:
    tools = json.dumps(req["tools"], ensure_ascii=True)
    return f"{req['system']}\n{tools}\n".encode()

def build_new(req: dict) -> bytes:
    tools = json.dumps(req["tools"], ensure_ascii=False)
    return f"{req['system']}\n{tools}".encode()

@dataclass(frozen=True)
class Diff:
    stage: str
    first_diff: int   # byte offset, never the bytes themselves
    old_len: int
    new_len: int
    fingerprint: str  # groups records by likely cause, still no content

def byte_class(data: bytes, i: int) -> str:
    if i >= len(data):
        return "end"
    b = data[i]
    if b == ord("\\"):
        return "escape"
    if b >= 0x80:
        return "non-ascii"
    if b == ord("\n"):
        return "newline"
    return "text"

def compare(stage: str, old: bytes, new: bytes) -> Diff | None:
    if old == new:
        return None
    i = next((k for k, (a, b) in enumerate(zip(old, new)) if a != b), min(len(old), len(new)))
    fp = f"{stage}:{byte_class(old, i)}->{byte_class(new, i)}"
    return Diff(stage, i, len(old), len(new), fp)

requests = [
    {"system": "You are helpful.", "tools": [{"name": "search", "description": "Web search"}]},
    {"system": "You are helpful.", "tools": [{"name": "cafe", "description": "Find a café"}]},
    {"system": "Be brief.", "tools": []},
    {"system": "Réponds en français.", "tools": [{"name": "meteo", "description": "Météo"}]},
    {"system": "You are helpful.", "tools": [{"name": "menu", "description": "Crème brûlée"}]},
    {"system": "Be brief.", "tools": [{"name": "calc", "description": "Calculator"}]},
]

diffs = [d for r in requests if (d := compare("prompt", build_old(r), build_new(r)))]
print(f"matched {len(requests) - len(diffs)} of {len(requests)}")
for d in diffs:
    print(d)
print("\ngrouped by fingerprint:")
for fp, n in Counter(d.fingerprint for d in diffs).most_common():
    print(f"  {n}  {fp}")

Output:

matched 0 of 6
Diff(stage='prompt', first_diff=66, old_len=67, new_len=66, fingerprint='prompt:newline->end')
Diff(stage='prompt', first_diff=61, old_len=71, new_len=66, fingerprint='prompt:escape->non-ascii')
Diff(stage='prompt', first_diff=12, old_len=13, new_len=12, fingerprint='prompt:newline->end')
Diff(stage='prompt', first_diff=59, old_len=77, new_len=68, fingerprint='prompt:escape->non-ascii')
Diff(stage='prompt', first_diff=53, old_len=82, new_len=69, fingerprint='prompt:escape->non-ascii')
Diff(stage='prompt', first_diff=57, old_len=58, new_len=57, fingerprint='prompt:newline->end')

grouped by fingerprint:
  3  prompt:newline->end
  3  prompt:escape->non-ascii

The same thing in C#, as a .NET 10 file-based app (dotnet run Shadow.cs). The default System.Text.Json encoder escapes non-ASCII characters, so the "new" version swaps in an encoder that allows all Unicode ranges:

#:property JsonSerializerIsReflectionEnabledByDefault=true
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

// Two versions of the same prompt-building step. The new one stops escaping
// non-ASCII text and trims the trailing newline.
var escaped = new JsonSerializerOptions();  // default encoder escapes non-ASCII
var raw = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) };

byte[] BuildOld(Req r) =>
    Encoding.UTF8.GetBytes($"{r.System}\n{JsonSerializer.Serialize(r.Tools, escaped)}\n");
byte[] BuildNew(Req r) =>
    Encoding.UTF8.GetBytes($"{r.System}\n{JsonSerializer.Serialize(r.Tools, raw)}");

string ByteClass(byte[] d, int i) =>
    i >= d.Length ? "end"
    : d[i] == (byte)'\\' ? "escape"
    : d[i] >= 0x80 ? "non-ascii"
    : d[i] == (byte)'\n' ? "newline"
    : "text";

Diff? Compare(string stage, byte[] oldB, byte[] newB)
{
    if (oldB.AsSpan().SequenceEqual(newB)) return null;
    int i = oldB.AsSpan().CommonPrefixLength(newB);   // first differing byte
    return new Diff(stage, i, oldB.Length, newB.Length,
        $"{stage}:{ByteClass(oldB, i)}->{ByteClass(newB, i)}");
}

Req[] requests =
[
    new("You are helpful.", [new("search", "Web search")]),
    new("You are helpful.", [new("cafe", "Find a café")]),
    new("Be brief.", []),
    new("Réponds en français.", [new("meteo", "Météo")]),
    new("You are helpful.", [new("menu", "Crème brûlée")]),
    new("Be brief.", [new("calc", "Calculator")]),
];

var diffs = requests.Select(r => Compare("prompt", BuildOld(r), BuildNew(r)))
                    .OfType<Diff>().ToList();
Console.WriteLine($"matched {requests.Length - diffs.Count} of {requests.Length}");
diffs.ForEach(Console.WriteLine);
Console.WriteLine("\ngrouped by fingerprint:");
foreach (var g in diffs.GroupBy(d => d.Fingerprint).OrderByDescending(g => g.Count()))
    Console.WriteLine($"  {g.Count()}  {g.Key}");

record Tool(string name, string description);
record Req(string System, Tool[] Tools);
record Diff(string Stage, int FirstDiff, int OldLen, int NewLen, string Fingerprint);

Output:

matched 0 of 6
Diff { Stage = prompt, FirstDiff = 63, OldLen = 64, NewLen = 63, Fingerprint = prompt:newline->end }
Diff { Stage = prompt, FirstDiff = 58, OldLen = 68, NewLen = 63, Fingerprint = prompt:escape->non-ascii }
Diff { Stage = prompt, FirstDiff = 12, OldLen = 13, NewLen = 12, Fingerprint = prompt:newline->end }
Diff { Stage = prompt, FirstDiff = 56, OldLen = 74, NewLen = 65, Fingerprint = prompt:escape->non-ascii }
Diff { Stage = prompt, FirstDiff = 50, OldLen = 79, NewLen = 66, Fingerprint = prompt:escape->non-ascii }
Diff { Stage = prompt, FirstDiff = 54, OldLen = 55, NewLen = 54, Fingerprint = prompt:newline->end }

grouped by fingerprint:
  3  prompt:newline->end
  3  prompt:escape->non-ascii

The offsets differ between the two languages because Python's json.dumps puts spaces after separators and System.Text.Json doesn't. The grouping is identical, which is the point: six mismatches, two causes, and not a single prompt stored.

There's a second lesson in the output. Fix the escaping bug in the Python version (ensure_ascii=True in build_new), run it again, and you get:

grouped by fingerprint:
  6  prompt:newline->end

The newline bug was in all six requests the whole time. In three of them it was hidden behind the escaping bug, because only the first difference gets recorded. That's one reason a match rate can fall after a fix, like Anthropic's did in May: each fix uncovers the bug behind it.

Three loops, and where the humans sat

The other half of the post is how they set up the agents. There are three loops.

  • Inner loop: fast and local. At first, agents guessed at a cause, opened a pull request and waited hours or days for staging. The redesign gave each agent a cloud sandbox with both codebases. An input check built the prompt in both versions without calling the model, in under a second. An output check ran both versions against a fake model with scripted replies. Agents wrote their own request that triggered the bug, changed the Rust until the two versions matched, and added a test that failed before the fix and passed after.
  • Outer loop: production. Requests were logged with metadata (model, prompt caching, tools, extended thinking) but no text. Agents compared like-for-like requests and checked whether a fingerprint disappeared on builds with the fix. If it didn't, the work went back to the inner loop.
  • Memory loop: rules that outlast the conversation. Decisions were saved as notes, so later agents linked new records to known bugs instead of inventing new workarounds. A rule to "port Python's behavior exactly" led an agent to find seven more places where the port had guessed. In June, an agent read about 60 review comments and proposed rules, and an engineer approved them into CLAUDE.md. Some rules became permanent checks: tests that fail on drift, lints for repeated review issues, and a merge check that requires a matching Rust change whenever Python changes.

The human gate sat between the inner and outer loops. The post's best example is from mid-May. Agents traced the largest remaining difference to web search: production fetched the tool's description from an internal service, and Rust didn't. An agent proposed copying the text into files. That passed the local verifier, and an engineer rejected it as throwaway code. Building the real call took weeks.

The post sums it up: "a verifier can tell an agent whether the outputs matched, but not whether the fix is good enough to ship." Any verifier can be gamed. Matching outputs is the goal you measure, and a correct fix is the goal you actually want.

What I'd borrow

You don't need Anthropic's scale for most of this to apply. If you're rewriting anything with an agent's help, whether that's a service, a parser or a sync engine, here's what I'd take:

  1. Use the old system as the test oracle. If the old version still runs, it's the best specification you have, better than the docs and better than the tests. Build the harness that compares the two before you trust anything the agent writes.
  2. Make the comparison exact and staged. Compare at every step, not just the final response. The bugs that matter are often the ones that don't throw.
  3. Store the shape of a difference, not the data. A stage, an offset, two lengths and a fingerprint are enough to find and group most bugs, and privacy stops being a reason to skip shadowing.
  4. Make the agent's inner loop fast. An agent that waits a day for staging is an expensive guesser. One with a sub-second check is a tireless debugger.
  5. Write corrections down where the next session will read them. This is the same reason I keep rules in project files for my own app work: a correction you only say out loud has to be said again next time.
  6. Keep a human at the "is this the right fix" step. Agents are very good at making the number go green. Someone has to decide whether green means done.

What not to over-read

These are Anthropic's numbers for Anthropic's system, and some come from partial windows. The CPU figure covers one region, the memory figure covers all of production, and the latency figure covers Claude Code requests over about two weeks. Shadowing only verifies what traffic actually exercises: a rare path that never shows up in the comparison window isn't verified, however good the match rate looks. And the team had something most rewrites don't: a working system they could keep running beside the new one for months.

The broader point does carry over, though. When an agent can write the first version in a week, the plan for proving it right is the project. If that plan is "the tests pass", the Messages API team's 98%-of-tests, 25%-of-traffic April is what you should expect. If you're planning a migration this way, my post on changing live systems covers the patterns around it: anti-corruption layers, expand and contract, and feature flags.

Sources

  • Anthropic: Migrating our Messages API to Rust (November 25, 2026)
  • My earlier post: More Code, Not More Software
← Previous

The Setting That Sent Every Message to the Poison Queue

Next →

Who Owns the Code Your Agent Writes?

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.