EngineeringLast verified: November 20268 min read

Rust in Production: A Guide to Moving a Fintech API from Node.js to Rust

How to plan and carry out a move of a payment validation API from Node.js to Rust: the reasons, the risks, shadow traffic, a gradual rollout, what to measure, and when to stay with Node.js.

Deep blue sculptural forms suggesting data flows
On this page

A payment validation API is often one of the first services a fintech team thinks of moving from Node.js to Rust. It sits in the path of every payment, customers notice its slowest responses, and its rules have to be exactly right. This guide goes through the move step by step: when it makes sense, how to plan it, how to run both versions side by side, what to measure, and when to leave the service where it is. Any figure below is an example; put your own measurements in its place.

The Starting Point: A Node.js Validation Service

Picture a service that checks transaction limits, fraud signals, merchant rules and account balances before a payment goes to the processor. After some years of changes, such a service may show one or more of these problems:

  • Slow outliers: the median response is fine, but garbage-collection pauses and a busy event loop show up at p99 and p99.9.
  • Memory use: each process keeps its own heap and caches, so running more processes for more CPU cores or for redundancy multiplies the memory bill.
  • CPU limits: one Node.js process runs its JavaScript on one main thread. Heavy parsing or rule evaluation blocks other requests unless it is moved to worker threads.
  • Tangled rules: shared state and long async chains make a new rule hard to add safely.

Find out which of these you have before you choose a remedy. Profile the service under real load and split the response time into its own CPU work, database and cache calls, and calls to other services. If most of the time is spent waiting, a better index or a cache will help more than a new language. Tangled rules can often be fixed in TypeScript.

The Rewrite: Axum + Tokio on Stable Rust

Start by writing down what the old service does: each rule, each edge case, each error code, each timeout and default value. The new service should give the same answers, including the odd ones that callers rely on. Improvements to the rules come later, as separate changes.

A typical set of libraries on stable Rust:

  • Axum for HTTP, with Tower middleware for timeouts, limits and tracing
  • Tokio as the async runtime
  • sqlx for database access, with SQL queries checked at compile time
  • serde and serde_json for reading and writing the payloads
  • redis-rs with a connection pool for rate limits and cached rules

Model the rules as small units that take a payment and a context and return a decision. Load the data a rule needs first and keep the rule itself free of network calls, so that it can be tested with plain values:

pub trait ValidationRule: Send + Sync {
    fn name(&self) -> &'static str;
    fn validate(&self, payment: &Payment, ctx: &RuleContext) -> Result<(), Rejection>;
}

Watch the places where the two languages differ:

  • Money: JavaScript numbers are floating point. Use integer minor units or a decimal type in Rust, and compare the rounding with the old service.
  • Missing and null: JavaScript distinguishes undefined from null. By default serde reads both a missing field and a null into None.
  • Text: string length in JavaScript counts UTF-16 code units, and len() on a Rust string counts bytes.
  • Regular expressions: the regex crate has no look-around and no backreferences, so some patterns have to be rewritten.
  • Overflow: integer arithmetic wraps around in release builds by default. Use checked operations for amounts.

Development Timeline

Plan in phases that each end with a condition:

  1. Describe and record. Document the behaviour and record requests and responses from production as a regression test. Recorded payments contain personal data and possibly card data, so mask them, limit who can read them, and set a date for deleting them.
  2. Build. Port the rules in small groups. A group is done when the recorded requests give the same answers.
  3. Load test. Test above the expected peak, with dependencies that are slow or failing as well as healthy ones.
  4. Shadow. Run the new service next to the old one on copies of live traffic.
  5. Roll out. Move real traffic in steps.
  6. Remove the old service. Put this in the plan, or you will maintain two.

A team's first Rust service takes longer, because the ownership rules and the async model have to be learned. Make sure at least two people can review the code and take the on-call shift.

Shadow Traffic and Rollout

In shadow mode the old service still answers. A copy of each request goes to the new one, and its decision is compared with the old one and then discarded. Sort the differences into bugs in the new service, bugs in the old one, and harmless ones such as the order of fields. Continue until each remaining difference has an explanation.

The shadow must have no side effects. It must not call the payment processor, send notifications or raise the counters used for rate limits and fraud checks. Give it read access and counters of its own, and send the copies asynchronously so that a slow shadow cannot delay the real answer.

Then move real traffic in steps, for example 1%, 10%, 50% and 100%. Stay at each step long enough to cover the daily peak and, if there is one, the month-end peak. Both versions share state during this time, so the keys and formats in Redis and in the database have to stay compatible. Keep each merchant on the same version during a step. Set the limits for going back in advance, make going back a routing change, and keep the Node.js service deployable until the new one has been through a full business cycle.

What to Measure

Take a baseline from the old service before the move, with the same tools and the same load.

Correctness:

  • Share of requests with the same decision and the same error code
  • Unexplained differences, which should reach zero

Latency:

  • p50, p99 and p99.9, measured at the caller, also during deployments and failures of dependencies

Resources:

  • Memory when idle and at peak, CPU time per request, number of instances, highest throughput within the latency limit

Cost:

  • Compute cost of this service alone, and the working hours for the move and for maintenance

A made-up example shows why cost needs a calculation of its own. Suppose a service costs 1,000 euros a month to run and the move takes two people three months. If the bill halved, the saving would be 6,000 euros a year, well below the cost of the work. In that case the reason for the move has to be latency, reliability or capacity.

What Makes the Difference

Three properties of Rust can help here:

1. No garbage collector. Memory is freed when values go out of scope, which takes collection pauses out of the slowest responses. Locks and slow dependencies can still cause outliers.

2. Several cores in one process. Tokio's multi-threaded runtime spreads tasks over the available cores, so one process can do the work of several Node.js processes and share one cache and one connection pool. Long calculations and blocking calls have to be kept off the runtime's threads, for example with spawn_blocking.

3. Typed parsing. serde reads JSON straight into typed structs, so an invalid payload is refused at the edge and the code behind it works with checked values.

A prototype of the busiest endpoint, tested with recorded traffic, gives a better estimate of the effect than published benchmarks.

Honest Trade-offs

Rust is not the right choice for every service.

  • Engineering time. The first Rust service takes longer to build than another Node.js service. In the meantime, changes to the old service either wait or are made twice.
  • Smaller hiring pool. There are fewer Rust developers than Node.js developers. A service that one person can maintain is a bigger risk than a slow one.
  • Two stacks. Shared libraries, build pipelines, logging and security updates now exist in two languages.

Stay with Node.js if the time goes to the database or to other services, if the rules change every week and latency is within its target, or if the team cannot keep up the Rust knowledge. Try the cheaper steps first: a newer Node.js version, worker threads, caching and connection pooling, or moving the heaviest function alone to a Rust addon.

Before You Start: A Short Checklist

  1. Record traffic before rewriting. It shows edge cases that the old code does not make obvious.

  2. Compare in shadow mode, then roll out in steps. Load tests show speed. Shadow traffic shows whether the decisions are the same.

  3. Decide in advance what counts as success. Write down the targets and the limits for going back before the first line of Rust.

Rust rules out some kinds of error at compile time: data races, use after free and null references in safe code. Wrong limits, wrong rounding and missing rules are still a matter for tests. The move pays off where the measured problem is CPU work, memory or slow outliers, and where the team wants to maintain the result for years.

If you read nothing else

  1. 01Profile first: Rust helps when CPU work, memory or garbage-collection pauses are the problem, and hardly at all when the service waits for a database.
  2. 02Record real requests and responses, then run the new service in shadow mode, without side effects, until every difference is explained.
  3. 03Roll out in steps with a way back, and measure correctness, latency, resources and cost against a baseline taken before the move.

Keep reading

Facing the same decision?

We take this kind of assessment as a paid engagement of its own — and often the answer is that you should not build anything.

Start a conversation