Python to Rust Migration Guide 2027: Hot Path First, Then Services

Max WellsMax WellsFounder of Rustify
By Max Wells11 min read

By Max Wells, updated December 3, 2026

TL;DR: A Python to Rust migration should almost never start as a rewrite. Profile first, move the one hot function into a Rust extension with PyO3 and maturin, and keep the Python API stable. Rewrite a whole service only when the per-request work itself dominates, the way Anthropic found when a partial PyO3-style move saved just 8% to 10% CPU and the full Rust request path saved about 70%.

  • Stage 1: profile, and prove the bottleneck is CPU in Python, not I/O or the database
  • Stage 2: Rust extension behind the same Python function (the Pydantic V2 model)
  • Stage 3: full service rewrite behind a stable contract, verified with shadow traffic
  • Never: line-by-line translation of a whole Python codebase in one release

Who Is This Guide For?

This guide is for Python engineers and tech leads who already have a production codebase and need a safe plan for moving part of it to Rust.

It is not a guide to learning Rust syntax. If that is where you are, start with Rust for Python developers. This guide answers a different question: you have a Python service, it costs too much or responds too slowly, and someone has proposed Rust. What should you move, in what order, and how do you know it worked?

The method below is built from teams that published their results: Pydantic, Astral, Dropbox, and Anthropic. The Rust rewrite case studies collect the wider evidence.

Should You Migrate From Python to Rust at All?

Migrate only when a profiler shows CPU-bound Python on a path that matters to users or to the cloud bill, and when optimizing the Python has stopped paying off.

Most slow Python services are not slow because of Python. They wait on a database, an external API, or a network hop, and Rust waits on those at exactly the same speed. Run a profiler on production-shaped load before writing a line of Rust.

SymptomLikely causeRust helps?
High latency, low CPUI/O, database, external callsRarely; fix queries, caching, concurrency
One function dominates CPU profilePure-Python loop, parsing, serializationYes, as an extension
CPU per request grows with payloadPer-byte or per-token work in PythonYes, possibly a full service
Memory per worker is hugePython object overhead, many processesOften
Bugs from shared mutable stateConcurrency designSometimes, via the type system
Team is two people, no Rust experienceStaffingNot yet

If your profile does not show a CPU-bound hotspot, a migration will add a second language, a second build system, and a hiring requirement without changing the user experience. Our Rust vs Python performance comparison covers where the speed difference is real.

What Are the Three Ways to Move Python Code to Rust?

There are three migration shapes, ordered by risk: a Rust extension inside Python, a Rust sidecar service, and a full Rust rewrite of the service.

1. EXTENSION (lowest risk)      2. SIDECAR                    3. FULL SERVICE (highest gain)
+------------------------+      +-----------+   RPC   +----+   +------------------------+
| Python app             |      | Python    | ------> |Rust|   | Rust service           |
|   calls parse()  ------+-+    | app       | <------ |svc |   |  request path in Rust  |
+------------------------+ |    +-----------+         +----+   +------------------------+
                           v                                    Python only routes, or
               Rust function via PyO3                           nothing at all
ShapeWhat movesTypical gainMain cost
Extension (PyO3)One hot function or library coreLarge on that functionBoundary crossings, packaging wheels
SidecarOne subsystem behind RPCIsolated scalingNetwork hop, two deployments
Full serviceThe whole request pathWhole-process CPU and memoryVerification, rollout, rebuilding libraries

Start at shape 1. Move to shape 3 only when the profile shows the remaining Python glue, not the hot function, is now the cost.

How Do You Move a Hot Path to Rust With PyO3?

Write the hot function in Rust, expose it with PyO3, build wheels with maturin, and keep the Python signature identical so callers never change.

PyO3 generates the bindings between Rust and CPython, and maturin builds and publishes the result as an ordinary Python wheel. Your Python code still imports a module and calls a function. The difference is that the function runs compiled Rust.

  1. Freeze the contract: write down the exact input and output of the Python function, including errors and edge cases.
  2. Capture real inputs: log a sample of production arguments, so tests reflect real data instead of hand-written cases.
  3. Port the logic idiomatically: use Rust types and iterators, not a line-by-line copy of the Python.
  4. Run both and compare: in tests and in a staging shadow, call the Python and Rust versions on the same input and diff the results.
  5. Switch behind a flag: route a small share of calls to Rust, then grow it, keeping the Python version as the fallback.
  6. Ship wheels for every target: build Linux, macOS, and Windows wheels in CI with maturin so nobody needs a Rust toolchain to install.

Pydantic V2 is the reference example of this shape: validation moved into pydantic-core, a Rust library, while users kept writing the same Python models, and its benchmarks report 4x to 50x faster validation than V1. Our PyO3 for Python engineers guide and maturin packaging guide cover the mechanics.

When Is a PyO3 Extension Not Enough?

An extension stops paying off when the hot data has to cross the Python and Rust boundary repeatedly, because the conversion cost eats the gain.

Anthropic's Messages API migration is the clearest public example. In March 2026 the team moved model-output parsing into Rust and called it from Python. Each output token still crossed the language boundary three times, and the change saved only 8% to 10% of CPU. Moving the full request path to Rust later delivered about 70% less CPU per request and more than 80% less memory.

Partial:  Python -> Rust parse -> Python -> Rust -> Python    per token, 3 crossings
Full:     Rust ---------------------------------------->      no crossings

Signs you have reached this point:

  • the Rust function is fast, but end-to-end CPU barely moved
  • profiles now show conversion, copying, and Python object creation around the call
  • the hot loop touches Python objects on every iteration
  • the service has a stable, well-defined external contract, such as an HTTP API

When all four are true, a full service rewrite becomes worth pricing. Our Anthropic migration breakdown shows the full timeline.

How Do You Rewrite a Python Service in Rust Safely?

Treat the Python service as the oracle: rebuild from its external contract, replay or mirror real traffic to both versions, and move users over in small slices.

This is the strangler fig pattern Martin Fowler described: the new system grows around the old one, route by route, until the old one can be removed.

                 +--> Python service (serves user) --> response A
client --> router|
                 +--> Rust service (shadow)     --> response B
                                                     |
                                           compare A vs B, log diffs
  1. Rewrite from the contract, not the code: the API, the outputs, and the side effects are what must match. Grab's Go rewrite made the same call, rewriting from the API instead of porting line by line.
  2. Shadow first: send a copy of real traffic to Rust, discard its responses, and log every difference.
  3. Compare at checkpoints, not only at the end: Anthropic compared intermediate state along the request path, so a mismatch pointed to the stage that caused it.
  4. Classify every diff: real bug, accepted improvement, or nondeterminism. Never let "close enough" become a silent policy.
  5. Cut over by slice: one endpoint, one customer tier, or one percentage at a time, with instant rollback to Python.
  6. Delete the Python path last: only after the Rust path has carried full traffic through a normal release cycle.

Tests are not enough on their own. Anthropic's Rust version passed about 98% of tests while matching Python on only about a quarter of live inputs, and it took shadow traffic to bring the match rate to 99.6%.

What Usually Breaks When Moving From Python to Rust?

The surprises are rarely the borrow checker; they are hidden Python behaviors, missing internal libraries, and blocking calls inside async code.

TrapWhy it happensMitigation
Implicit Python behaviorDict ordering, float formatting, unicode handling, None vs missingByte-level diffing of real outputs
Internal librariesAuth, config, metrics clients exist only in PythonBudget time to rebuild or wrap them
Blocking in asyncA sync client called inside Tokio stalls the runtimeUse async clients or spawn_blocking
Error shape driftRust returns a different message or status codeTreat errors as part of the contract
PackagingWheels missing for one platform break installsBuild all targets in CI with maturin
Team loadTwo languages, two toolchainsStart with volunteers and one owner

Grab reported both the internal library gap and a blocking Redis call inside async code in its Counter Service rewrite, and said the borrow checker was not the biggest hurdle. Our async Rust with Tokio guide covers the runtime side.

What Do Successful Python to Rust Migrations Look Like?

The public successes all kept a Python-facing contract stable while Rust replaced the expensive part underneath it.

  • Pydantic: same Python models, Rust validation core, 4x to 50x faster than V1 in its benchmarks.
  • Ruff: a new Rust tool replacing Python linters and formatters, which Astral says runs 10x to 100x faster than Flake8 and Black.
  • Dropbox: rebuilt the desktop sync engine, Nucleus, in Rust over about four years, driven by correctness more than speed.
  • Anthropic: rewrote the Messages API request path after a partial move fell short, with public traffic on Rust since September 2026.

For a hands-on small example, see I rewrote my Python script in Rust. For hiring and career impact, see Rust for Python developers.

Frequently Asked Questions

To migrate a Python project to Rust, profile production load first, move the single hottest CPU-bound function into a Rust extension with PyO3 and maturin while keeping its Python signature unchanged, then consider rewriting a whole service only if boundary crossings still dominate the profile. Verify every step against the Python version on real inputs, not only on unit tests. Roll out behind a flag so you can fall back to Python instantly, and delete the Python path only after Rust has carried full traffic.

Rewriting Python in Rust is worth it when a profiler shows CPU-bound Python on a user-facing or high-cost path, such as parsing, serialization, validation, or per-token streaming work, and when caching, better algorithms, and optimizing the Python itself have stopped paying off. It is rarely worth it for I/O-bound services, small teams with no Rust experience, or code whose bottleneck is a database. Pydantic and Anthropic both migrated only after measuring the cost, and both kept a stable contract for callers.

PyO3 is a Rust library that creates bindings between Rust and the CPython interpreter, used mainly to write Python extension modules in Rust and, less often, to embed a Python interpreter inside a Rust program so the two languages can share data and call each other. Combined with maturin, which builds and publishes the result as a standard wheel, it lets Python code import compiled Rust functions like ordinary modules. That is how pydantic-core ships its Rust validation engine to Python users.

AI coding agents can produce a working first Rust version of Python code quickly, and Anthropic reports that Claude wrote the first version of its Messages API request path in about a week, but a first version that compiles and passes tests is not the same as a version that behaves identically. That version passed about 98% of tests yet matched Python on only about a quarter of live inputs. Shadow traffic and output diffing brought the match rate to 99.6%.

A single PyO3 extension for one hot function often takes days to a few weeks including packaging and verification, while a full service rewrite usually takes months, because proving that the Rust version matches Python on real traffic takes longer than writing it. Anthropic began with a partial Rust move in March 2026 and moved public traffic in September 2026. Dropbox spent about four years rebuilding its sync engine. Plan the schedule around verification and rollout, not coding.

The Bottom Line

A Python to Rust migration is a sequence, not a rewrite. Measure, move the hot function behind the same Python API, and only rewrite the service when crossing the boundary has become the cost. Keep the Python version alive as the oracle until real traffic proves the Rust version matches.

Teams that follow that order get the Pydantic and Anthropic results. Teams that start with a big-bang translation usually get a second codebase and the same bill.

Keep Reading

Sources

Keep learning

Continue with a related Rust guide

Browse all articles

Want a clear path to your Rust goals?

Fill out the form

Book your event

Rustify

Apply for Rustify Program

👉 We are selective about who we work with. This call is reserved for developers serious about advancing their career with Rust.

🎯 On this 30-min diagnostic call, you will get:
  • An honest assessment of where you are and what's blocking you
  • Direct feedback on whether Bootcamp or Mentorship is the right fit for you

⚡ Not everyone is accepted: We only work with motivated professionals ready to take action.

By entering your information, you agree that your data will be stored in accordance with our terms & privacy policy

December 2026

Sun

Mon

Tue

Wed

Thu

Fri

Sat

Please fill out the form before choosing your time slot.

Ready to Land a $80k+ Rust Job in the US or Europe?