Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 132 ยท Projects

Project: Bank Account System

Build a bank in Rust in stages: a Money type, an Account trait with trait objects, typed errors, safe transfers past the borrow checker, then Rc/RefCell and Arc/Mutex variants.

A bank is a classic exercise because the rules are strict and everyone understands them: you cannot withdraw money you do not have, a transfer must never create or destroy money, and two people must not be able to spend the same dollar. Those rules map directly onto Rust's strengths. Types keep money from being mixed up with plain numbers, traits describe what every kind of account can do, Result makes every failure visible, and ownership decides who may change an account at a given moment.

We build the system in five stages: money and a single account, an Account trait with two kinds of accounts, a Bank that transfers money (and a borrow-checker error you will meet sooner or later), a single-threaded shared account with Rc<RefCell<โ€ฆ>>, and finally a multi-threaded bank with Arc and Mutex.

This is a teaching project, not banking software. Real systems use a database with transactions, audit trails, idempotency keys and decimal arithmetic rules set by regulators. The ideas below (integer money, typed errors, all-or-nothing transfers, lock ordering) are the real ones, though.

Stage 1: money and a first account

Never store money in f64. Floating-point numbers cannot represent 0.10 exactly, so sums drift (0.1 + 0.2 is not 0.3). Store whole cents in an integer, and wrap the integer in a newtype so it cannot be confused with a count or an id. The newtype also gives us a place to put formatting and checked arithmetic.

Rust Stage 1: Money, errors and one account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

What the types are doing for you:

  • Money wraps an i64 in a tuple struct. Passing a plain i64 where Money is expected is a compile error, so you cannot deposit an account id by mistake. In a real project, put Money in its own module and keep the field private so that only the constructors can create values.
  • checked_add returns None on overflow instead of wrapping around or panicking. The ? after ok_or turns that None into a proper BankError::Overflow.
  • Validation happens before any change. When withdraw returns an error, the balance is untouched. That is the property you want: a failed operation has no effect.
  • f.pad makes Display respect width and alignment, so {:>10} lines up a column of amounts.
  • The last line prints false, which is the reason we use cents.

Stage 2: a trait for all accounts

Banks have different products. A checking account may go below zero up to an overdraft limit and charges a fee at the end of the month if it is negative. A savings account pays interest and allows only a few withdrawals each month. Both can deposit, withdraw and report a balance. That shared behaviour is a trait.

We use composition for the shared parts: a Ledger holds the balance and the history of transactions, and each account type owns one. The trait then only has to express what differs, using default methods for the rest.

Rust Stage 2: the Account trait and two account kinds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This is long, so here are the main ideas.

  • A trait is a contract plus defaults. deposit and withdraw are written once in the trait, in terms of ledger_mut() and overdraft_limit(). Checking only supplies the pieces that differ (its overdraft), and Savings overrides withdraw because it must count withdrawals.
  • Box<dyn Account> lets a single Vec hold different types. The call goes through a vtable at run time (see trait objects). dyn Account works because the trait is object safe: no generic methods and no Self returned by value.
  • describe(account: &dyn Account) takes a reference to any account without caring about the box. Note account.as_ref() to go from &Box<dyn Account> to &dyn Account.
  • The supertrait fmt::Debug (trait Account: fmt::Debug) makes every account printable with {:?},, which is handy for logs and assertion messages.
  • The ledger is the source of truth. Instead of changing a balance directly, every change goes through Ledger::record, which updates the balance and appends a Transaction. You can always explain the balance by replaying the history.
  • The last println! shows the final entry, a Fee charged to the checking account because it ended the month overdrawn.

When two types repeat the same overridden method nearly line for line (look at Savings::withdraw), that is a sign the trait could expose a smaller hook. A cleaner design would add an after_withdrawal(&mut self) default method and let Savings override only that.

Stage 3: the bank and the transfer

A Bank owns the accounts and gives each one an id. Opening an account returns the new id, and every operation looks the account up by id. Because accounts are looked up, a lookup can fail, so it gets its own error: AccountNotFound.

The hard method is transfer. You must take money out of one account and put it into another, and if anything goes wrong the whole operation must have no effect. It seems natural to fetch both accounts at once. Try it with a plain map of accounts:

Rust Two mutable borrows of one map (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops you with error[E0499]: cannot borrow accounts as mutable more than once at a time. get_mut borrows the whole map mutably, not just one entry, so a second get_mut while from is alive would overlap. The compiler cannot know that keys 1 and 2 are different, and if they were the same key you would hold two &mut to one account, which is exactly what Rust forbids. (The standard library does have get_disjoint_mut for maps and slices, which checks the keys at run time; it is a fine answer when you really need two references at once.)

The simplest honest fix is to use the borrows one after another: withdraw first, then deposit, and undo the withdrawal if the deposit fails. First validate everything that can be validated up front, so that the undo is a rare safety net.

Rust Stage 3: a bank with all-or-nothing transfers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Some points worth stating out loud:

  • transfer never holds two borrows at once. self.account_mut(from)?.withdraw(amount)? is one statement, so the borrow ends at the semicolon.
  • The order is: validate, withdraw, deposit, undo on failure. Failed transfers (insufficient funds, unknown target, same account, invalid amount) leave every balance as it was. The assertion at the end checks the most important invariant: the total never changes.
  • BTreeMap keeps accounts sorted by id, so reports print in a stable order. A HashMap would print in a random order, which is fine for the bank but awkward in output.
  • The expect("refundโ€ฆ") documents a reasoning: the refund cannot fail, because we just removed that very amount from this account. If the reasoning is wrong, panicking loudly is better than silently losing money.
  • In a real bank the withdraw-then-deposit window is dangerous (a crash in between would lose the money). Databases solve this with a transaction that makes both steps atomic. Our single-threaded program has no window, because nothing else can run between the two statements.

Stage 4: one account, two owners (Rc<RefCell<โ€ฆ>>)

So far every account has exactly one owner: the bank. A joint account has two customers who both see the same balance. Single ownership cannot express that. Reference counting can: Rc<T> lets several handles share one value, and RefCell<T> allows mutation through a shared handle by checking the borrow rules at run time instead of compile time. Together, Rc<RefCell<Account>> is the single-threaded "shared and mutable" building block. See Rc and Arc and RefCell and Cell for the details.

Rust Stage 4: a joint account with Rc and RefCell (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program ends with a panic on purpose. The run prints panicked at main.rs:43:25: followed by RefCell already borrowed, and exits with code 101; line 43 is the second borrow_mut. That is the cost of RefCell: a mistake the compiler would have caught with &mut becomes a runtime failure. Use try_borrow_mut when you cannot prove it is safe, keep borrows short-lived (one statement), and never hold a Ref or RefMut across a call that might borrow the same cell again.

Rc is also single-threaded: it cannot be sent to another thread, and the compiler enforces that. For threads you need the next stage.

Stage 5: many threads (Arc<Mutex<โ€ฆ>>)

A real bank serves many customers at once. The thread-safe version of Rc<RefCell<T>> is Arc<Mutex<T>>. Arc is a reference-counted handle that is safe to share across threads, and Mutex allows one thread at a time to change what is inside. The simplest design puts the entire bank behind one lock:

Rust Stage 5a: one lock around the whole bank

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Every worker moves $1.00 from its own account to the next one, 500 times. Each account gives away 500 transfers and receives 500, and nothing runs out of money, so the final balances are always the same. Look at what the code does not do: it never reads a balance and writes it back in two separate locked sections. The check and the change happen under one lock, so no other thread can slip in between them. That mistake (a check-then-act race) is the most common bank bug in concurrent code.

One global lock is correct but slow when thousands of unrelated transfers could proceed in parallel. The refinement is one lock per account. Now a transfer needs two locks, and that opens a new danger: if thread A locks account 1 and then wants 2, while thread B locked 2 and wants 1, both wait forever. This is a deadlock. The standard cure is a global lock order: always lock the account with the lower id first.

Rust Stage 5b: a lock per account with lock ordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

What the output tells you: all 2,000 transfers completed (nobody ran out of money), and the total is still 400,000 cents. If you remove the ordering and lock from first and to second, this program can hang forever on a busy machine. The per-account balances at the end are not printed because they do not need to be deterministic in general, even though the total always is. The thing to check in concurrent code is the invariant (here: the total), not the exact interleaving.

Two details that trip people up:

  • A MutexGuard unlocks when it is dropped, at the end of transfer. Both guards live until the function returns, including on the early return Err(โ€ฆ). This is RAII (see Drop and RAII).
  • lock() returns an error if another thread panicked while holding the lock (the mutex is "poisoned"). unwrap() is acceptable in a demo; a real bank would decide deliberately what to do with a poisoned account.

Choosing between the designs

Need Tool
One owner, many kinds of accounts Box<dyn Account> in a Vec or BTreeMap
Several owners, one thread Rc<RefCell<T>>
Several owners, several threads, simple Arc<Mutex<Bank>>
Many threads, little contention Arc<Bank> with a Mutex per account and a lock order
Counters only (no multi-field invariants) atomics, see atomics
Durability and crash safety a database transaction (outside the standard library)

Ideas to extend it

  1. Add a Transaction::TransferOut/TransferIn pair to the ledger so a transfer appears in both histories.
  2. Add a Frozen flag to accounts and a BankError::AccountFrozen. Where in the trait do you check it?
  3. Replace the Money(i64) cents with a decimal rule that rounds interest to the nearest cent (half to even). Test it with amounts like $0.05 at 1.5 %.
  4. Make Bank::transfer generic over any impl Account instead of boxing. What do you lose?
  5. Write a stress test that runs 8 threads for 100,000 transfers and asserts that the total never changes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is money stored as an integer number of cents in a newtype instead of an f64?

    Binary floating point cannot represent most decimal fractions exactly, so sums drift. Integer cents are exact, and the newtype adds type safety and a place for formatting.
  2. 2. What does the compiler complain about when you call accounts.get_mut(&1) and accounts.get_mut(&2) and keep both results?

    get_mut borrows the whole map mutably. Two such borrows alive at once are rejected with E0499, since the compiler cannot know the keys differ.
  3. 3. In transfer, why is the order validate, withdraw, deposit, undo on failure?

    All-or-nothing behavior is the goal: check what you can first, and if the second step fails after the first succeeded, undo the first step.
  4. 4. What is the difference between Rc<RefCell<T>> and Arc<Mutex<T>>?

    Rc and RefCell are not thread safe (the compiler refuses to send them to threads). Arc and Mutex are, and Mutex makes threads take turns.
  5. 5. Why do both transfer calls lock the account with the lower index first?

    If one thread locks 1 then 2 while another locks 2 then 1, each may hold what the other needs. A single global order makes that cycle impossible.

Summary

  • Store money as integer cents in a newtype; use checked arithmetic and return typed errors.
  • Validate before you change anything, so failed operations have no effect.
  • A trait describes shared behavior, with default methods for the common parts; Box<dyn Trait> stores different implementations together.
  • Looking up two items in one map for mutation clashes with the borrow checker (E0499); do the steps one after another, or use a disjoint-borrow API.
  • Rc<RefCell<T>> shares mutable data on one thread and panics at run time on a conflicting borrow; Arc<Mutex<T>> does it across threads.
  • With several locks, always acquire them in one fixed order, and test the invariant (the total) rather than the interleaving.

Next: Project: A Tiny HTTP Server