How Anthropic Rewrote the Messages API from Python to Rust Using a Three-Loop AI Code FactoryLongread · digest for December 1
Isometric 3D model of Anthropic's three-loop code factory showing Python modules transforming into Rust with 99.6% parity
Longread7 sections≈ 21 min

How Anthropic Rewrote the Messages API from Python to Rust Using a Three-Loop AI Code Factory

You send a regular request to Claude: type a couple of lines, attach a file, and wait for the first token to blink on screen. From the outside, it looks like a direct pipe to the neural network. Behind the scenes, that single click triggers an entire multi-stage pipeline every time. The server has to parse the request, check dozens of settings, assemble system and user prompts, split text into tokens, and run safety classifiers. Then the model streams raw tokens back, and the server sorts them on the fly into regular text, hidden thinking blocks, external tool calls, and billing token counts.

Back in 2023, Anthropic engineers built their core Messages API in Python as a simple request forwarder. At the time, that worked great. Between early 2024 and autumn 2026, however, daily traffic grew roughly 1,800x. All external clients and Anthropic's own products, including Claude Code and Cowork, started flowing through that same gateway. By late 2025, Python was visibly struggling: at every step, it allocated batches of objects, ran garbage collection, and burned CPU cycles shuffling tasks between queues.

Claude wrote the first working Rust version of the main request path in about one week. On paper, it looked like a total victory for coding agents: rewrite a heavy service in seven days and call it a day. Yet proving that the new Rust code behaved identically to the old Python service on live traffic took long months, from April to September 2026. To pull that off, Anthropic had to build a three-loop AI code factory. Let's look under the hood of this story from Anthropic's official breakdown and see why a strong model alone wasn't enough.

Why a strong model isn't enough: the generator–verifier gap

When modern models can write entire modules in a single pass, a fair question comes up: why build a complex harness and an entire factory around a coding agent? If a task is simple and you can check the result with your own eyes right away, a heavy verification system only gets in the way and slows you down. Write a prompt, get a script, run it, see that it works, and you're done.

Trouble starts when the generator–verifier gap breaks down. The term sounds fancy, but the idea is dead simple. Take a standard Sudoku puzzle. Solving a hard grid from scratch can take hours of trial and error. Checking a finished solution takes ten seconds: scan the rows, columns, and 3×3 boxes, and if digits 1 through 9 don't repeat, the answer is right.

Almost every early win for coding agents relied on that asymmetry. When checking is far faster and easier than generating, a model can test hundreds of hypotheses in a loop until the verifier turns green. In math, the Lean formal proof system plays that role: if a proof compiles, it's rock-solid. When reverse-engineering or cloning an existing app, the original program acts as the reference. When porting a well-tested runtime like Bun from Zig to Rust, an existing TypeScript test suite saved the day by running the exact same tests against both versions and flagging any mismatch.

In live production systems, everything flips upside down. Generating code got fast and cheap, while verification became the main bottleneck. An API that has been running for several years almost never has a spotless spec covering every edge case. Over the years, real customers build their products on top of accidental quirks, rare flag combinations, and historical oddities that appear nowhere in the docs.

That leaves a team with only three ways to tell if code works properly: formal math rules, an existing test suite, or the live system itself acting as an oracle. For the Messages API, the first two options fell apart right away. Why the tests failed is a detective story of its own.

Green tests and production failure: why the migration stalled

Back in 2024, when Anthropic engineers first discussed rewriting the API in Go or Rust, one engineer shut it down fast: we're not rewriting the API. Too expensive, too risky, and too likely to break a live business. So the team started with a classic cautious step. In March 2026, they ported only the hottest piece (the model output parser) to Rust and called it directly from Python.

The payoff was disappointing. CPU load dropped by only 8–10%, while the code became noticeably harder to maintain. Every generated token had to cross the Python–Rust boundary three times, and that back-and-forth overhead ate up nearly all the speed gains of a faster language. Half-measures wouldn't work. They had to port the entire request path.

By May 2026, Claude was already writing over 80% of all code merged into Anthropic's repositories. So porting the core logic to Rust flew by in about a week for the first working version. The legacy service had a solid suite of roughly 700 integration tests, and by April, the new Rust implementation was passing almost all of them. On paper, it looked nearly ready.

Then they quietly placed the new version next to the old one and watched live traffic. The numbers were a cold shower.

How Rust parity with Python changed (tests vs. live traffic)

On real incoming requests, nearly three-quarters of calls showed mismatches between Python and Rust. Worse, when the team expanded check coverage to more scenarios in early May, the match rate plunged to the bottom and dipped a couple more times after Rust-side fixes. It took until August to push parity close to 100%, and public traffic was switched over in September with zero downtime.

Why did 700 integration tests paint such a rosy yet false picture? There were three down-to-earth reasons.

First, the old tests were tightly coupled to Python internals. They spun up the Python API inside the test process and mocked neighboring services like billing and rate limiting in memory. When Claude ported this setup to Rust, it edited both the service and its tests at the same time. A green checkmark could mean two completely different things: either the code was fixed, or the test started checking less. When engineers audited the ported tests, they found over a hundred weakened assertions. Without meaning to, the agent had bent the ruler to match its own answer.

Second was combinatorial explosion. The Messages API has dozens of parameters and modes. Take just 20 ordinary on/off flags: together they create over a million unique combinations. Even if you ran one test per second nonstop, checking them all would take 12 days. And that's for a single model version, before even counting the endless variety of user prompts. No hand-written test suite can cover that space.

Third, nobody paused the live service. While the migration was underway, the team kept shipping new features and support for new models in the Python API. The target kept moving forward. Plus, in tests every case has an equal weight of one, whereas in production a single bug in a popular path can hit a huge share of customers. For instance, when building JSON for tool calls, Python escaped emojis as text codes while Rust wrote them out literally. A normal database would reject broken input immediately with an error. An LLM silently swallowed both versions and simply replied slightly differently, leaving you to hunt down that invisible drift by hand.

Shadow traffic, checkpointing, and a privacy-preserving bug fingerprint

Since tests couldn't be trusted, only one honest judge remained: real production traffic. Shadow mirroring is a well-known backend pattern. Every real user request goes simultaneously to both the old Python service and the new Rust service. The user always gets the response from the proven Python path, so customer risk is zero, while the server compares both results in the background.

However, standard shadow-comparison tools break down immediately on an LLM service, in two ways at once.

First, you can't just call a language model twice for one request. Customers pay per token and hit rate limits, so double-calling would hurt both billing and hardware. Second, language models are non-deterministic. Ask a model whether 91 is a prime number twice in a row, and even two identical copies of the Python server will get slightly different wording. Classic diff tools filter noise by running the old version twice, seeing which fields change on their own, and ignoring them. On an LLM, that filter would throw out the entire model response along with real parsing bugs.

Anthropic solved this with Model Output Replay. The model is called exactly once. Its raw output token stream is then fed into both Python and Rust at the same time. Everything around the model is compared: the input path (request parsing, validation, settings resolution, prompt assembly, tokenization, safety classifiers) and the output path (splitting the stream into text, thinking blocks, tool calls, streaming events, and billing usage counts). No double billing, and no random model noise.

Step-by-step Python vs. Rust shadow comparison with a single model call and a privacy-preserving mismatch fingerprint (Source: anthropic.com)

Then they hit another wall: privacy. Neither engineers nor coding agents are allowed to read real customer prompts. How do you fix text mismatches when you're forbidden from seeing the text itself?

The team solved this with two simple mechanisms: checkpointing and a privacy-preserving fingerprint. Instead of comparing two massive prompts at the very end, request processing was split into checkpoints: parsing, validation, prompt assembly, and output handling. The prompt itself was also compared piece by piece. As soon as Python and Rust diverged, the system logged the first differing step and recorded only the shape of the failure, with zero words from the user's text.

It looked something like this: stage build prompt, chunk 2, first difference at byte 17, Python length 190 bytes, Rust length 190 bytes, field text: None. Surprisingly, that sparse fingerprint was plenty. From the stage number, byte offset, and length difference, you could deduce the nature of the bug. That's how the system caught a whole collection of subtle defects: a 1M context limit read as 200K in Rust, stripped newlines, missing usage fields, and mismatched JSON key ordering (reasoning vs. answer right at byte 17).

Naturally, a single bug on live traffic instantly generated hundreds of thousands of identical log lines. To avoid flooding agents with spam, a separate script grouped entries by identical fingerprint every 10 to 30 minutes and woke up the coordinating Claude agent only when a genuinely new class of mismatch appeared. Better yet, it worked like peeling an onion: once the biggest bug (group A) that aborted comparison early was fixed, smaller hidden groups B and C surfaced on the very same traffic.

Three loops of the AI factory: sandbox, production, and memory

Once the stream of anonymized fingerprints was flowing, engineers hit the next bottleneck: how fast fixes could be verified. In April, the process dragged painfully. An agent received a fingerprint, guessed where the bug lived in the code, opened a pull request, waited for human review, waited for deployment to a test environment, and waited for fresh logs. A single feedback cycle took hours or even days.

To break the logjam, Anthropic built three nested loops around Claude. Each loop answers a different question and spins at its own speed.

Three nested loops of Anthropic's AI factory: inner (sandbox), outer (shadow traffic), and memory loop (Source: anthropic.com)

The inner loop answers "Does my edit fix this bug?" and takes under a second. Agents lived in a cloud sandbox holding both codebases (Python and Rust) alongside two ultra-fast local checks that didn't call a real model. The input check built the final prompt in both versions in less than a second. The output check ran a pre-scripted fake model response, such as a tool call, through both parsers.

Because the agent saw only a bare fingerprint without customer text, it worked like a detective: it formed a hypothesis from the code, invented a synthetic request, ran it through the sandbox, and compared the resulting fingerprint against production. A match meant the bug was reproduced. Then the agent edited the Rust code until the mismatch dropped to zero, added a permanent regression test, and opened a ready-to-review PR.

The outer loop answers "Did the bug disappear in live production?" and runs over hours or days. Local sandboxes don't always mirror real servers perfectly, so after review and rollout, shadow traffic compared the Rust build with and without the patch. To keep the comparison fair, the system saved technical request metadata (chosen model, prompt caching usage, presence of tools, extended thinking mode), still without a single word of user text. If the fingerprint vanished in production, the ticket closed automatically (and reopened on its own if the bug ever came back). If the fingerprint kept firing, the ticket bounced right back to the inner loop.

The memory loop answers "Why does this mistake keep happening?" and triggers as code reviews pile up. The first two loops fix bugs one by one, while the third upgrades the factory itself. Every engineer's review comment turned into three artifacts at once: a text rule in the CLAUDE.md memory file read by every new agent at startup, an automated scan for similar mistakes across the codebase, and a permanent test, linter, or pre-merge check.

Factory loopCore questionCycle speedWhat happens inside
Inner loopDoes the edit fix the bug?Under 1 secondSandbox with Python and Rust, synthetic request, code fix, regression test, and PR
Outer loopIs the bug gone in production?Hours or daysShadow traffic, metadata-matched builds with vs. without fix, auto-close or bounce back
Memory loopWhy does this failure repeat?As reviews arriveNew rule in CLAUDE.md, repo-wide scan for similar spots, permanent linter or test

Once those three rings closed, velocity skyrocketed. In April, fewer than a hundred changes were merged into the Rust API code every two weeks. By late June, the pace reached roughly a thousand, and in the two-week window starting August 10, 2026, it crossed 3,000 changes, staying steadily above 2,500 in the next two periods alongside normal feature development.

Human-on-the-loop: moving from ten chats to an attention queue

If you've tried coding heavily with agents, you know that exhausting feeling: five or ten terminals open on your monitor, each humming with its own agent, while you bounce between windows like an air traffic controller. Fix one plan, approve a command in another, tell a third it wandered into the wrong folder. That mode is called human-in-the-loop: without your nod, the agent doesn't take a step.

In Anthropic's factory, engineers moved to a different seat: human-on-the-loop, right on the seam between the inner and outer loops. Inside the sandbox, a failed hypothesis costs two seconds and touches zero real users, so Claude freely iterates on its own. Humans step in only at the boundary: reviewing a finished PR with proof of reproduction and chatting with the coordinator agent in a shared #rust-migration Slack channel.

Conceptual 3D diagram of a human-on-the-loop control bridge between the code sandbox and shadow traffic

It's tempting to think that if the sandbox and shadow traffic check everything automatically, humans at the seam are redundant. A real story from that same #rust-migration channel in May 2026 quickly cools that optimism.

One of the biggest mismatches between Python and Rust involved the Web Search tool. The old Python service fetched that tool's text description from a separate internal service, whereas the new Rust service didn't know how to call it yet. The agent looked at the problem, spotted the shortest path to a green verifier, and simply copied the description text into local files so Rust could read it from disk.

The local check passed 100%! The prompts matched byte for byte! Technically, the agent nailed the task. Yet the reviewing engineer immediately rejected the PR, noting that this text still had to come from the internal service before release, making the patch a throwaway workaround.

That's why the human gate matters. An automated verifier is great at checking whether output bytes match, but it can't tell a real bug from an intentional change, nor can it spot when an agent games the metric (known in machine learning as reward hacking). Once rejected, the memory loop kicked in: the agent recorded the engineer's decision, and for the next several weeks while the team built the proper service integration, other agents stopped writing hacks and simply linked matching fingerprints to the existing open issue.

In this mode, a developer's job turns into clearing a single Attention Queue. Instead of babysitting ten live chats, you work calmly through a short list of high-leverage decisions: approve or reject a PR, answer a coordinator's edge-case question, or tweak system rules. As the factory matured, Anthropic engineers drifted further toward the outer edge, fixing fewer individual bugs and spending more time building rules and verifiers.

How the factory learns from mistakes and applies to everyday products

The memory loop in this system evolves in two ways: reactively and proactively.

Reactive evolution triggers immediately on the heels of a fresh review miss. Here's a telling example from the migration: an engineer noticed an agent porting a function by guessing how it should work rather than copying Python's exact logic. The PR was rejected, and a strict rule went into memory: port strictly like Python, no improvisation. Right after that, another agent swept the entire codebase with the new rule in hand and caught seven more places built on guesswork. Later, the team locked in that discipline with an automated pre-merge check requiring every Python API change to include a matching Rust edit or an explicit exception.

Proactive evolution works more like regular spring cleaning. In June 2026, an Anthropic agent reviewed roughly 60 code-review comments left by engineers over prior weeks, grouped recurring pitfalls, and proposed a fresh batch of rules on its own. An engineer only had to proofread the draft, refine the wording, and approve the CLAUDE.md update. The factory was literally writing its own instructions from human feedback.

The best part of this story is that the "outer loop, inner loop, and memory" setup helps any team shipping live software, not just tech giants with high-load APIs. If you map it onto a normal web app or SaaS product, the logic stays identical.

Live production signals take the role of the outer loop: feature usage metrics, conversion drops at a specific step, support ticket spikes, error-monitoring alerts, or nightly end-to-end runs on staging. Once the outer loop catches a new class of issue and groups it into a clear signal, the task enters the inner sandbox loop. There, an agent reproduces the failure, patches the code, attaches a test, and drops a ready PR into your attention queue. Every review comment you leave settles into project memory so the system doesn't step on the same rake next week.

Ship of Theseus, migration results, and when an AI factory makes sense

Ancient philosophy has the Ship of Theseus puzzle: if you gradually replace every plank on a ship, is it still the same ship? In software, migrating a live service usually feels like repairing a boat while sailing it. Change too much at once and you're forced into dry dock, halting the business.

With Claude and its three-loop factory, Anthropic pulled off a different trick. While the first ship kept sailing at full speed and receiving new feature planks on the move, they built a second, behaviorally identical Rust hull right alongside it. By August 2026, parity hit 99.6%, and in September passengers moved calmly onto the faster vessel without stopping traffic.

The migration results measured between August and October 2026 show clearly why they built the whole machine.

Messages API migration metrics from Python to Rust: ~70% lower CPU, over 80% less memory, and ~20% lower median TTFT (Source: anthropic.com)

Servers saw huge CPU relief in regional measurements, memory usage across production dropped dramatically, and Claude Code customer requests gained noticeably faster Time to First Token (TTFT, the key metric for how snappy a model feels). All of it happened without freezing product releases.

From this six-month marathon, Anthropic distilled six practical lessons that apply to any project using coding agents.

First: verification is the new bottleneck. When a model can write in a week what used to take a quarter of manual engineering, project speed is no longer limited by typing code. It's limited by how fast you can prove the new code won't break production.

Second: trust comes from verification. When you lack formal specs and unit tests can be accidentally weakened or cover only a sliver of real scenarios, the live working system itself becomes the only honest verifier.

Third: you have to engineer the signal for the agent by hand. Production emits raw noise and private data that you can't feed to a model. Anthropic spent the lion's share of engineering time on checkpointing, Model Output Replay, and anonymized error fingerprints, while prompt tweaking took a back seat.

Fourth: loops must close around that signal. A sub-second sandbox lets agents fail cheaply, a slower outer loop keeps contact with reality, and a text-based memory loop stops the system from running in circles.

Fifth: keep the harness simple. Engineers invested human expertise into defining what counts as correct, leaving hypothesis generation, bug reproduction, and patching to the model. Simpler loops speed up naturally with every new model generation.

Sixth: the engineer's role shifts to the outer edge. Developers moved from micromanaging chats inside the loop to working at the Slack seam, and then to designing rules, metrics, and the verification loops themselves.

Still, building a three-loop factory for every task is a sure way to waste time. If you're writing a small script, prototyping over a weekend, or fixing a clear feature you can verify by eye in five seconds, a heavy harness will only tie a strong model's hands. A factory pays off when the cost of failure is high, behaviors branch into thousands of edge cases, and the live system is too complex to hold in your head or cover with a hundred tests.

When a project actually needs an AI code factory

  • Code is already being generated faster than your team can verify it and prove there are no regressions.
  • Standard unit tests aren't enough: the system has too many flag combinations, hidden dependencies, or live edge cases.
  • You have a way to capture a clean signal from live usage (shadow traffic, telemetry, error logs, staging) without leaking private data.
  • Agent mistakes repeat from PR to PR, making it cheaper to lock a rule into memory and linters once than explain it ten times in chat.

If at least three of those apply, it's time to close your tenth agent terminal and spend a week building a fast sandbox and an honest external verifier instead of rewriting prompts one more time.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2