Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 147 ยท Projects

Project: Bank Account System

Build a bank in Go in four stages - accounts with policies and custom errors, mutex-protected balances, deadlock-free transfers using lock ordering, and an audit ledger you can replay to verify.

Money is the classic example for concurrency, because the rules are strict and mistakes are visible. A balance must never be wrong, even when a thousand customers act at the same moment. A transfer must either happen completely or not at all, and no cent may ever appear or vanish. If you can build a bank that keeps those promises, you understand the three hardest ideas of everyday Go concurrency: protecting shared state, making a multi-step operation atomic, and avoiding deadlock.

In this project you build a small bank in four stages, and each stage is a complete program. In stage 1 you model accounts with structs, an interface and custom errors, and you meet the integer-cents rule for money. In stage 2 you make balances safe for many goroutines with a mutex. In stage 3 you add a Bank with transfers, see a deadlock happen on purpose, and fix it with lock ordering. In stage 4 you add an append-only audit ledger and use it to prove that the bank's books balance after a storm of concurrent transactions.

You'll use structs, interfaces, custom errors with errors.Is and errors.As, wrapped errors, the sync package and goroutines.

The plan

Stage What you build Main Go ideas
1 Account, Policy interface, Cents, typed errors Interfaces, errors.As, errors.Is, String() methods
2 Goroutine-safe deposits and withdrawals sync.Mutex, check-then-act, atomic.Int64, data races
3 A Bank with atomic transfers Lock ordering, deadlock, error wrapping with Unwrap
4 An audit ledger, replayed to verify the books Append-only logs, invariants, sync.RWMutex

Stage 1: accounts, policies and errors

Never store money in a float64. Floating-point numbers cannot represent 0.10 exactly, so sums drift (0.1 + 0.2 is not 0.3). Banks count the smallest unit, and so will we: a Cents type based on int64. Adding a String() method lets fmt print it as $12.34, and the printing code is the only place where cents become dollars.

Accounts of different kinds follow different rules. A checking account may go below zero up to an overdraft limit; a savings account may not. Instead of two near-identical types with duplicated code, we model the rule as a small interface, a policy, and give every account one. This is composition over inheritance: Account has a Policy, and the Policy answers a single question, "what is the lowest balance you may reach?".

Errors carry information. A plain errors.New("insufficient funds") would tell a user nothing. We define:

  • ErrInvalidAmount, a sentinel error for zero or negative amounts. Callers test it with errors.Is.
  • InsufficientFundsError, a typed error with fields (account, balance, requested amount, floor) and a Shortfall() method. Callers extract it with errors.As and read the fields. The method has a pointer receiver, so the code returns &InsufficientFundsError{...}.

The report helper at the bottom shows how a caller reacts: it asks errors.As first, then errors.Is, then falls back to the error text.

Go Stage 1: accounts, policies and typed errors

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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

Follow the numbers. Alice starts with $100.00 and an overdraft of $50.00, so her lowest allowed balance is -$50.00. Withdrawing $120 takes her to -$20.00, which is allowed. Withdrawing another $40 would take her to -$60.00, so the bank refuses and Shortfall() reports the missing $10.00. Bob's savings account has no overdraft, so $30 is refused when he has $25.00. The final transfer works because Alice's -$20.00 - $25.00 = -$45.00 is still above her floor.

Design points:

  • Interfaces describe what a caller needs. Policy has two methods, and Savings and Checking satisfy it without any implements keyword. A new account type (a student account with a $10 minimum balance) is one more tiny type, and Account does not change. See interface design.
  • Savings{} is an empty struct that exists only to carry methods. It takes no memory, and its zero value is ready to use.
  • Value and pointer receivers are mixed deliberately. Policy implementations are tiny values with value receivers; Account and InsufficientFundsError use pointer receivers because they are mutated or returned by pointer. See value vs pointer receivers.
  • 1_000_000 is a numeric literal with digit separators (Go 1.13): the underscores are ignored.
  • Transfer is a trap. It withdraws and then deposits as two separate steps. If anything fails or another goroutine looks in between, money is missing for a moment. For a single goroutine that is acceptable; for a bank it is not, and it is the main thing we fix later.

Stage 2: protecting balances with a mutex

So far only one goroutine touches the accounts. A real bank has thousands of customers acting at once, and the moment two goroutines read and write the same variable without coordination, you have a data race. The classic symptom is a lost update: both goroutines read a balance of $100, both add $10, and both write $110, so one deposit has disappeared.

The first program in this stage makes the problem visible. It deposits $1 a hundred times from a hundred goroutines into an unprotected balance. To make the bad timing certain instead of rare, the unsafe deposit yields the processor with runtime.Gosched() between its read and its write. Without the yield, the race is still there, but it only shows up occasionally, which is the reason races are so hard to debug.

Go A lost-update race, made visible

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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

The balance ends far below the expected 10,000 cents, because most goroutines read the same stale value. (We print only the boolean, since the exact number depends on scheduling.) On your own machine, the race detector would report this program at once: go run -race . or go test -race. Always run your concurrent tests with -race.

The cure is a sync.Mutex. The Account gets a mu field. Every method that touches balance locks it first and unlocks with defer. Two rules make the difference between a safe account and a subtly broken one:

  1. Protect the check and the change together. Withdraw reads the balance, compares it with the floor, then subtracts. If the lock only covered the subtraction, two goroutines could both pass the check and overdraw the account. This pattern is called check-then-act, and the whole sequence must happen under one lock.
  2. Never copy a struct that contains a mutex. A copy has its own lock and shares nothing with the original. That is why every function takes *Account, and why go vet warns about copying locks.

The second program tests exactly that: a savings account with $30.00 and 100 goroutines that each try to withdraw $1.00. If the check-then-act is atomic, exactly 30 withdrawals succeed and the balance ends at zero, every time. It also runs a thousand deposits and four hundred withdrawals together and checks the arithmetic.

Go Stage 2: a mutex-protected 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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

The result is the same on every run: exactly 30 successes, 70 refusals and a final balance of $0.00. That is the property to look for in concurrent code: the answer does not depend on which goroutine happens to run first. Which particular goroutines succeed is random, but how many succeed is not.

Some points that trip up beginners:

  • defer a.mu.Unlock() right after Lock() guarantees the unlock on every return path, including early returns and panics. See defer.
  • atomic.Int64 (Go 1.19) is a counter that goroutines can update without a mutex. It is perfect for statistics. Use a mutex when several values must change together, such as a balance and its history.
  • Read methods need the lock too. Balance() locks because a read concurrent with a write is also a race, even though it "only reads".
  • The unlocked ID() is fine because id is set once in the constructor and never changes. Data that is immutable after construction needs no lock.

Stage 3: a Bank and deadlock-free transfers

A transfer touches two accounts, and both must change together: no other goroutine may ever observe the money gone from the source but not yet in the destination. So a transfer has to hold both locks at once. That creates the danger of deadlock.

Imagine that alice sends money to bob while bob sends money to alice. Goroutine 1 locks alice and waits for bob. Goroutine 2 locks bob and waits for alice. Each holds what the other needs, so neither can ever proceed. The program that follows creates exactly this situation. To make the unlucky timing certain, both goroutines wait on a WaitGroup after taking their first lock until the other one has taken its first lock too. Go detects that every goroutine is blocked and stops with a fatal error.

Go Two transfers lock in opposite order (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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program stops with fatal error: all goroutines are asleep - deadlock!, followed by the stacks of the blocked goroutines. They show sync.(*Mutex).Lock in naiveTransfer, and the main goroutine stuck in finished.Wait(). Go's runtime can only detect a deadlock when every goroutine is blocked, as here. In a real server other goroutines keep running, the two stuck ones just hang forever, and nothing is reported. Deadlocks in production are silent.

The standard cure is lock ordering. If every transfer locks the two accounts in the same global order, a cycle cannot form: whoever locks the smaller id first holds the thing the other needs to start, so the other waits at its first lock, not at its second. We use the account id (a string, compared with <) as the order. For alice and bob both transfers lock alice first, whichever direction the money flows.

Now the Bank. It owns a map from id to account, protected by an RWMutex because lookups are frequent and openings are rare. Transfer does this:

  1. Validate the amount and reject a transfer to the same account (locking one mutex twice would deadlock with itself).
  2. Look up both accounts.
  3. Lock them in id order.
  4. Check the source's policy, move the money, and unlock (via defer, in reverse order).

Errors from Transfer are wrapped in a TransferError that remembers the parties and amount. It has an Unwrap method, so errors.Is(err, ErrUnknownAccount) and errors.As(err, &insufficient) still see the original error inside. This is the idiom for adding context without hiding the cause.

The stress test at the end hammers the bank: 8 goroutines perform 2,000 random transfers each between 5 accounts, in all directions, many of them opposite to each other. Accounts start with small balances, so some transfers are refused. The checks are the invariants that must hold no matter how the goroutines interleave: the total amount of money is unchanged, and no account ever went below its floor.

Go Stage 3: a Bank with ordered locking

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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

All the invariants hold. Note what the test does not print: how many transfers succeeded and how many were refused. Those numbers depend on the order in which goroutines run, so they can differ between runs. A good concurrent test checks properties that must hold for every interleaving, not one lucky outcome.

Look closely at a few lines:

  • fail := func(err error) error { ... } is a small closure that builds the wrapped error, so each early exit is a single return fail(...). The caller gets the same type for every failure.
  • fmt.Errorf("%w: %q", ErrUnknownAccount, id) wraps a sentinel and adds the id in one step.
  • The Bank mutex protects the map, not the balances. Each Account has its own mutex. Splitting the locks means a transfer between two accounts never blocks transfers between two others, which is essential for throughput. The RWMutex lets many goroutines look up accounts at the same time.
  • Lock order is by id, not by role. The code swaps first and second if the destination's id is smaller. Any total order works, as long as every code path that holds two locks uses it.
  • Locks are released in reverse order thanks to defer, which runs last-in, first-out.
  • Total() is a snapshot, not a transaction. It locks accounts one at a time, so if transfers are running it can see money in flight. That is why the test calls it after wg.Wait(). A bank needs a consistent snapshot for reports, which you could get with a ledger (stage 4) or by locking everything in id order.

Lock ordering only works if you can see every place that takes two locks. If a function holds one account's lock and calls code (a callback, an interface method) that locks another, you have a hidden second lock and no guarantee about order. Keep critical sections small, do not call unknown code while holding a lock, and never send on a channel while holding one.

Stage 4: an audit ledger you can replay

Banks keep records of everything. An audit ledger is an append-only list of events: every opening deposit, every withdrawal, every transfer, and every refusal, each with a sequence number. It is useful for customers (a statement), for debugging (what exactly happened?) and, most interestingly here, for verification: if you start with zero balances and replay all successful events, you must arrive at exactly the balances the accounts hold now. If you don't, there is a bug.

The design needs care:

  • Record while holding the account locks. If the ledger entry were written after unlocking, two transfers on the same account could be recorded in a different order than they were applied. Writing under the lock keeps the ledger consistent with each account's history.
  • The ledger has its own mutex, held only for the tiny append. The lock order is always account locks first, then ledger lock, never the other way round, so the ledger cannot take part in a deadlock.
  • Entries are immutable values, and Entries() returns a clone so readers cannot corrupt the log.
  • Refusals are recorded too, with Kind: "rejected" and a note. They do not change balances, so the replay skips them.

The program first runs a small, fully deterministic scenario and prints its ledger, so you can see what an audit trail looks like. Then it repeats the stress test from stage 3, replays the ledger, and compares the replay with the real balances.

Go Stage 4: audit ledger and replay verification

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 bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first half is the audit trail of a short story. Alice's $120 transfer is accepted because her overdraft allows -$20.00. The second $40 transfer is refused: the ledger shows a rejected entry with the reason, and no money moved. The transfer to carol is rejected because carol does not exist (there is no Open for her), and the withdrawal of $5.00 from bob goes through.

The second half proves the point of the whole design. After 16,000 concurrent operations from eight goroutines, replaying the ledger from nothing reproduces every balance exactly, and the sequence numbers run 1 to N without a gap. If you remove the lock in Withdraw or record entries after unlocking, this check fails. That is the value of a ledger: a second, independent account of what happened, against which the live state can be tested.

A real bank database does the same job with transactions: the SQL database holds the locks and the write-ahead log, and you ask for BEGIN ... COMMIT. The principles are identical: atomicity, a consistent order of acquiring locks, an append-only log and invariants that you can check. See databases with database/sql.

Ideas for extending the bank

  • Add Statement(id) that returns an account's entries in order, plus a running balance.
  • Add interest: a method on Savings accounts that deposits a percentage, run by a time.Ticker goroutine that stops with a context.
  • Add a Freeze(id) state that makes every operation on the account fail with a new sentinel error ErrFrozen.
  • Replace the in-memory ledger with a file written through a single goroutine that receives entries on a channel (the actor pattern).
  • Expose the bank over HTTP and test it with net/http/httptest: see the REST API and URL shortener projects.
  • Run your tests with go test -race -count=20 so that the scheduler tries many interleavings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the bank store money as an int64 number of cents instead of a float64 of dollars?

    Binary floating point cannot represent values like 0.10 exactly, so sums drift. Integer cents are exact, and conversion to dollars happens only when printing.
  2. 2. 100 goroutines each call Withdraw(100) on a savings account holding 3000 cents, and Withdraw locks the mutex around both the check and the change. How many succeed?

    Because the check and the subtraction are one atomic step, the balance goes 3000, 2900, ... 0, and every further attempt is refused. Which goroutines win is random; how many win is not.
  3. 3. Which technique prevents deadlock between a transfer alice -> bob and a transfer bob -> alice?

    If every code path acquires the locks in one fixed order, a circular wait cannot form. Locking source-then-destination gives opposite orders for opposite transfers, which is the deadlock.
  4. 4. errors.Is(err, ErrUnknownAccount) is true for an error returned by Transfer, although Transfer returns a *TransferError. Why?

    errors.Is and errors.As call Unwrap repeatedly, comparing each error in the chain. The Unwrap method is what makes a wrapper transparent.
  5. 5. Why is the ledger entry written while the account locks are still held?

    If an entry were written after unlocking, two operations on the same account could be logged in the opposite order from how they happened, and a replay would no longer match the live balances.

Summary

  • Represent money as integer cents with a String() method. Model differing rules (overdraft or not) with a small interface and composition instead of duplicated types.
  • Use sentinel errors for simple conditions (errors.Is) and typed errors with fields for rich ones (errors.As). Wrap errors with a type that has Unwrap, or with %w, so the cause stays visible.
  • Protect shared state with a mutex, always lock with defer Unlock, never copy a mutex, and keep check and change inside one critical section.
  • A multi-account operation must hold all its locks at once; acquire them in one global order (for example by id) so a cycle, and therefore a deadlock, is impossible.
  • Test concurrent code with invariants that hold for every interleaving (total money, floors, replay equals state), and run it with go test -race.
  • An append-only ledger written under the same locks gives you an audit trail and an independent way to verify the live state.

Next: Project: URL Shortener Service