I Built a Sub-Millisecond Settlement Engine in Rust From Scratch

Leader ●1 ●6 ●21
calendar_today ago • schedule4 min read

If you have ever operated a tech consultancy, software export agency, or remote engineering team in an emerging market (like Bangladesh, Pakistan, Vietnam, or Nigeria), you are painfully familiar with international settlement friction.

A client sends $10,000 via wire from New York or Frankfurt. What follows is a multi-day waiting game:

  1. The funds bounce across 2 to 4 intermediary correspondent banks.
  2. 3 to 5 business days elapse.
  3. By the time the funds arrive in your domestic bank account, $300 to $700 has been deducted in intermediary fees, correspondent charges, and opaque foreign exchange spreads.

In regions where global aggregators like Stripe do not offer local merchant accounts, this friction directly drains economic output.

Most people blame local banking inefficiency. But looking into the technical plumbing, the bottleneck is architectural. Legacy interbank networks were designed in the 1970s for batch messaging, not atomic settlement.

Over the past few months, I set out to build a clean, sovereign core engine from first principles in Rust: PaySwitch.

Here is a breakdown of the core architectural decisions.


1. Zero Float Loss: The Integer Constraint

In conventional web development, developers frequently store monetary amounts as f64 or float. In high-throughput financial switching, floating-point arithmetic is a disaster due to IEEE 754 non-associative rounding errors:

0.1 + 0.2 != 0.3

In PaySwitch, floating-point types are strictly banned across all calculation paths. Every currency balance, fee, and foreign exchange conversion is represented in 128-bit unsigned atomic integer units (cents, pence, poisha):

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Amount(pub u128);

For foreign exchange conversions, exchange rates are computed using integer ratios rather than decimal multipliers:

// Atomic conversion: Net = (Source * RateNumerator) / RateDenominator
let target_amount = (net_source * self.rate_numerator) / self.rate_denominator;

This guarantees mathematical precision down to the single atomic unit, with zero rounding drift over millions of transactions.


2. Invariant Conservation in Double-Entry Accounting

Financial ledgers must uphold one fundamental law: money cannot appear or disappear. Every transfer must balance debit and credit legs identically:

\[\sum \Delta \text{Debits} \equiv \sum \Delta \text{Credits}\]

In PaySwitch, transfers are atomic memory operations that execute only after strict precondition checks:

pub fn execute_transfer(
    &self,
    debit_account_id: Uuid,
    credit_account_id: Uuid,
    amount: Amount,
    currency: Currency,
) -> Result<Transfer, PaySwitchError> {
    if debit_account_id == credit_account_id {
        return Err(PaySwitchError::IdenticalAccounts(debit_account_id));
    }

    let mut accounts = self.accounts.write();

    // 1. Verify debit account balance and currency
    let debit_account = accounts.get(&debit_account_id)
        .ok_or(PaySwitchError::AccountNotFound(debit_account_id))?;
    
    if debit_account.currency != currency {
        return Err(PaySwitchError::CurrencyMismatch(
            debit_account.currency.to_string(), currency.to_string()
        ));
    }
    if debit_account.available_balance().0 < amount.0 {
        return Err(PaySwitchError::InsufficientFunds(
            debit_account_id, amount.0, debit_account.available_balance().0
        ));
    }

    // 2. Verify credit account
    let credit_account = accounts.get(&credit_account_id)
        .ok_or(PaySwitchError::AccountNotFound(credit_account_id))?;
    
    if credit_account.currency != currency {
        return Err(PaySwitchError::CurrencyMismatch(
            credit_account.currency.to_string(), currency.to_string()
        ));
    }

    // 3. Atomically apply mutation
    accounts.get_mut(&debit_account_id).unwrap().settled_balance.0 -= amount.0;
    accounts.get_mut(&credit_account_id).unwrap().settled_balance.0 += amount.0;

    Ok(...)
}

3. Tamper-Evident SHA-256 Merkle Chaining

In conventional databases, an insider with root access can modify a balance row in a database table without leaving a cryptographic trace.

To prevent this, PaySwitch chains every transfer cryptographically:

let mut hasher = Sha256::new();
hasher.update(&prev_hash);
hasher.update(transfer_id.as_bytes());
hasher.update(debit_account_id.as_bytes());
hasher.update(credit_account_id.as_bytes());
hasher.update(&amount.0.to_be_bytes());
hasher.update(&(currency as u8).to_be_bytes());

let entry_hash: [u8; 32] = hasher.finalize().into();

Any modification to a past transfer invalidates every subsequent hash in the chain, providing instant mathematical proof of tampering.


4. Durability via Write-Ahead Log (WAL)

Holding state purely in memory provides sub-millisecond throughput, but memory is volatile. Putting PostgreSQL or MySQL in front of every transfer creates network and disk lock contention.

PaySwitch uses an append-only binary Write-Ahead Log:

  1. Before any balance mutation is applied in memory, a framed binary record is appended to disk.
  2. The record includes a 32-bit CRC checksum.
  3. On startup, the engine reads the WAL, validates checksums, and replays state.
+----------------+-------------------+--------------------+------------------------+
| Magic (4B)     | Payload Len (4B)  | CRC32 Checksum(4B) | Serialized Payload     |
| "PSWL"         | uint32_be         | uint32_be          | JSON/Binary Record     |
+----------------+-------------------+--------------------+------------------------+

5. Bridging Global to Regional Rails

A settlement switch is only useful if it talks to the outside world. PaySwitch natively includes:

  • ISO 20022: Structural support for pacs.008 (Credit Transfer) and pacs.002 (Status Report) messaging.
  • Regional Payout Rails: Payload validation for domestic clearing networks (Bangladesh Bank NPSB, BEFTN, RTGS, and instant wallet formatting for bKash and Nagad).

Open Source and Next Steps

PaySwitch is dual-licensed under GNU AGPLv3 for open-source reference and commercial terms for private banking infrastructure.

The project is live on GitHub and published on crates.io:

If you are working on sovereign payment systems, distributed consensus, or financial accounting engines, I welcome your feedback, PRs, and architectural reviews.

Want more #opensource & #architecture deep dives?

Join 5,971+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

The Sovereign Vault — A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

Comparison: Universal Import vs. Plaid/Yodlee

Pocket Portfolio - Mar 12

AAIF Hits 10 Projects. Its CTO on What to Adopt Now and the Security Gaps Left Open

Tom Smithverified - Oct 23

The Interface of Uncertainty: Designing Human-in-the-Loop

Pocket Portfolio - Mar 10
chevron_left
1.5k Points • 28 Badges
Remote • exploidus.com
9Posts
10Comments
6Connections
Founder and Principal Systems Architect at Exploidus Labs (https://exploidus.com), engineering deter... Show more

Related Jobs

Commenters (This Week)

4 comments
2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!