AlgoViz

Design a cash machine (ATM)

hard 85 min

Card, PIN, notes.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:10

Theory

Read or listen first. About 2 min.

What it is

A cash machine lets a person take notes from an account. It reads a card, asks a bank whether the PIN and the amount are fine, and moves notes to a slot.

As an object design it is a coordinator between two things that it does not control: a bank that may be silent and a dispenser that may jam. Between them it has one thing of its own, a journal that survives a power cut.

The heart is the order of steps: plan, write, hold, write, pay, write, commit. Every other class exists so that this order can be stopped anywhere and finished later.

Why it exists

It is asked because everyone has used one, and because it separates drawings from designs. A menu with states takes ten minutes. The question of what happens when the light goes out takes the rest of the hour.

The same shape is in paying online, in shipping a parcel after a charge, in booking with two companies, and in any step that cannot be undone in the middle of steps that can.

It teaches honesty in types. A dispenser that answers yes, no or unknown leads to a better program than one that returns nothing.

A short history

  1. 27 June 1967

    Barclays unveils a cash machine at its branch in Enfield, north London. It let people withdraw 10 pounds at a time.

  2. 25 September 1973

    US patent 3,761,682 is published: a credit card automatic currency dispenser by Docutel, filed on 7 October 1971.

  3. 16 September 1975

    US patent 3,905,461 is granted to Chubb Integrated Systems. Its priority date is 2 May 1966, before the Enfield machine was shown.

  4. 1999

    EMVCo is formed to manage the EMV specifications for chip cards, so that cards and machines of different countries work together.

  5. 8 November 2005

    PostgreSQL 8.1 is released with two-phase commit: prepare first, commit later, also after a crash.

Words to know

Hold
Money is reserved at the bank and not yet taken.
Commit
The held money is taken. Also called capture or post.
Release
A hold is given back. After a lost answer it is called a reversal.
Reference
A name for one payment, made by the machine, that every message carries.
Journal
A list of steps that only grows and survives a power cut.
Idempotent
Doing it twice has the same effect as doing it once.
Suspect
A payment where no program can know whether notes left.
Settle
Finish all open payments, at the start and by a timer.
Dispenser
Rollers, tray, shutter and sensors that move notes.
Phase
What the customer may do now. Lives in memory only.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Card and PIN. The bank checks, the machine obeys

Understand it

Story

A toy bank with note rolls

Four friends play bank. Lee sits inside a cardboard machine with three rolls of play money, a notebook and a toy telephone. Noor is the bank and has a board with the accounts. Nobody can see both sides at once, and that is the whole difficulty: the notes are here, the account is there, and the lamp can go out at any moment.

The notebook in the machine
502010notebookBANK: ASHAfree300held0

The notebook is the journal, the board is the bank, the slot is the dispenser, and the lamp is the power.

What an interviewer looks for here

  • Who owns what

    Accounts and PINs belong to the bank. Notes and the journal belong to the machine.

  • The order of steps

    Hold, pay, commit. Write before each one.

  • Silence is not no

    A lost answer leaves two possible worlds.

  • Honest not-knowing

    Sometimes a person must count. The design has a word for it.

How to spend the round

Ask first

Five questions, and what each answer changes

QuestionIf yesIf noDefault we take
Is the bank another system?Calls can be lost: refs and a journalOne lock would doAnother system
Can the dispenser fail?Two kinds of failureA toy problemYes, and it may be unsure
Only withdrawals?One dangerous verbDeposits add counting and envelopesWithdraw and balance
Several machines for one account?Limits and tries live at the bankThe machine could countMany machines
Must it work without the bank?Offline limits and riskSilence means try laterNo offline mode
The first answer decides the whole design. If they say that accounts are in memory, say what would change if they were not.

Order

Why pay before commit?

There are two actions that cannot be done at one moment: notes move here, a balance changes there. Something can fail in between. So ask which mistake you can live with.

OrderIf it stops in the middleWho losesCan it be repaired?
Take money, then payCharged, no notesCustomerOnly by a complaint
Pay, then take moneyNotes, not chargedBankPerhaps not: the account may be empty by then
Hold, pay, commitHeld, notes or no notesNobody yetYes: the journal says which
The hold turns a loss into a question, and the journal answers it.

A good withdrawal

Read

What each last line means

After a power cut, look at the last line of each payment

Last lineWhat may be trueWhat to do
noneNothing happenedNothing
ASKEDThe bank may hold money. No notes movedRelease
PAYINGThe bank holds. Notes may be anywhereAsk the sensors
PAIDNotes are gone. The bank may not knowCommit
RETURNEDNotes are inside. The bank may still holdRelease
SUSPECTNobody knowsWait for a person. Keep the hold
DONEBoth sides agreeNothing

The life of one payment

Bad

The design most people draw first

The design to avoid: the machine owns the money of the bank

ATM- accounts: Map<Card, Account>- cash: double- currentUser: User+ withdraw(amount: double)+ deposit(amount: double)+ getPin(card): StringAccount+ balance: double+ pin: String+ setBalance(value)

1/4Accounts inside the machine

There are many machines and one account. A machine that holds balances has a copy, and the copy is wrong as soon as someone uses another machine. It also knows every PIN.

owns (dies together)extends (is a)uses

Python
def withdraw(self, amount):    account = self.accounts[self.card]    if account.balance >= amount and self.cash >= amount:   # 80 from one 50 and one 20?        account.balance -= amount                           # power cut here: charged, no notes        self.dispenser.dispense(amount)                     # jammed: still charged        self.cash -= amount        return True    return False
Reads well, and loses money in four ways.
  1. 1

    The account is a copy

    Another machine has another copy. Both say yes to the same last 50.

  2. 2

    A sum is not notes

    Having 70 inside does not mean that 60 can be paid.

  3. 3

    No memory

    After a power cut nobody knows whether a payment was running.

  4. 4

    A failure nobody can see

    dispense returns nothing, so a jam looks like success.

Good

The design to reach

The design to reach: a machine between a bank and a dispenser, with a journal

CashMachine- card: Text?+ phase: Phase+ insert(card), eject()+ enter_pin(pin): Pin+ withdraw(amount): Result+ settle()+ staff_counted(ref, paid)

1/5The coordinator

It knows one card and one moment. It owns no account.

has (lives on)implementsowns (dies together)uses

Two things that the machine does not control, left and right, and one memory below that it does.

Who knows what

What each class owns

ClassKnowsDoesDoes not
CashMachineOne card, one phasePuts steps in orderKnow balances or PINs
CashBoxNotes by valuePlans a paymentMove anything
JournalEvery step everSays what is openDecide
DispenserIts sensorsMoves notes, says what it sawKnow accounts
BankAccounts, holds, triesHolds, commits, releasesKnow notes
EntryOne step of one paymentNothingChange

Danger

The answer that never came

One silence, two possible worlds

The bank does not answer the hold. What do you do?

BreaksTreat it as no
How
Show an error and forget.
Limit
The money may be held with nobody to release it.
Choose when
Never.
WorksTry again
How
Send the same hold with the same ref a few times.
Limit
The customer waits, and the bank may stay silent.
Choose when
Once or twice, for seconds.
StrongGive up and release by ref, until it is heard
How
The line stays open in the journal. A timer sends the release again.
Limit
The bank must accept a release for a hold that it has not seen, and remember it.
Choose when
Always, after the short retries.

Shape

Where does a fact live?

Ask this about every fact

Survives a bad day

  • A line before each step
  • The same code finishes and repairs
  • Every bank verb has a ref
  • Unknown is a word in the code

Survives a demo

  • Change the balance, then pay
  • Retry without a reference
  • A special repair script
  • dispense(): void

Summary

The whole topic in one minute.

Draw the border first: balances, tries and limits belong to the bank, notes and a journal to the machine. Both sides of the machine are interfaces, and both can fail: the bank by silence, the dispenser by not knowing.

A withdrawal plans, then holds, pays and commits, with a journal line before each step. After a stop, the last line decides: release, commit, or ask the sensors. If they do not know, the hold stays and a person counts.

Every bank verb carries a reference and may be repeated in any order. Finishing a payment and repairing one are the same code, so the repair is tested every day.

  • Hold, pay, commit. Write a line before each step.
  • The bank owns balances, tries and limits. The machine owns notes and a journal.
  • Silence is not a no. Release by reference until it is heard.
  • After PAYING, ask the sensors. If they do not know, a person counts and the hold stays.
  • Commit and release may arrive twice, late, or before the hold.
  • Finishing and repairing are the same code.

Sources