Notes
Requirements
Fix the scope. A customer inserts a card and enters a PIN. Three wrong PINs block the card. Once signed in, they can check the balance, withdraw cash, deposit notes, and eject the card. Every transaction is logged, and a session left alone for too long ends by itself. Say out loud what is out of scope: real bank networks, chip cryptography and printed receipts.
Ask the questions that change the code. Is the lockout per machine or per card? Per card, kept at the bank, so a thief cannot just walk to the next ATM. If the notes cannot make the amount, refuse before touching the account. If the cash jams after the account was debited, reverse the debit. And one account can be used by the ATM, a phone app and a card machine at the same time.
- insert card, enter PIN
- three wrong PINs block the card
- check balance
- withdraw cash in fixed notes
- deposit notes
- eject card, end the session
- log every transaction
- idle session times out
- out of scope: real network,
- card chip crypto, receipts
- lockout per ATM or per card?
- per card, at the bank
- which notes?
- 2000, 500 and 200
- amount the notes cannot make?
- refuse before any debit
- cash jams after the debit?
- reverse the debit
- one account, many channels?
- yes: ATM, app, card swipe
- limit per withdrawal: 20,000
Entities
The entities. A card is just a number and the account it points to. The bank owns the accounts, checks PINs and writes the transaction log; it is the source of truth that every channel shares. The ATM is a thin client with its own cash dispenser and one session at a time. Keeping the money rules in the bank, and not in the machine, is the key modelling choice here.
Class diagram
Turn them into types. A card and a transaction never change after creation, so they are Java records. The transaction type is an enum. Money is a long number of cents, never a double, so adding and subtracting never drifts. The only hot mutable number in the whole design is the account balance, which is an atomic long. One mutable thing makes the thread safety story short.
record Card(String number, String accountId)
record Transaction(long id, String account,
TxType type, long cents, boolean ok,
Instant at)
enum TxType { BALANCE, WITHDRAW,
DEPOSIT, REVERSAL }
class Account {
final String id;
AtomicLong balance; // cents
} PIN and lockout
The PIN check. The bank never stores the PIN itself, only a salted hash, and compares hashes with a constant-time equals so timing reveals nothing. Wrong attempts are counted per card in an atomic integer at the bank. The third strike returns blocked, and every later try is refused, on every ATM. A correct PIN resets the count. In a real bank this runs inside secure hardware, so mention that.
expected = pinHashByCard.get(card)
if (expected == null) return UNKNOWN
wrong = strikes(card)
if (wrong.get() >= 3) return BLOCKED
if (isEqual(expected, hash(card, pin))) {
wrong.set(0); return OK;
}
return wrong.incrementAndGet() >= 3
? BLOCKED : WRONG; Why not if statements
Why not flags and if statements? Because every button would check every flag: is the machine in service, is there a card, was the PIN right. Withdraw, deposit, balance and eject all repeat the same chain. Add one new step, such as asking for a one-time code, and you edit every method. The rules are grouped by button, when they should be grouped by the step the session is in.
String withdraw(long cents) {
if (outOfService) ...
else if (card == null) ...
else if (!pinOk) ...
else ...
}
// balance, deposit, enterPin and eject
// repeat the same chain of flags State pattern
The State pattern. One interface lists every button. Each step of a session is a class: Idle, CardInserted, Authenticated and OutOfService. The ATM holds the current state and passes every button to it. A neat Java trick: default methods in the interface politely refuse, so each state only overrides the few buttons that make sense for it. Idle only overrides insert card.
Write the transition table before the classes. Idle plus a card moves to CardInserted. The right PIN moves on to Authenticated; a wrong one stays and says how many tries are left; the third wrong one keeps the card and goes back to Idle. Eject or a timeout ends the session. If the cassettes are empty when a session ends, the machine goes out of service until an operator reloads it.
interface AtmState {
default String insertCard(Atm a, Card c)
{ return refuse("insert card"); }
default String enterPin(Atm a, String p)
{ return refuse("enter PIN"); }
... balance, withdraw, deposit, eject
}
synchronized String withdraw(long c) {
return state.withdraw(this, c);
} - Idle + card -> CardInserted
- CardInserted + right PIN
- -> Authenticated
- CardInserted + wrong PIN -> stay
- CardInserted + third wrong
- -> keep card, Idle
- Authenticated + eject -> Idle
- any + timeout -> Idle
- session ends, no cash left
- -> OutOfService
- OutOfService + reload -> Idle
Flow: sign in
Walk the sign-in. The customer types a wrong PIN. The machine passes it to the CardInserted state, which asks the bank. The bank answers wrong, with two tries left, and the state stays where it is. The second attempt is right, so the state switches the machine to Authenticated. Notice that the ATM never decides whether a PIN is right; it only reacts to the bank's answer.
Chain of notes
Cash uses the Chain of Responsibility pattern. Each cassette is a handler for one note value, linked from the largest note to the smallest. A handler takes as many of its notes as the amount and its count allow, then passes what is left to the next handler. Three thousand seven hundred becomes one two-thousand note, three five-hundreds and one two-hundred. Adding a new note value means adding one handler to the chain.
Planning never changes the cassettes; it only returns a map of notes. If the plan does not cover the full amount, the ATM refuses before touching the account. Committing subtracts the counts later. Be honest about one limit: greedy can fail when counts run low. Six hundred with one five-hundred and three two-hundreds fails greedily, though three two-hundreds would work. A small backtracking or dynamic programming search fixes it.
void plan(long rest, Map<Long,Integer> out){
int use = (int) min(rest / note, count);
if (use > 0) out.put(note, use);
long left = rest - use * note;
if (left > 0 && next != null)
next.plan(left, out);
}
3,700: 2000 x1, 500 x3, 200 x1 - plan() changes nothing
- covered != amount: refuse
- 300 with 2000, 500, 200:
- impossible, refuse early
- dispense(plan) subtracts counts
- greedy limit: 600 with one 500
- and three 200s: greedy takes
- 500, stuck with 100 left
- fix: backtrack one note, or DP
Flow: withdraw
The withdraw flow, in the order that keeps everyone safe. Validate the amount. Plan the notes, which is cheap and changes nothing. Then ask the bank to debit the account; if funds are short, stop. Then dispense. If the motor jams, the bank reverses the debit and logs a reversal, so the customer is never charged for cash they did not get. The order matters: cheap checks first, money last.
check: multiple of 100, under limit
plan = cash.plan(cents)
if (plan.isEmpty()) return "cannot make"
tx = bank.debit(account, cents)
if (!tx.ok()) return "insufficient funds"
if (!cash.dispense(plan.get())) {
bank.reverse(tx);
return "not dispensed, reversed";
}
return "take your cash" Flow: deposit
Deposits run the other way. The machine counts the notes and rejects any value it does not know. The notes go into the matching cassettes, which is how recycling ATMs work, and the bank credits the account and logs a deposit. A real bank might hold the deposit as pending until a person checks the notes; that is a nice extension to mention, a new status on the transaction.
Transaction log
The transaction log. Every attempt is recorded by the bank with an id from an atomic counter, the type, the amount, whether it worked, and the time from an injected clock. Failed withdrawals are logged too, because fraud checks and customer disputes need them. A jam shows up as a withdrawal followed by a reversal, so the history explains itself. The log is a concurrent queue, safe for many channels to append.
Transaction t = new Transaction(
txSeq.incrementAndGet(), account,
type, cents, ok, clock.get());
log.add(t); // ConcurrentLinkedQueue
history(account): filter the log
declined debits are logged too:
fraud checks and disputes need them Concurrency
The concurrency question. The ATM, a phone app and a card machine all debit the same account at the same moment. A check-then-subtract would let two of them spend the same money. Instead, the debit reads the balance, checks it is enough, and swaps in the new value with compare-and-set. If another channel changed the balance in between, the swap fails and the loop reads again. The balance can never go below zero.
Give every shared field a safe home. The balance is an atomic long with a compare-and-set loop. PIN strikes are atomic integers per card at the bank. Accounts and PIN hashes sit in concurrent maps, and the log is a concurrent queue. Inside one ATM there is a single customer, so its public methods are simply synchronized, and the cassettes are only touched under that lock. Records need no locking at all.
while (true) {
long cur = balance.get();
if (cur < cents) return false;
if (balance.compareAndSet(cur,
cur - cents))
return true;
// someone else changed it: retry
} - balance: AtomicLong + CAS loop
- PIN strikes: AtomicInteger
- per card, at the bank
- accounts, hashes:
- ConcurrentHashMap
- log: ConcurrentLinkedQueue
- one ATM: synchronized methods,
- cassettes used only under it
- records: immutable, share freely
Session timeout
A forgotten session is a real risk, so a timer calls tick on the ATM. Every button press records the last activity time, and if more than sixty seconds have passed, the session ends and the card comes back. The time comes from an injected clock, a supplier of instants. In the demo we move a fake clock forward ninety seconds instead of sleeping, which keeps the test fast and never flaky.
synchronized String tick() {
if (card != null && Duration.between(
lastActivity, clock.get())
.compareTo(TIMEOUT) > 0) {
endSession();
return "timed out, card returned";
}
return "ok";
} Extensibility
Interviewers like to add rules. A daily withdrawal limit becomes a small list of withdraw rules checked before the debit. A one-time code after the PIN is one more state between CardInserted and Authenticated. A new note value is one more handler in the chain. Pending deposits are a new status on the transaction. And other banks' cards make the bank an interface with one implementation per card network.
- daily limit: a WithdrawRule
- chain checked before debit
- one-time code: a new
- VerifyingOtp state
- new note value: one more
- NoteHandler in the chain
- pending deposits: a status
- on Transaction
- many banks: Bank becomes an
- interface, one per network
Testing
The full code is below the player. The demo signs in after one wrong PIN, withdraws three thousand seven hundred in mixed notes, is refused an amount the notes cannot make, survives a simulated jam with a reversal, deposits, times out a session with the fake clock, and blocks a card on the third wrong PIN. Then eight threads race to take two thousand each from ten thousand. Exactly five succeed, every time.
enter PIN 1111 -> Wrong PIN, 2 tries left withdraw 3,700 -> 2000x1 500x3 200x1 withdraw 300 -> cannot make 300.00 withdraw (jam) -> 1,000.00 reversed deposit 4x500 -> Deposited 2,000.00 balance -> 10,300.00 tick +90s -> timed out third wrong PIN -> card blocked race: 8 debits of 2,000 on 10,000 -> 5 ok, 3 declined, balance 0
Follow-ups
Expect these follow-ups. Why keep the lockout at the bank? So a blocked card is blocked on every machine. Debit first or dispense first? Plan, debit, dispense, and reverse on failure. What if the ATM loses power mid-dispense? It writes a journal entry before dispensing and reconciles with the cassette counts on boot. Would a synchronized account work? Yes; compare-and-set just avoids threads waiting on a lock.
- why lockout at the bank?
- so every ATM sees it
- debit first or dispense first?
- plan, debit, dispense, reverse
- greedy fails with low counts?
- backtrack or DP
- ATM loses power mid-dispense?
- journal, reconcile on boot
- why not synchronized Account?
- fine too; CAS avoids waiting
Say it like this
Here is the short version to say out loud. The bank owns the accounts, the PIN strikes and the transaction log. The ATM passes every button to its current state. Cash is a chain of note handlers that plan before anything moves. A withdrawal plans the notes, debits the account with compare-and-set, dispenses, and reverses the debit if the cash jams.
- "The bank owns accounts, PIN
- strikes and the log. The ATM
- passes each button to its
- State. Cash is a chain of note
- handlers that plan first. A
- withdrawal plans, debits with
- compare-and-set, dispenses,
- and reverses on a jam."