Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: Bank Account Simulator

Build a bank account model in F#: records for state, a union for commands and events, validation with Result, applying events with fold, and an agent that serializes access, step by step.

This project pulls together the previous chapters: records and unions for the domain, Result for rules that can fail, pattern matching to apply changes, List.fold to replay history and an agent to make it safe for concurrent callers. We build a small bank account the way many F# systems are built: commands are requests, events are facts, and the balance is computed from the events.

Because F# does not run in the in-page editor, the F# code here is read-only and its outputs are described in comments you can check by running dotnet fsi. A C# version of the core logic runs in the editor so you can see the behaviour live.

Step 1: the model

FSHARP
type Money = decimal

type Account =
    { Id: string
      Owner: string
      Balance: Money
      IsClosed: bool }

type Command =
    | Deposit of Money
    | Withdraw of Money
    | Close

type Event =
    | Deposited of Money
    | Withdrawn of Money
    | Closed

type BankError =
    | InvalidAmount of Money
    | InsufficientFunds of balance: Money * requested: Money
    | AccountClosed
    | BalanceNotZero of Money

The three types mirror the story. A Command says what someone wants, an Event says what happened and BankError lists every way a request can be refused. Because errors are a union, a caller can show a specific message, and adding a new rule later makes every unhandled match warn (Discriminated Unions).

Step 2: deciding

The decide function applies the rules. It takes the current account and a command and returns events or an error. It never changes anything:

FSHARP
let decide (account: Account) (command: Command) : Result<Event list, BankError> =
    if account.IsClosed then
        Error AccountClosed
    else
        match command with
        | Deposit amount when amount <= 0m -> Error (InvalidAmount amount)
        | Deposit amount -> Ok [ Deposited amount ]
        | Withdraw amount when amount <= 0m -> Error (InvalidAmount amount)
        | Withdraw amount when amount > account.Balance ->
            Error (InsufficientFunds (account.Balance, amount))
        | Withdraw amount -> Ok [ Withdrawn amount ]
        | Close when account.Balance <> 0m -> Error (BalanceNotZero account.Balance)
        | Close -> Ok [ Closed ]

Guards run top to bottom, so the invalid-amount checks come before the balance check. A pure function like this is a pleasure to test: no database, no mocks (Testing F# Code).

Step 3: evolving

The evolve function applies an event to an account and returns the next one:

FSHARP
let evolve (account: Account) (event: Event) : Account =
    match event with
    | Deposited amount -> { account with Balance = account.Balance + amount }
    | Withdrawn amount -> { account with Balance = account.Balance - amount }
    | Closed -> { account with IsClosed = true }

Events never fail: all validation happened in decide. To rebuild an account from history, fold the events over a starting value:

FSHARP
let openAccount id owner = { Id = id; Owner = owner; Balance = 0m; IsClosed = false }

let replay events = events |> List.fold evolve (openAccount "A-1" "Ada")
flowchart LR
    C["Command"] --> D["decide<br/>(rules)"]
    D -->|Ok events| E["evolve<br/>(apply)"]
    D -->|Error| R["BankError"]
    E --> S["new Account"]
    S -->|"next command"| D

Every request goes through decide first; only successful decisions reach evolve.

A handy combinator runs both steps:

FSHARP
let execute account command =
    decide account command
    |> Result.map (fun events -> events, List.fold evolve account events)

Try it in FSI:

FSHARP
let acct = openAccount "A-1" "Ada"
execute acct (Deposit 100m)
// Ok ([Deposited 100M], { Id = "A-1"; Owner = "Ada"; Balance = 100M; IsClosed = false })
execute acct (Withdraw 50m)
// Error (InsufficientFunds (0M, 50M))
C# C# version of decide and evolve

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 Console.ReadLine()), it gets the next line from this box.

Step 4: one account, many callers

If two web requests withdraw from the same account at once, both could read the same balance and overdraw it. Put the account into an agent (MailboxProcessor and Agents); it handles one command at a time:

FSHARP
type AccountMsg =
    | Execute of Command * AsyncReplyChannel<Result<Account, BankError>>
    | GetBalance of AsyncReplyChannel<Money>

let startAccount id owner =
    MailboxProcessor.Start(fun inbox ->
        let rec loop account =
            async {
                match! inbox.Receive() with
                | Execute (command, reply) ->
                    match decide account command with
                    | Ok events ->
                        let next = List.fold evolve account events
                        reply.Reply (Ok next)
                        return! loop next
                    | Error e ->
                        reply.Reply (Error e)
                        return! loop account
                | GetBalance reply ->
                    reply.Reply account.Balance
                    return! loop account
            }
        loop (openAccount id owner))

let agent = startAccount "A-1" "Ada"
let result = agent.PostAndAsyncReply(fun ch -> Execute (Deposit 50m, ch)) |> Async.RunSynchronously

The agent is the only holder of the state, so even a thousand concurrent withdrawals cannot corrupt the balance: each runs decide against the latest account.

Ideas to extend it

  1. Add Transfer of toAccount: string * Money and a bank that coordinates two agents.
  2. Store the event list in a file (JSON via System.Text.Json) and rebuild each account on startup with replay.
  3. Add an overdraft limit as a field of Account and change one when guard.
  4. Write FsCheck properties: "the balance is never negative" and "replaying the events gives the same account".
  5. Render a statement with List.scan evolve to show the balance after each event.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is decide a pure function?

    decide takes an account and a command and returns a value, so it is easy to test.
  2. 2. What does List.fold evolve account events do?

    fold threads the account through evolve once per event.
  3. 3. Why wrap the account in an agent?

    An agent serialises access without locks, which prevents overdrawing by race.
  4. 4. Which type lists every reason a request may be refused?

    BankError is the union of failures, so callers can match on specific cases.

Summary

  • Model with records and unions: Account, Command, Event, BankError.
  • decide validates (returns Result), evolve applies events, fold replays history.
  • An agent protects the account from concurrent access without locks.
  • The same design extends to storage, transfers and property-based tests.

Next: Project: Expression Evaluator