Skip to content

Engineering: Rust makes bad state unrepresentable. Someone still has to design the state.

How Rust moves business rules out of validators and into types the compiler enforces, and why LLM-written Rust without senior design goes wrong.

· 7 min read

By Track49

In April we argued that when AI writes code faster, the compiler should review harder. This is the longer, more technical version of that argument.

“Rust is memory-safe” is true, and it undersells the language. Memory safety removes a class of vulnerabilities. The larger gain for business software is different: Rust lets you make the rules of your domain part of the type system, so that code which breaks them does not compile.

It also oversells something. The compiler enforces the model you give it. It does not tell you whether the model is right. That gap is where projects fail, and it is wider when an LLM writes the code.

Where invariants live today

An invariant is a rule that must always hold. Treaty shares sum to 100%. A paid claim has a payment date. A matter is not opened before the conflict check clears. Two amounts in different currencies are never added.

In most object-oriented and dynamic systems, those rules live in four places: a constructor that may or may not be called, a validator that runs on some paths, a comment, and the heads of the senior staff. Every function that receives the data has two options. It re-checks the rule, which is slow and drifts out of step. Or it trusts that someone upstream checked, which is how a ten-year-old system collects its strangest bugs.

Rust gives you a third option: put the rule in the type, check it once at the boundary, and let the compiler carry the guarantee to every call site.

1. Parse once, then trust the type

A newtype with a private field can only be built through a function you control. Every later use inherits the proof.

pub struct BasisPoints(u16);

impl BasisPoints {
    /// 0 to 10_000, i.e. 0% to 100%. The only way to build one.
    pub fn new(bp: u16) -> Option<Self> {
        (bp <= 10_000).then_some(Self(bp))
    }
}

pub struct Shares(Vec<(ReinsurerId, BasisPoints)>);

impl Shares {
    /// The only way to build a `Shares`: lines that total exactly 100%.
    pub fn new(lines: Vec<(ReinsurerId, BasisPoints)>) -> Result<Self, SharesError> {
        let total: u32 = lines.iter().map(|(_, bp)| u32::from(bp.0)).sum();
        if total == 10_000 {
            Ok(Self(lines))
        } else {
            Err(SharesError::Total(total))
        }
    }
}

Any function that takes &Shares knows the lines sum to 100%. It has no validator to call and no comment to read. The check happens once, where untrusted data enters, and a Shares that totals 150% cannot exist anywhere in the program.

2. Let each state carry exactly its own data

The classic schema for a workflow is a status column plus a set of nullable fields. Five nullable fields allow 32 combinations per status. A handful of them are valid. The rest are bugs waiting for a code path.

enum Claim {
    Reported { reported_on: Date },
    Assessed { reported_on: Date, reserve: Money<Usd> },
    Paid     { reported_on: Date, amount: Money<Usd>, paid_on: Date },
    Denied   { reported_on: Date, reason: DenialReason },
}

A paid claim without a payment date is not a validation error here. It is a value that cannot be written. And because match must be exhaustive, adding a state such as Reopened makes the compiler list every function that now has to decide what reopening means, provided nobody wrote a catch-all _ arm. That is worth a lint (clippy::wildcard_enum_match_arm).

3. Make the units part of the type

Money is an integer of minor units plus a currency. If the currency is a type parameter, mixing currencies is a compile error, not a reconciliation finding.

use std::marker::PhantomData;
use std::ops::Add;

pub struct Usd;
pub struct Eur;

pub struct Money<C> { minor: i64, currency: PhantomData<C> }

impl<C> Add for Money<C> {
    type Output = Money<C>;
    fn add(self, other: Money<C>) -> Money<C> {
        // Real code uses checked arithmetic and returns a Result.
        Money { minor: self.minor + other.minor, currency: PhantomData }
    }
}

// let total = usd_fee + eur_fee;  // error[E0308]: mismatched types

PhantomData costs nothing at run time. The currency exists only for the compiler, which is exactly where you want it. Conversion becomes an explicit function that takes a rate and a timestamp, so it shows up in review and in the audit trail.

4. Turn process rules into proof tokens

Some rules are about order: this step happens only after that one. Rust can encode “only after” as a value that only the earlier step can create.

mod conflicts {
    /// Proof that this client passed a conflict check. The private field
    /// means no other module can construct one, and the proof carries the
    /// client it cleared; it is not `Clone`, so it is spent once.
    pub struct Cleared { client: Client }

    impl Cleared {
        pub fn client(&self) -> &Client { &self.client }
    }

    pub fn check(client: Client, parties: &[Party]) -> Result<Cleared, Conflict> {
        // ...search, then:
        Ok(Cleared { client })
    }
}

pub fn open_matter(cleared: conflicts::Cleared) -> Matter {
    // There is no code path to this line without a passed check for this
    // client, and a clearance for one client cannot open a matter for another.
}

The same pattern, called typestate, gives an order the types Order<Draft> and Order<Approved>. approve(self) consumes the draft and returns the approved order, so the old value cannot be used again. A function that releases funds takes only Order<Approved>. A missing step is not a code-review comment. The program does not build.

5. Ownership makes invariants survive concurrency

An invariant that holds in one thread can break when two threads touch the same data. Rust’s borrowing rules allow either one writer or many readers, never both at once. So no other code can observe a value halfway through a write. Send and Sync extend the same rule across threads: if a type is not safe to share, sharing it does not compile. Data races, the bugs that appear once a month under load and never in staging, become build errors. Higher-level races, such as check-then-act across two locks, and deadlocks are still possible, which is one more reason the ownership design matters.

Errors follow the same idea. A Rust function that can fail returns Result<T, E>, and E is usually an enum of the specific ways it can fail. Failure is part of the signature, the caller must handle it, and adding a new failure mode shows every caller that ignores it. Nothing is thrown past three layers of the stack, as an exception would be.

The sharp edge

Everything above has a precondition: someone decided what the states are, which rules are invariants, where the trust boundaries sit, and who owns which data. The compiler checks your code against that model. It cannot check the model against your business.

That has two consequences people underestimate.

A wrong model is enforced just as faithfully as a right one. If you encode the claim lifecycle wrongly, the compiler defends the mistake at every call site, and changing it later touches every one of them. A loosely typed system lets a bad model leak, and people work around it; Rust holds it in place.

Early structural decisions are expensive to reverse. These include lifetimes inside core types, generics against trait objects, the ownership graph between aggregates, async boundaries, and crate and module seams. If they are made well, later features rarely need to touch them. If they are made badly, every feature fights the borrow checker. And a fight with the borrow checker is almost always a modeling problem dressed up as a syntax problem.

Why an LLM and no senior is a recipe for disaster

An LLM will write Rust that compiles, and that is the risk. Faced with a borrow-checker error, it takes the shortest path to green:

  • .clone() everywhere, so ownership is never actually designed;
  • Arc<Mutex<…>> around shared state, which turns a design question into a runtime lock;
  • .unwrap() on every Result, which puts the exceptions back in as panics;
  • status: String and five Option fields, the nullable-column schema rebuilt in a new language;
  • f64 for money;
  • and, when it is stuck, unsafe.

Ask it to port an object-oriented system and it transliterates. Class hierarchies become trait Entity with Box<dyn Entity>, getters and setters survive intact, inheritance is faked with Deref, and the business rules stay where they were: spread across services, callbacks, ORM hooks and database triggers. The output passes the compiler and the tests that came with it. It has none of the guarantees this article describes, because none of them were designed. You end up with the old system’s model at Rust’s cost of change.

The same holds for a capable team, or a capable solo developer, new to the language and leaning on an assistant. The model writes the syntax. Nobody has decided the invariants.

Moving business logic out of an old system is extraction rather than translation. You find the rules, including the ones that live only in a trigger or in someone’s memory. You name the states and write down the transitions. You decide which rules belong in types, which in pure functions, and which in the database. Then you check that every behavior the business relies on survives. That work needs people who know both the domain and the language well enough to know which guarantees are worth their cost.

Where the senior time goes

At the outset: the domain model, the state machines, the error taxonomy, the trust boundaries, the module seams, and a written policy on unsafe and panics. This is a few weeks of work that decides the next five years.

In design and implementation: reviewing types more than lines. A pull request that adds a variant, a newtype or a proof token deserves more attention than one that adds a hundred lines of logic, because the types are the specification.

Once those rails exist, the rest gets faster. Junior engineers and AI assistants work inside a model that rejects most of their mistakes at compile time. In that setting AI-assisted Rust is excellent. Without the rails, it is a fast way to build a system that is hard to change and only looks safe.

Rust is a very good tool for encoding a complicated business, provided the people doing the encoding understand both the business and the language.

  • rust
  • engineering
  • ai
  • design