Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 146 ยท Projects

Project: Bank Account Simulation

Build a bank simulation in Swift with actors, typed errors, async transfers with rollback, an audit ledger and protocol-based fee policies. Learn actor reentrancy by example, in your browser.

A bank is the textbook example for concurrency, because it is the one place where everybody understands why a bug matters. If two transfers touch the same account at the same moment and the program loses one update, money appears or disappears. In Swift 6 the language itself helps you avoid that, through actors that protect state, Sendable checking that rejects unsafe sharing, and async/await that lets many operations wait without blocking.

In this project you build a small bank: accounts with different rules, deposits, withdrawals and transfers between accounts, an audit ledger that records every movement, and a batch of transfers that run in parallel. Along the way you will see one of the subtle facts about actors, reentrancy, produce a real bug and then fix it. You should have read actors, tasks and task groups, and know protocols and typed throws.

The design

Money handling follows three rules that every serious system adopts:

  1. Never use Double for money. 0.1 + 0.2 is not 0.3 in binary floating point. We store whole cents in an Int wrapped in a Money struct.
  2. Every change is recorded. An append-only ledger lists each movement with a sequence number. The balance is the current state; the ledger is the history that explains it.
  3. Operations are all-or-nothing. A transfer takes money out of one account and puts it into another. If the second step fails, the first one must be undone.

The pieces:

TEXT
Money            a value type counting cents
BankError        everything that can go wrong (typed)
AccountPolicy    a protocol: checking and savings accounts follow different rules
Ledger           a protocol: where the history is written (here, an actor in memory)
Account (actor)  one account's balance, protected from data races
Bank (actor)     opens accounts and coordinates transfers

Nothing here talks to a real bank, of course. It is a simulation to practice concurrency. Real financial software adds durable databases, idempotency keys and much more.

Step 1: money, errors and a first actor

Start with the smallest working piece: Money, an error type, and one account as an actor. The goal of this step is to see what changes when state lives inside an actor: every access from outside needs await.

Swift Step 1: Money and an account actor

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

Three points about this first actor. owner is a let of a Sendable type, so it can be read from anywhere without await: it can never change, so there is nothing to protect. balance, in contrast, is mutable, and reading it from outside takes await because the actor might be busy. And the methods declare throws(BankError), so a caller that wraps them in do/catch receives a BankError.

The description of Money splits cents into dollars and a two-digit remainder, so 2575 cents prints as $25.75. Because the balance is Int, adding .dollars(100) and subtracting 2575 cents gives exactly 7425 cents with no rounding surprise.

Step 2: what actors protect you from

Why not simply use a class? Let us try, with the obvious code, and let the Swift 6 compiler answer:

Swift A plain class shared between tasks (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 readLine()), it gets the next line from this box.

Swift 6 refuses to compile this. The error reads passing closure as a 'sending' parameter risks causing data races between code in the current task and concurrent execution of the closure, with a note that the closure captures account, which is still accessible to the current task. This is a compile-time data race check: ten tasks could run balance -= amount at the same time on different threads, and the updates would overwrite one another. With a class, you would find that bug in production, intermittently. With Swift 6, you find it before the program starts. Changing final class Account to actor Account makes the capture legal, because actors are Sendable by construction, and every call into the actor runs one at a time.

Step 3: the reentrancy trap

Actors guarantee that only one piece of code runs inside the actor at a time. That does not mean a method runs to completion without interruption. Whenever an actor method hits an await, it suspends, and the actor is free to start another call. When the first call resumes, the world may have changed. This is reentrancy.

Here is a withdrawal that looks careful. It checks the balance, then does something asynchronous (imagine writing an audit record), then subtracts. Three tasks each try to take $60 from an account that holds $100:

Swift A check-then-await-then-act bug

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

The buggy version allows all three withdrawals and ends at -$80: each task passed the check while the balance was still 100, then slept, and only afterwards subtracted. The safe version has exactly one success. The rule to remember is simple:

Finish your state changes before you await, or re-check your assumptions after. Within a stretch of code with no await, an actor is as safe as a lock. Across an await, any assumption you made earlier may be false.

The compiler cannot catch this bug, because every line is individually legal. Reentrancy is the price of actors never blocking a thread, and the discipline is: check and change in the same synchronous stretch. The real account below follows that rule everywhere.

Step 4: protocols, a ledger and a bank

Now the complete core. Two protocols let behavior vary without a pile of if statements. An AccountPolicy captures what differs between a checking and a savings account (how low the balance may go, and what a withdrawal costs). A Ledger captures where history goes. Both protocols inherit from Sendable, because values that conform will be shared between actors.

An Account actor holds one balance. A Bank actor owns the accounts and coordinates transfers. A transfer is two steps in two different actors, so it must handle failure of the second step by refunding the first, and it must be correct even though other tasks run in between. The batch at the end sends 40 transfers around a ring of five accounts at the same time:

Swift Step 4: accounts, ledger, bank and parallel 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 readLine()), it gets the next line from this box.

Take the key parts in turn.

Protocols instead of conditions. Account never asks "is this savings?". It asks its policy for the lowest allowed balance and for the fee. Adding a "student" account means writing one struct. A Ledger is likewise a protocol: tests use MemoryLedger, and a production version could write to a database. The stored properties policy and ledger are of type any AccountPolicy and any Ledger, which are existential types, so different accounts can hold different policies.

State changes come before awaits. In deposit and withdraw the balance is updated first, and only then does the code call the ledger with await. Even though the actor is released while waiting for the ledger, the check and the change were done in one uninterrupted stretch, which is exactly the rule from step 3.

Rollback. In transfer, a failed target.deposit (here, a frozen account) triggers source.refund(amount + fee). After the failed transfer to the frozen bob, alice's balance is back where it was, and the ledger shows both the transferOut and the refund. The ledger never deletes history; a correction is a new entry.

Copy before you await. totalBalance copies the account list (Array(accounts.values)) before the loop. While one await is suspended, another task could open an account and mutate the dictionary. Iterating over a copy avoids an invalid iteration and gives a consistent snapshot of which accounts exist.

Parallel transfers. The task group creates 40 child tasks. They interleave unpredictably, but the outcome is deterministic by design: the ring transfers cannot overdraw any account, so there are no failures, every account receives and sends the same amounts in the end, and the total stays the same. Because the order is not deterministic, the program prints only the properties that must hold in every order: balances, total, number of ledger entries. That is how you test concurrent code: assert invariants, not interleavings.

When the order of events is scheduler-dependent, never print the order. Print sorted data, totals and conserved quantities. A test that depends on thread timing is a test that fails once a month.

Step 5: the complete program

The last step adds a small text interface over the bank, so you can script scenarios in the Input box. The interface follows the pattern of the to-do manager: parse a line into an operation, run it against the core, and return lines of output. Operations are async because every bank call is.

The new parts are Money(text:) to parse dollars (rejecting negative numbers and nonsense), the handle function, the statement view built from the ledger, an audit summary, and the parallel command that runs the ring batch from step 4. To save space the core types are repeated exactly as in step 4; the program below is the complete listing.

Swift Step 5: the complete bank simulation

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

The shape of handle repeats the pattern of the previous project: parse, call the core, return strings. The nested helper argument(_:) shows that a nested function can be typed-throwing too, and that it captures args and line from the enclosing scope. Note the statement command: before reading the ledger it asks the bank for the account, which throws unknownAccount for a typo instead of quietly printing an empty history.

Look at the transcript of transfer alice bob 20 after freeze bob: the error says the account is frozen, and statement alice then shows a transferOut entry directly followed by a refund entry for the same amount. The history is honest about what happened, which is exactly what an auditor wants to see.

Taking it further

  • Idempotent transfers. Give each transfer a unique id and keep the set of completed ids, so a retry after a network failure does not move the money twice.
  • Lock ordering for atomic swaps. Our transfer is atomic in outcome (refund on failure) but not isolated: for a moment, money is in neither account. If that matters, make Bank perform both steps without suspending in between, by making the account state plain data owned by the bank actor.
  • Interest. Add a protocol method monthlyInterest(on:) to AccountPolicy and a Bank.applyInterest() that processes accounts in a task group.
  • Persistence. Make LedgerEntry Codable, then rebuild all balances by replaying the ledger. This is the idea behind event sourcing.
  • Observability. Replace the in-memory ledger with one that also streams entries through an AsyncStream; the async pipeline project shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project store money as cents in an Int?

    Whole cents add up exactly. Double accumulates tiny representation errors, which is unacceptable for money.
  2. 2. What is actor reentrancy?

    Actors serialize access, but they release the actor while a method waits at an await. State may change in between.
  3. 3. How does the Account actor avoid the check-then-await-then-act bug?

    Code without an await in the middle cannot be interleaved, so check and update stay consistent.
  4. 4. What does the transfer do when the target deposit fails?

    The second step failing must undo the first. The refund is recorded as a new ledger entry, because history is append-only.
  5. 5. Why does the parallel demo print balances and totals rather than the order of transfers?

    Test concurrent code by asserting invariants that hold in every interleaving, such as conserved totals, not by relying on a specific order.

Summary

  • Represent money as integer cents in a Money value type, and make failures a typed BankError.
  • Actors protect mutable state from data races; Swift 6 rejects sharing a plain class between concurrent tasks at compile time.
  • Reentrancy means an await inside an actor method is a point where other calls can run. Make checks and changes in one synchronous stretch, and copy collections before awaiting inside a loop.
  • Protocols (AccountPolicy, Ledger) let behavior and storage vary without conditionals, and Sendable protocols can be held by actors.
  • A multi-step operation across actors needs compensation: undo the first step if the second fails, and record the correction.
  • Test concurrent code with invariants (total conserved, counts correct), never with timing or ordering.

Next: Project: Inventory and Reports