An ATM handles two kinds of money, and most bad designs mix them up. The notes in the cassettes belong to the machine. The balance belongs to the bank, sits in a database the ATM never sees, and is shared with every other ATM, the UPI app on the customer’s phone and the branch counter. The ATM can count its notes; it can only ask the bank about the balance. Once you hold onto that split, the rest of the problem follows: which states the session goes through, how ₹2,600 turns into notes, and what happens when the machine has already debited the account and then jams after the third note.
That last case is what interviewers actually push on. Anyone can draw Idle, card inserted and PIN entered. The interesting part is what happens when money and hardware disagree.
What it has to do
Settle these before drawing anything:
- Card and PIN. Insert a card, enter a PIN. Three wrong PINs block the card. Customers can eject the card at any point before a withdrawal starts.
- Balance enquiry. Read from the bank, never cached on the machine.
- Cash withdrawal. In multiples of ₹100, up to a per-transaction cap the machine is configured with (₹10,000 in the code), and within a daily limit the bank enforces per account.
- Dispensing by denomination. The machine holds ₹500, ₹200 and ₹100 cassettes (the usual mix in India now that the ₹2,000 note has been withdrawn). It has to find a combination of notes it actually has, and refuse before touching the account if it cannot.
- Failure handling. If the dispenser delivers less than was debited, the shortfall goes back to the account and the machine takes itself out of service until someone restocks or fixes it.
- One customer at a time per machine, many machines per bank. The account balance must stay correct when several machines (or a machine and a phone app) debit it at the same moment.
What I would say is out of scope, out loud, in the first five minutes:
- Cash deposit and note recognition. A recycler that takes notes in and pays them back out is a different machine; I cover how the design stretches to it below.
- Transfers, bill payments, PIN change, mini statements. Each is one more menu action on the same authenticated state, so they add typing, not design.
- Card chip and EMV cryptography, PIN encryption, the HSM. Real, important, and not what a class-design round is testing.
- The network between the ATM and the bank (switch, ISO 8583 messages). I model the bank as an interface with four calls.
- Receipt printing, the screen UI, languages.
- Interest, overdrafts, multiple currencies.
Two owners: the machine and the bank
The classes fall out of that split.
On the machine:
ATM(calledMachinein the Java file, because the outer class is alreadyAtm) holds the currentState, the inserted card and resolved account number for this session only, the head of the cassette chain, the hardware, and a counter for transaction ids.Stateand its four subclasses:Idle,HasCard,Authenticated,OutOfService. Every customer action goes through the current state.Cassetteis one tray of one note value with a count, plus a pointer to the next cassette. The chain runs ₹500, then ₹200, then ₹100.Hardwareis the physical note feeder. It is told “feed 4 notes of ₹500” and returns how many actually came out. The real one talks to a device driver; the test one,JammingHardware, stops after a set number of notes.
At the bank:
Bankexposesverify_pin,balance,debit(txn_id, account, amount)andreverse(txn_id, account, amount). It owns the wrong-PIN counters, the daily limits and the balances.Accountholds a balance, a daily limit, what has been withdrawn today, a lock, and a map of transaction id to outcome so a replayed request gets the same answer.
There is no Card class and no Customer class. A card here is an id the bank maps to a PIN and an account. If the interviewer wants expiry dates or several accounts per card (savings and current, picked on screen), Card becomes a real class, but I would not start with it.
classDiagram
class ATM {
+id: str
+state: State
+card: str
+account: str
+cash: Cassette
+hardware: Hardware
+max_per_txn: int
+insert_card(card) str
+enter_pin(pin) str
+balance() str
+withdraw(amount) str
+eject() str
+restock(notes) str
-next_txn_id() str
}
class State {
<<abstract>>
+insert_card(atm, card)
+enter_pin(atm, pin)
+balance(atm)
+withdraw(atm, amount)
+eject(atm)
}
class Idle
class HasCard
class Authenticated
class OutOfService
class Cassette {
+value: int
+count: int
+next: Cassette
+plan(amount) dict
+dispense(plan, hw) int
}
class Hardware {
+feed(value, count) int
}
class JammingHardware
class Bank {
+verify_pin(card, pin) str
+balance(account) int
+debit(txn_id, account, amount)
+reverse(txn_id, account, amount)
}
class Account {
+number: str
+balance: int
+daily_limit: int
+withdrawn_today: int
-outcomes: dict~str, str~
-lock: Lock
}
ATM --> State
ATM *-- Cassette
ATM --> Hardware
ATM --> Bank
State <|-- Idle
State <|-- HasCard
State <|-- Authenticated
State <|-- OutOfService
Cassette --> Cassette : next
Hardware <|-- JammingHardware
Bank "1" *-- "*" AccountThe session as a state machine
Four states. Each row is what the action does in that state; a dash means the machine refuses with the state’s message.
| Action | Idle | HasCard | Authenticated | OutOfService |
|---|---|---|---|---|
| insert card | to HasCard, unless the card is blocked | - | - | - |
| enter PIN | - | right: to Authenticated; wrong: stay; third wrong: card blocked, back to Idle | - | - |
| balance | - | - | read from bank | - |
| withdraw | - | - | pay and go to Idle; jam: to OutOfService | - |
| eject | - | to Idle | to Idle | - |
| restock (operator) | to Idle | - | - | to Idle |
Two decisions in that table are worth defending.
A withdrawal ends the session. After the cash comes out, the card comes back and the machine is Idle. Many ATMs work this way and I think it is the right default: the classic way to lose money at an ATM is to walk off with the notes and leave the card in an authenticated session. If the interviewer wants “another transaction?” on screen, it is one line, but say why you chose the stricter version.
OutOfService is a state, not a flag. With a boolean out_of_service checked at the top of every method, someone eventually adds a method and forgets the check. As a state, every action already refuses, because OutOfService overrides nothing.
The machine has no Dispensing state. Dispensing happens inside one call and nothing else can happen during it, so a state that exists for the length of a function call earns nothing. If the hardware were asynchronous (start feeding, get a callback later), Dispensing would become a real state, because a customer could press Cancel in the middle and you would need to know what that means.
Patterns, and the ones I left out
State, for the session. The alternative is an enum and a switch in every method, and in a four-state, five-action machine that is 20 cases spread over five methods. With State, each class lists only what it allows, and the base class refuses everything else with the state’s own message (“insert your card first”, “enter your PIN first”, “out of service”). Adding a state, say AwaitingAccountType for picking savings or current after the PIN, is a new class plus one changed transition in HasCard; nothing else moves. The vending machine uses the same pattern; the ATM version is more interesting because one transition (withdraw) can fail half way.
The states hold no data of their own; the card, account and cash live on the ATM. That means they could be shared singletons instead of Authenticated() on every transition. I create new ones because it costs nothing at this scale and keeps the code obvious; if the interviewer asks, sharing them is fine precisely because they are stateless.
Chain of Responsibility, for notes. Each Cassette pays what it can in its own denomination and hands the remainder to the next one. A new note value is a new link; the ATM code does not change. This is the pattern most ATM answers reach for, and the textbook version has a bug that is worth knowing about.
The textbook handler takes as many of its notes as it can, then passes the rest on. That is greedy, and with a limited stock greedy fails when an answer exists. Load a machine with four ₹500s and three ₹200s, and no ₹100s, and ask for ₹600. Greedy takes one ₹500, leaving ₹100 that nobody can pay, and refuses. Three ₹200s would have worked. Ask for ₹1,100 and greedy takes two ₹500s and is stuck on ₹100 again, while ₹500 + 3 × ₹200 works. These are not exotic loads: a machine that has run out of ₹100s is a normal Saturday evening.
The fix keeps the chain shape. Each cassette tries its largest possible count first, asks the rest of the chain about the remainder, and if the rest says no, tries one note fewer. It is backtracking, bounded by the amount: for a ₹10,000 cap the ₹500 cassette tries at most 21 counts and the ₹200 cassette at most 51 for each of those, and the ₹100 cassette at the bottom answers immediately with a division. About a thousand calls in the worst case, nothing for a machine that then spends seconds counting notes. With more denominations or bigger amounts you would switch to dynamic programming over the amount, but the interface stays plan(amount).
The other change from the textbook is splitting plan from dispense. plan changes nothing; it only answers “can I, and with which notes”. dispense actually moves notes and decrements counts. The ATM plans, then debits the account, then dispenses. If the plan fails, the bank never hears about it.
Considered and dropped:
- Singleton for
BankorATM. There are many ATMs by definition, and the demo runs three against one bank. A singleton bank makes every test share one set of balances. Pass the bank in. - Command objects for transactions (
WithdrawCommand,BalanceCommand). They pay off when you need a persistent journal you can replay after a crash, or a queue of operations. With one synchronous withdrawal per session I keep the flow as a method; the transaction id and the bank’s outcome map already give the replay safety a command log would. I would bring Command in for the crash-recovery follow-up below. - Observer for receipts and SMS alerts. Real, but the SMS comes from the bank when the debit posts, not from the ATM. On the machine, the only listener would be the receipt printer, and one listener does not need a pattern.
- Template Method for transaction types. “Validate, authorise, execute, print” sounds like a template, but balance enquiry has nothing to authorise and nothing to execute. Forcing both through one skeleton gives empty hook methods.
- Strategy for dispensing. Plausible if the bank wants “fewest notes” on one machine and “keep ₹100s for small withdrawals” on another. Today there is one algorithm, so the chain is enough; if a second policy shows up, the chain’s
planbecomes the default strategy.
The order inside a withdrawal
This is the part to write on the whiteboard as numbered steps, because the order is the design:
- Check the amount on the machine: positive, a multiple of ₹100, under the per-transaction cap. No network call yet.
planthe notes. If the cassettes cannot make the amount, refuse now. The customer has lost nothing and the bank has seen nothing.- Create a transaction id (
ATM01-0003): machine id plus a sequence number. debitat the bank with that id. The bank checks the balance and the daily limit under the account’s lock. If it refuses, nothing has been dispensed, so there is nothing to undo.dispensethe planned notes. Hardware reports how many really came out.- If fewer notes came out than were debited,
reversethe difference against the same transaction id, end the session and go out of service.
Why debit before dispense? Because the two failure modes are not symmetric. If you dispense first and the debit then fails (network down, account frozen a second ago), the customer walks away with money the bank never recorded, and nobody can get it back. If you debit first and the dispense fails, the customer is short until the reversal posts, which is annoying but recoverable, and every bank already has a process for it. RBI’s 2019 turnaround-time rules make that process mandatory for Indian banks: a failed ATM withdrawal has to be reversed within five days of the transaction, with ₹100 a day paid to the customer for any delay beyond that. In the card-network message format (ISO 8583) the undo message is literally called a reversal, which is why the method has that name.
Step 2 before step 4 matters just as much. A design that debits and then discovers it has no notes the right shape needs a reversal for something it could have known up front.
The code
Both files were run on the box this lesson was written on (Python 3.13.5, OpenJDK 21.0.13) and print byte-for-byte identical output. Nothing in the demo is random; the jam is a scripted JammingHardware, and the only threads are in demo 7, whose printed result does not depend on scheduling. The files and expected-output.txt are in course-code/low-level-design/15/ in the course repository.
Read these parts closely:
Bank.debitstores the outcome against the transaction id inside the account’s lock, refusals included. A retried request with the same id gets the same answer and moves no money. Storing refusals is deliberate: if a timed-out “insufficient funds” were retried after a salary credit landed, the ATM would get “ok” for a request whose customer had already been told no and walked away.Cassette.planreturns a map and changes nothing.Cassette.dispensestops at the first cassette that delivers short and returns what was actually paid, rather than throwing; the caller needs the number to reverse the right amount.- The wrong-PIN counter is in
Bank, keyed by card. If it lived on the ATM, a thief could try two PINs at one machine, walk to the next, and try two more, forever. - In
HasCard.enter_pin, the third wrong PIN ends the session so the machine does not sit in HasCard with a blocked card.
Python
"""ATM low-level design: State pattern for the session, a chain of cassettes
for cash, idempotent debits, and a reversal when the dispenser jams.
Run: python3 atm.py
"""
from __future__ import annotations
import threading
from dataclasses import dataclass, field
class AtmError(Exception):
"""A refused operation. The message is what the screen shows."""
# ---------------- bank side: the ATM never holds a balance ----------------
@dataclass
class Account:
number: str
balance: int
daily_limit: int
withdrawn_today: int = 0
outcomes: dict[str, str] = field(default_factory=dict) # txn id -> "ok" or the refusal
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
class Bank:
MAX_PIN_TRIES = 3
def __init__(self) -> None:
self._accounts: dict[str, Account] = {}
self._cards: dict[str, tuple[str, str]] = {} # card -> (pin, account number)
self._wrong_pins: dict[str, int] = {}
self._card_lock = threading.Lock()
def open_account(self, number: str, balance: int, daily_limit: int) -> None:
self._accounts[number] = Account(number, balance, daily_limit)
def issue_card(self, card: str, pin: str, number: str) -> None:
self._cards[card] = (pin, number)
def is_blocked(self, card: str) -> bool:
with self._card_lock:
return self._wrong_pins.get(card, 0) >= self.MAX_PIN_TRIES
def verify_pin(self, card: str, pin: str) -> str:
"""Returns the account number. The wrong-PIN count lives here, not in the ATM."""
with self._card_lock:
if card not in self._cards:
raise AtmError("card not recognised")
tries = self._wrong_pins.get(card, 0)
if tries >= self.MAX_PIN_TRIES:
raise AtmError("card blocked, contact your bank")
real_pin, number = self._cards[card]
if pin == real_pin:
self._wrong_pins[card] = 0
return number
tries += 1
self._wrong_pins[card] = tries
left = self.MAX_PIN_TRIES - tries
if left == 0:
raise AtmError("wrong PIN, card blocked")
raise AtmError(f"wrong PIN, {left} {'try' if left == 1 else 'tries'} left")
def balance(self, number: str) -> int:
acct = self._accounts[number]
with acct.lock:
return acct.balance
def debit(self, txn_id: str, number: str, amount: int) -> None:
"""Idempotent: a replayed txn id gets the first outcome again and moves no money."""
acct = self._accounts[number]
with acct.lock:
if txn_id not in acct.outcomes:
acct.outcomes[txn_id] = self._try_debit(acct, amount)
outcome = acct.outcomes[txn_id]
if outcome != "ok":
raise AtmError(outcome)
@staticmethod
def _try_debit(acct: Account, amount: int) -> str:
if amount > acct.balance:
return f"insufficient funds (balance Rs {acct.balance})"
if acct.withdrawn_today + amount > acct.daily_limit:
return f"daily limit, Rs {acct.daily_limit - acct.withdrawn_today} left today"
acct.balance -= amount
acct.withdrawn_today += amount
return "ok"
def reverse(self, txn_id: str, number: str, amount: int) -> None:
"""Credit back the undispensed part of a debit. Keyed on the original id, so retries are safe."""
acct = self._accounts[number]
with acct.lock:
key = "REV:" + txn_id
if key in acct.outcomes:
return
if acct.outcomes.get(txn_id) != "ok":
raise ValueError(f"nothing to reverse for {txn_id}")
acct.balance += amount
acct.withdrawn_today -= amount
acct.outcomes[key] = "ok"
# ---------------- cash side: hardware plus a chain of cassettes ----------------
class Hardware:
"""The note feeder. Returns how many notes physically came out."""
def feed(self, value: int, count: int) -> int:
return count
class JammingHardware(Hardware):
"""Test double: delivers `jam_after` notes in total, then jams."""
def __init__(self, jam_after: int) -> None:
self.left = jam_after
def feed(self, value: int, count: int) -> int:
out = min(count, self.left)
self.left -= out
return out
class Cassette:
"""One link in the chain: pays what it can in its own note and hands the rest on."""
def __init__(self, value: int, count: int, nxt: Cassette | None = None) -> None:
self.value, self.count, self.next = value, count, nxt
def plan(self, amount: int) -> dict[int, int] | None:
"""Notes per value that make `amount`, or None. Tries the most notes first, backs off one at a time."""
most = min(self.count, amount // self.value)
for take in range(most, -1, -1):
rest = amount - take * self.value
mine = {self.value: take} if take else {}
if rest == 0:
return mine
if self.next is None:
return None # fewer notes here only leaves more for nobody
below = self.next.plan(rest)
if below is not None:
return mine | below
return None
def dispense(self, plan: dict[int, int], hw: Hardware) -> int:
"""Feeds the planned notes, top of the chain first. Returns the amount actually paid out."""
want = plan.get(self.value, 0)
got = hw.feed(self.value, want) if want else 0
self.count -= got
paid = got * self.value
if got < want or self.next is None:
return paid # jammed: stop, do not keep feeding
return paid + self.next.dispense(plan, hw)
def build_chain(notes: list[tuple[int, int]]) -> Cassette:
head = None
for value, count in sorted(notes): # build from the smallest so the largest ends up first
head = Cassette(value, count, head)
return head
def cassettes(head: Cassette | None):
while head:
yield head
head = head.next
def greedy_plan(head: Cassette, amount: int) -> dict[int, int] | None:
"""The textbook version, for comparison: largest note first, never reconsiders."""
plan = {}
for c in cassettes(head):
take = min(c.count, amount // c.value)
if take:
plan[c.value] = take
amount -= take * c.value
return plan if amount == 0 else None
def fmt_plan(plan: dict[int, int] | None) -> str:
if plan is None:
return "impossible"
return " + ".join(f"{v}x{n}" for v, n in plan.items())
# ---------------- the ATM and its states ----------------
class State:
name = "State"
hint = "not allowed now"
def insert_card(self, atm: ATM, card: str) -> str:
raise AtmError(self.hint)
def enter_pin(self, atm: ATM, pin: str) -> str:
raise AtmError(self.hint)
def balance(self, atm: ATM) -> str:
raise AtmError(self.hint)
def withdraw(self, atm: ATM, amount: int) -> str:
raise AtmError(self.hint)
def eject(self, atm: ATM) -> str:
raise AtmError(self.hint)
class Idle(State):
name, hint = "Idle", "insert your card first"
def insert_card(self, atm, card):
if atm.bank.is_blocked(card):
raise AtmError("card blocked, contact your bank")
atm.card = card
atm.state = HasCard()
return "enter PIN"
class HasCard(State):
name, hint = "HasCard", "enter your PIN first"
def enter_pin(self, atm, pin):
try:
atm.account = atm.bank.verify_pin(atm.card, pin)
except AtmError:
if atm.bank.is_blocked(atm.card):
atm.end_session()
raise
atm.state = Authenticated()
return "PIN ok"
def eject(self, atm):
atm.end_session()
return "card returned"
class Authenticated(State):
name, hint = "Authenticated", "card already inserted"
def balance(self, atm):
return f"balance Rs {atm.bank.balance(atm.account)}"
def withdraw(self, atm, amount):
if amount <= 0 or amount % 100:
raise AtmError("amount must be a multiple of Rs 100")
if amount > atm.max_per_txn:
raise AtmError(f"maximum Rs {atm.max_per_txn} per withdrawal")
plan = atm.cash.plan(amount)
if plan is None:
raise AtmError(f"cannot pay Rs {amount} with the notes loaded ({atm.cash_summary()})")
txn = atm.next_txn_id()
atm.bank.debit(txn, atm.account, amount) # refused -> nothing dispensed, nothing to undo
paid = atm.cash.dispense(plan, atm.hardware)
if paid < amount:
atm.bank.reverse(txn, atm.account, amount - paid)
atm.end_session()
atm.state = OutOfService()
return f"{txn} paid Rs {paid} of {amount}, Rs {amount - paid} credited back, card returned"
atm.end_session()
if atm.cash_total() < 100:
atm.state = OutOfService()
return f"{txn} paid {fmt_plan(plan)}, card returned"
def eject(self, atm):
atm.end_session()
return "card returned"
class OutOfService(State):
name, hint = "OutOfService", "out of service"
class ATM:
def __init__(self, atm_id: str, bank: Bank, notes: list[tuple[int, int]],
hardware: Hardware | None = None, max_per_txn: int = 10_000) -> None:
self.id, self.bank, self.max_per_txn = atm_id, bank, max_per_txn
self.cash = build_chain(notes)
self.hardware = hardware or Hardware()
self.state: State = Idle()
self.card: str | None = None
self.account: str | None = None
self._seq = 0
def insert_card(self, card: str) -> str:
return self.state.insert_card(self, card)
def enter_pin(self, pin: str) -> str:
return self.state.enter_pin(self, pin)
def balance(self) -> str:
return self.state.balance(self)
def withdraw(self, amount: int) -> str:
return self.state.withdraw(self, amount)
def eject(self) -> str:
return self.state.eject(self)
def restock(self, notes: list[tuple[int, int]], hardware: Hardware | None = None) -> str:
if self.card is not None:
raise AtmError("customer session in progress")
self.cash = build_chain(notes)
self.hardware = hardware or Hardware()
self.state = Idle()
return f"restocked {self.cash_summary()}"
def next_txn_id(self) -> str:
self._seq += 1
return f"{self.id}-{self._seq:04d}"
def end_session(self) -> None:
self.card = self.account = None
self.state = Idle()
def cash_total(self) -> int:
return sum(c.value * c.count for c in cassettes(self.cash))
def cash_summary(self) -> str:
return " + ".join(f"{c.value}x{c.count}" for c in cassettes(self.cash) if c.count)
# ---------------- demo ----------------
def step(atm: ATM, label: str, fn, *args) -> None:
try:
out = fn(*args)
except AtmError as e:
out = f"refused: {e}"
print(f" {atm.id} {label:<16} {out} [{atm.state.name}]")
def main() -> None:
bank = Bank()
bank.open_account("ASHA", 12_000, daily_limit=5_000)
bank.open_account("RAVI", 3_000, daily_limit=25_000)
bank.open_account("MEERA", 20_000, daily_limit=25_000)
bank.open_account("FAMILY", 5_000, daily_limit=50_000)
bank.issue_card("4111-01", "1234", "ASHA")
bank.issue_card("4111-02", "4321", "RAVI")
bank.issue_card("4111-03", "2468", "MEERA")
a1 = ATM("ATM01", bank, [(500, 10), (200, 10), (100, 10)])
a2 = ATM("ATM02", bank, [(500, 4), (200, 3)])
print("1) One session, every state")
step(a1, "withdraw 1000", a1.withdraw, 1000)
step(a1, "insert 4111-01", a1.insert_card, "4111-01")
step(a1, "balance", a1.balance)
step(a1, "PIN 9999", a1.enter_pin, "9999")
step(a1, "PIN 1234", a1.enter_pin, "1234")
step(a1, "balance", a1.balance)
step(a1, "withdraw 150", a1.withdraw, 150)
step(a1, "withdraw 15000", a1.withdraw, 15000)
step(a1, "withdraw 2600", a1.withdraw, 2600)
print("\n2) Daily limit is the bank's rule, not the ATM's")
step(a1, "insert 4111-01", a1.insert_card, "4111-01")
step(a1, "PIN 1234", a1.enter_pin, "1234")
step(a1, "withdraw 3000", a1.withdraw, 3000)
step(a1, "withdraw 2400", a1.withdraw, 2400)
print(f" ATM01 cassettes now {a1.cash_summary()} = Rs {a1.cash_total()}")
print("\n3) Greedy vs the back-off chain, ATM02 loaded with", a2.cash_summary())
for amount in (600, 700, 800, 1100):
print(f" Rs {amount:>4}: greedy {fmt_plan(greedy_plan(a2.cash, amount)):<14}"
f"chain {fmt_plan(a2.cash.plan(amount))}")
step(a2, "insert 4111-02", a2.insert_card, "4111-02")
step(a2, "PIN 4321", a2.enter_pin, "4321")
step(a2, "withdraw 1100", a2.withdraw, 1100)
step(a2, "insert 4111-02", a2.insert_card, "4111-02")
step(a2, "PIN 4321", a2.enter_pin, "4321")
step(a2, "withdraw 200", a2.withdraw, 200)
step(a2, "withdraw 2000", a2.withdraw, 2000)
step(a2, "eject", a2.eject)
print("\n4) Replaying a debit (the ATM timed out and retried)")
bank.debit("ATM09-0042", "RAVI", 500)
print(f" debit ATM09-0042 Rs 500 -> balance Rs {bank.balance('RAVI')}")
bank.debit("ATM09-0042", "RAVI", 500)
print(f" replay ATM09-0042 Rs 500 -> balance Rs {bank.balance('RAVI')}")
for label in ("debit ", "replay"):
try:
bank.debit("ATM09-0043", "RAVI", 5000)
except AtmError as e:
print(f" {label} ATM09-0043 Rs 5000 -> refused: {e}")
print("\n5) Dispenser jams after 3 notes")
a3 = ATM("ATM03", bank, [(500, 10)], hardware=JammingHardware(jam_after=3))
step(a3, "insert 4111-03", a3.insert_card, "4111-03")
step(a3, "PIN 2468", a3.enter_pin, "2468")
step(a3, "withdraw 2000", a3.withdraw, 2000)
step(a3, "insert 4111-03", a3.insert_card, "4111-03")
step(a3, "restock", a3.restock, [(500, 20)])
step(a3, "insert 4111-03", a3.insert_card, "4111-03")
step(a3, "PIN 2468", a3.enter_pin, "2468")
step(a3, "balance", a3.balance)
step(a3, "eject", a3.eject)
print("\n6) Wrong PINs are counted by the bank, across ATMs")
step(a1, "insert 4111-02", a1.insert_card, "4111-02")
step(a1, "PIN 0000", a1.enter_pin, "0000")
step(a1, "PIN 1111", a1.enter_pin, "1111")
step(a1, "eject", a1.eject)
step(a2, "insert 4111-02", a2.insert_card, "4111-02")
step(a2, "PIN 2222", a2.enter_pin, "2222")
step(a1, "insert 4111-02", a1.insert_card, "4111-02")
print("\n7) Ten ATMs debit Rs 1000 each from one Rs 5000 account at the same moment")
gate = threading.Barrier(10)
ok, refused = [], []
tally = threading.Lock()
def hit(i: int) -> None:
gate.wait()
try:
bank.debit(f"J-{i}", "FAMILY", 1000)
result = ok
except AtmError:
result = refused
with tally:
result.append(i)
threads = [threading.Thread(target=hit, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f" {len(ok)} debited, {len(refused)} refused, balance Rs {bank.balance('FAMILY')}")
if __name__ == "__main__":
main()
Java
// ATM low-level design: State pattern for the session, a chain of cassettes
// for cash, idempotent debits, and a reversal when the dispenser jams.
// Run: javac Atm.java && java Atm
import java.util.*;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public class Atm {
/** A refused operation. The message is what the screen shows. */
static class AtmError extends RuntimeException {
AtmError(String msg) { super(msg); }
}
// ---------------- bank side: the ATM never holds a balance ----------------
static class Account {
final String number;
final int dailyLimit;
int balance, withdrawnToday;
final Map<String, String> outcomes = new HashMap<>(); // txn id -> "ok" or the refusal
final ReentrantLock lock = new ReentrantLock();
Account(String number, int balance, int dailyLimit) {
this.number = number; this.balance = balance; this.dailyLimit = dailyLimit;
}
}
static class Bank {
static final int MAX_PIN_TRIES = 3;
private final Map<String, Account> accounts = new HashMap<>();
private final Map<String, String[]> cards = new HashMap<>(); // card -> {pin, account}
private final Map<String, Integer> wrongPins = new HashMap<>();
void openAccount(String number, int balance, int dailyLimit) {
accounts.put(number, new Account(number, balance, dailyLimit));
}
void issueCard(String card, String pin, String number) { cards.put(card, new String[]{pin, number}); }
synchronized boolean isBlocked(String card) { return wrongPins.getOrDefault(card, 0) >= MAX_PIN_TRIES; }
/** Returns the account number. The wrong-PIN count lives here, not in the ATM. */
synchronized String verifyPin(String card, String pin) {
if (!cards.containsKey(card)) throw new AtmError("card not recognised");
int tries = wrongPins.getOrDefault(card, 0);
if (tries >= MAX_PIN_TRIES) throw new AtmError("card blocked, contact your bank");
String[] entry = cards.get(card);
if (entry[0].equals(pin)) {
wrongPins.put(card, 0);
return entry[1];
}
tries++;
wrongPins.put(card, tries);
int left = MAX_PIN_TRIES - tries;
if (left == 0) throw new AtmError("wrong PIN, card blocked");
throw new AtmError("wrong PIN, " + left + (left == 1 ? " try" : " tries") + " left");
}
int balance(String number) {
Account a = accounts.get(number);
a.lock.lock();
try { return a.balance; } finally { a.lock.unlock(); }
}
/** Idempotent: a replayed txn id gets the first outcome again and moves no money. */
void debit(String txnId, String number, int amount) {
Account a = accounts.get(number);
String outcome;
a.lock.lock();
try {
outcome = a.outcomes.computeIfAbsent(txnId, id -> tryDebit(a, amount));
} finally { a.lock.unlock(); }
if (!outcome.equals("ok")) throw new AtmError(outcome);
}
private static String tryDebit(Account a, int amount) {
if (amount > a.balance) return "insufficient funds (balance Rs " + a.balance + ")";
if (a.withdrawnToday + amount > a.dailyLimit)
return "daily limit, Rs " + (a.dailyLimit - a.withdrawnToday) + " left today";
a.balance -= amount;
a.withdrawnToday += amount;
return "ok";
}
/** Credit back the undispensed part of a debit. Keyed on the original id, so retries are safe. */
void reverse(String txnId, String number, int amount) {
Account a = accounts.get(number);
a.lock.lock();
try {
String key = "REV:" + txnId;
if (a.outcomes.containsKey(key)) return;
if (!"ok".equals(a.outcomes.get(txnId)))
throw new IllegalStateException("nothing to reverse for " + txnId);
a.balance += amount;
a.withdrawnToday -= amount;
a.outcomes.put(key, "ok");
} finally { a.lock.unlock(); }
}
}
// ---------------- cash side: hardware plus a chain of cassettes ----------------
/** The note feeder. Returns how many notes physically came out. */
static class Hardware {
int feed(int value, int count) { return count; }
}
/** Test double: delivers jamAfter notes in total, then jams. */
static class JammingHardware extends Hardware {
int left;
JammingHardware(int jamAfter) { left = jamAfter; }
@Override int feed(int value, int count) {
int out = Math.min(count, left);
left -= out;
return out;
}
}
/** One link in the chain: pays what it can in its own note and hands the rest on. */
static class Cassette {
final int value;
int count;
final Cassette next;
Cassette(int value, int count, Cassette next) { this.value = value; this.count = count; this.next = next; }
/** Notes per value that make amount, or null. Tries the most notes first, backs off one at a time. */
LinkedHashMap<Integer, Integer> plan(int amount) {
int most = Math.min(count, amount / value);
for (int take = most; take >= 0; take--) {
int rest = amount - take * value;
LinkedHashMap<Integer, Integer> mine = new LinkedHashMap<>();
if (take > 0) mine.put(value, take);
if (rest == 0) return mine;
if (next == null) return null; // fewer notes here only leaves more for nobody
LinkedHashMap<Integer, Integer> below = next.plan(rest);
if (below != null) { mine.putAll(below); return mine; }
}
return null;
}
/** Feeds the planned notes, top of the chain first. Returns the amount actually paid out. */
int dispense(Map<Integer, Integer> plan, Hardware hw) {
int want = plan.getOrDefault(value, 0);
int got = want > 0 ? hw.feed(value, want) : 0;
count -= got;
int paid = got * value;
if (got < want || next == null) return paid; // jammed: stop, do not keep feeding
return paid + next.dispense(plan, hw);
}
}
static Cassette buildChain(int[][] notes) {
int[][] sorted = notes.clone();
Arrays.sort(sorted, Comparator.comparingInt(n -> n[0]));
Cassette head = null;
for (int[] n : sorted) head = new Cassette(n[0], n[1], head); // smallest first, so the largest ends up on top
return head;
}
/** The textbook version, for comparison: largest note first, never reconsiders. */
static LinkedHashMap<Integer, Integer> greedyPlan(Cassette head, int amount) {
LinkedHashMap<Integer, Integer> plan = new LinkedHashMap<>();
for (Cassette c = head; c != null; c = c.next) {
int take = Math.min(c.count, amount / c.value);
if (take > 0) plan.put(c.value, take);
amount -= take * c.value;
}
return amount == 0 ? plan : null;
}
static String fmtPlan(Map<Integer, Integer> plan) {
if (plan == null) return "impossible";
StringJoiner sj = new StringJoiner(" + ");
plan.forEach((v, n) -> sj.add(v + "x" + n));
return sj.toString();
}
// ---------------- the ATM and its states ----------------
static abstract class State {
abstract String name();
abstract String hint();
String insertCard(Machine atm, String card) { throw new AtmError(hint()); }
String enterPin(Machine atm, String pin) { throw new AtmError(hint()); }
String balance(Machine atm) { throw new AtmError(hint()); }
String withdraw(Machine atm, int amount) { throw new AtmError(hint()); }
String eject(Machine atm) { throw new AtmError(hint()); }
}
static class Idle extends State {
String name() { return "Idle"; }
String hint() { return "insert your card first"; }
@Override String insertCard(Machine atm, String card) {
if (atm.bank.isBlocked(card)) throw new AtmError("card blocked, contact your bank");
atm.card = card;
atm.state = new HasCard();
return "enter PIN";
}
}
static class HasCard extends State {
String name() { return "HasCard"; }
String hint() { return "enter your PIN first"; }
@Override String enterPin(Machine atm, String pin) {
try {
atm.account = atm.bank.verifyPin(atm.card, pin);
} catch (AtmError e) {
if (atm.bank.isBlocked(atm.card)) atm.endSession();
throw e;
}
atm.state = new Authenticated();
return "PIN ok";
}
@Override String eject(Machine atm) { atm.endSession(); return "card returned"; }
}
static class Authenticated extends State {
String name() { return "Authenticated"; }
String hint() { return "card already inserted"; }
@Override String balance(Machine atm) { return "balance Rs " + atm.bank.balance(atm.account); }
@Override String withdraw(Machine atm, int amount) {
if (amount <= 0 || amount % 100 != 0) throw new AtmError("amount must be a multiple of Rs 100");
if (amount > atm.maxPerTxn) throw new AtmError("maximum Rs " + atm.maxPerTxn + " per withdrawal");
Map<Integer, Integer> plan = atm.cash.plan(amount);
if (plan == null)
throw new AtmError("cannot pay Rs " + amount + " with the notes loaded (" + atm.cashSummary() + ")");
String txn = atm.nextTxnId();
atm.bank.debit(txn, atm.account, amount); // refused -> nothing dispensed, nothing to undo
int paid = atm.cash.dispense(plan, atm.hardware);
if (paid < amount) {
atm.bank.reverse(txn, atm.account, amount - paid);
atm.endSession();
atm.state = new OutOfService();
return txn + " paid Rs " + paid + " of " + amount + ", Rs " + (amount - paid) + " credited back, card returned";
}
atm.endSession();
if (atm.cashTotal() < 100) atm.state = new OutOfService();
return txn + " paid " + fmtPlan(plan) + ", card returned";
}
@Override String eject(Machine atm) { atm.endSession(); return "card returned"; }
}
static class OutOfService extends State {
String name() { return "OutOfService"; }
String hint() { return "out of service"; }
}
static class Machine {
final String id;
final Bank bank;
final int maxPerTxn;
Cassette cash;
Hardware hardware;
State state = new Idle();
String card, account;
private int seq;
Machine(String id, Bank bank, int[][] notes) { this(id, bank, notes, new Hardware(), 10_000); }
Machine(String id, Bank bank, int[][] notes, Hardware hardware, int maxPerTxn) {
this.id = id; this.bank = bank; this.maxPerTxn = maxPerTxn;
this.cash = buildChain(notes);
this.hardware = hardware;
}
String insertCard(String card) { return state.insertCard(this, card); }
String enterPin(String pin) { return state.enterPin(this, pin); }
String balance() { return state.balance(this); }
String withdraw(int amount) { return state.withdraw(this, amount); }
String eject() { return state.eject(this); }
String restock(int[][] notes) {
if (card != null) throw new AtmError("customer session in progress");
cash = buildChain(notes);
hardware = new Hardware();
state = new Idle();
return "restocked " + cashSummary();
}
String nextTxnId() { return String.format("%s-%04d", id, ++seq); }
void endSession() { card = null; account = null; state = new Idle(); }
int cashTotal() {
int t = 0;
for (Cassette c = cash; c != null; c = c.next) t += c.value * c.count;
return t;
}
String cashSummary() {
StringJoiner sj = new StringJoiner(" + ");
for (Cassette c = cash; c != null; c = c.next) if (c.count > 0) sj.add(c.value + "x" + c.count);
return sj.toString();
}
}
// ---------------- demo ----------------
interface Action { String run(); }
static void step(Machine atm, String label, Action fn) {
String out;
try { out = fn.run(); } catch (AtmError e) { out = "refused: " + e.getMessage(); }
System.out.println(String.format(" %s %-16s %s [%s]", atm.id, label, out, atm.state.name()));
}
public static void main(String[] args) throws Exception {
Bank bank = new Bank();
bank.openAccount("ASHA", 12_000, 5_000);
bank.openAccount("RAVI", 3_000, 25_000);
bank.openAccount("MEERA", 20_000, 25_000);
bank.openAccount("FAMILY", 5_000, 50_000);
bank.issueCard("4111-01", "1234", "ASHA");
bank.issueCard("4111-02", "4321", "RAVI");
bank.issueCard("4111-03", "2468", "MEERA");
Machine a1 = new Machine("ATM01", bank, new int[][]{{500, 10}, {200, 10}, {100, 10}});
Machine a2 = new Machine("ATM02", bank, new int[][]{{500, 4}, {200, 3}});
System.out.println("1) One session, every state");
step(a1, "withdraw 1000", () -> a1.withdraw(1000));
step(a1, "insert 4111-01", () -> a1.insertCard("4111-01"));
step(a1, "balance", a1::balance);
step(a1, "PIN 9999", () -> a1.enterPin("9999"));
step(a1, "PIN 1234", () -> a1.enterPin("1234"));
step(a1, "balance", a1::balance);
step(a1, "withdraw 150", () -> a1.withdraw(150));
step(a1, "withdraw 15000", () -> a1.withdraw(15000));
step(a1, "withdraw 2600", () -> a1.withdraw(2600));
System.out.println("\n2) Daily limit is the bank's rule, not the ATM's");
step(a1, "insert 4111-01", () -> a1.insertCard("4111-01"));
step(a1, "PIN 1234", () -> a1.enterPin("1234"));
step(a1, "withdraw 3000", () -> a1.withdraw(3000));
step(a1, "withdraw 2400", () -> a1.withdraw(2400));
System.out.println(" ATM01 cassettes now " + a1.cashSummary() + " = Rs " + a1.cashTotal());
System.out.println("\n3) Greedy vs the back-off chain, ATM02 loaded with " + a2.cashSummary());
for (int amount : new int[]{600, 700, 800, 1100})
System.out.println(String.format(" Rs %4d: greedy %-14schain %s",
amount, fmtPlan(greedyPlan(a2.cash, amount)), fmtPlan(a2.cash.plan(amount))));
step(a2, "insert 4111-02", () -> a2.insertCard("4111-02"));
step(a2, "PIN 4321", () -> a2.enterPin("4321"));
step(a2, "withdraw 1100", () -> a2.withdraw(1100));
step(a2, "insert 4111-02", () -> a2.insertCard("4111-02"));
step(a2, "PIN 4321", () -> a2.enterPin("4321"));
step(a2, "withdraw 200", () -> a2.withdraw(200));
step(a2, "withdraw 2000", () -> a2.withdraw(2000));
step(a2, "eject", a2::eject);
System.out.println("\n4) Replaying a debit (the ATM timed out and retried)");
bank.debit("ATM09-0042", "RAVI", 500);
System.out.println(" debit ATM09-0042 Rs 500 -> balance Rs " + bank.balance("RAVI"));
bank.debit("ATM09-0042", "RAVI", 500);
System.out.println(" replay ATM09-0042 Rs 500 -> balance Rs " + bank.balance("RAVI"));
for (String label : new String[]{"debit ", "replay"}) {
try { bank.debit("ATM09-0043", "RAVI", 5000); }
catch (AtmError e) { System.out.println(" " + label + " ATM09-0043 Rs 5000 -> refused: " + e.getMessage()); }
}
System.out.println("\n5) Dispenser jams after 3 notes");
Machine a3 = new Machine("ATM03", bank, new int[][]{{500, 10}}, new JammingHardware(3), 10_000);
step(a3, "insert 4111-03", () -> a3.insertCard("4111-03"));
step(a3, "PIN 2468", () -> a3.enterPin("2468"));
step(a3, "withdraw 2000", () -> a3.withdraw(2000));
step(a3, "insert 4111-03", () -> a3.insertCard("4111-03"));
step(a3, "restock", () -> a3.restock(new int[][]{{500, 20}}));
step(a3, "insert 4111-03", () -> a3.insertCard("4111-03"));
step(a3, "PIN 2468", () -> a3.enterPin("2468"));
step(a3, "balance", a3::balance);
step(a3, "eject", a3::eject);
System.out.println("\n6) Wrong PINs are counted by the bank, across ATMs");
step(a1, "insert 4111-02", () -> a1.insertCard("4111-02"));
step(a1, "PIN 0000", () -> a1.enterPin("0000"));
step(a1, "PIN 1111", () -> a1.enterPin("1111"));
step(a1, "eject", a1::eject);
step(a2, "insert 4111-02", () -> a2.insertCard("4111-02"));
step(a2, "PIN 2222", () -> a2.enterPin("2222"));
step(a1, "insert 4111-02", () -> a1.insertCard("4111-02"));
System.out.println("\n7) Ten ATMs debit Rs 1000 each from one Rs 5000 account at the same moment");
CyclicBarrier gate = new CyclicBarrier(10);
AtomicInteger ok = new AtomicInteger(), refused = new AtomicInteger();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int n = i;
threads.add(new Thread(() -> {
try { gate.await(); } catch (Exception e) { throw new RuntimeException(e); }
try { bank.debit("J-" + n, "FAMILY", 1000); ok.incrementAndGet(); }
catch (AtmError e) { refused.incrementAndGet(); }
}));
}
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
System.out.println(" " + ok.get() + " debited, " + refused.get() + " refused, balance Rs " + bank.balance("FAMILY"));
}
}
Output
1) One session, every state
ATM01 withdraw 1000 refused: insert your card first [Idle]
ATM01 insert 4111-01 enter PIN [HasCard]
ATM01 balance refused: enter your PIN first [HasCard]
ATM01 PIN 9999 refused: wrong PIN, 2 tries left [HasCard]
ATM01 PIN 1234 PIN ok [Authenticated]
ATM01 balance balance Rs 12000 [Authenticated]
ATM01 withdraw 150 refused: amount must be a multiple of Rs 100 [Authenticated]
ATM01 withdraw 15000 refused: maximum Rs 10000 per withdrawal [Authenticated]
ATM01 withdraw 2600 ATM01-0001 paid 500x5 + 100x1, card returned [Idle]
2) Daily limit is the bank's rule, not the ATM's
ATM01 insert 4111-01 enter PIN [HasCard]
ATM01 PIN 1234 PIN ok [Authenticated]
ATM01 withdraw 3000 refused: daily limit, Rs 2400 left today [Authenticated]
ATM01 withdraw 2400 ATM01-0003 paid 500x4 + 200x2, card returned [Idle]
ATM01 cassettes now 500x1 + 200x8 + 100x9 = Rs 3000
3) Greedy vs the back-off chain, ATM02 loaded with 500x4 + 200x3
Rs 600: greedy impossible chain 200x3
Rs 700: greedy 500x1 + 200x1 chain 500x1 + 200x1
Rs 800: greedy impossible chain impossible
Rs 1100: greedy impossible chain 500x1 + 200x3
ATM02 insert 4111-02 enter PIN [HasCard]
ATM02 PIN 4321 PIN ok [Authenticated]
ATM02 withdraw 1100 ATM02-0001 paid 500x1 + 200x3, card returned [Idle]
ATM02 insert 4111-02 enter PIN [HasCard]
ATM02 PIN 4321 PIN ok [Authenticated]
ATM02 withdraw 200 refused: cannot pay Rs 200 with the notes loaded (500x3) [Authenticated]
ATM02 withdraw 2000 refused: cannot pay Rs 2000 with the notes loaded (500x3) [Authenticated]
ATM02 eject card returned [Idle]
4) Replaying a debit (the ATM timed out and retried)
debit ATM09-0042 Rs 500 -> balance Rs 1400
replay ATM09-0042 Rs 500 -> balance Rs 1400
debit ATM09-0043 Rs 5000 -> refused: insufficient funds (balance Rs 1400)
replay ATM09-0043 Rs 5000 -> refused: insufficient funds (balance Rs 1400)
5) Dispenser jams after 3 notes
ATM03 insert 4111-03 enter PIN [HasCard]
ATM03 PIN 2468 PIN ok [Authenticated]
ATM03 withdraw 2000 ATM03-0001 paid Rs 1500 of 2000, Rs 500 credited back, card returned [OutOfService]
ATM03 insert 4111-03 refused: out of service [OutOfService]
ATM03 restock restocked 500x20 [Idle]
ATM03 insert 4111-03 enter PIN [HasCard]
ATM03 PIN 2468 PIN ok [Authenticated]
ATM03 balance balance Rs 18500 [Authenticated]
ATM03 eject card returned [Idle]
6) Wrong PINs are counted by the bank, across ATMs
ATM01 insert 4111-02 enter PIN [HasCard]
ATM01 PIN 0000 refused: wrong PIN, 2 tries left [HasCard]
ATM01 PIN 1111 refused: wrong PIN, 1 try left [HasCard]
ATM01 eject card returned [Idle]
ATM02 insert 4111-02 enter PIN [HasCard]
ATM02 PIN 2222 refused: wrong PIN, card blocked [Idle]
ATM01 insert 4111-02 refused: card blocked, contact your bank [Idle]
7) Ten ATMs debit Rs 1000 each from one Rs 5000 account at the same moment
5 debited, 5 refused, balance Rs 0
What to look for in the output:
- Demo 1 goes through every state: a withdrawal refused in Idle, a balance request refused before the PIN, one wrong PIN, then the amount checks. ₹150 and ₹15,000 are rejected on the machine without a transaction id; ₹2,600 becomes 500x5 + 100x1 and the card comes back.
- Demo 2 is the daily limit. Asha has a ₹5,000 limit and has taken ₹2,600, so the bank refuses ₹3,000 and says ₹2,400 is left. Notice the successful withdrawal is
ATM01-0003: the refused request used0002. Every request that reaches the bank gets an id, including the ones it refuses, so the logs on both sides line up. - Demo 3 is the greedy bug on a machine with 500x4 + 200x3. Greedy fails ₹600 and ₹1,100; the back-off chain pays both. ₹800 fails in both, correctly: it needs four ₹200s or a ₹100. After Ravi takes ₹1,100 the machine holds only three ₹500s, so ₹200 is refused, and ₹2,000 is refused by the machine before the bank could even say his balance is too low.
- Demo 4 replays transaction ids directly against the bank. The second debit of
ATM09-0042changes nothing, and the refusedATM09-0043is refused again with the same message. - Demo 5 is the jam. Meera asks for ₹2,000, the plan is four ₹500s, the feeder stops after three. ₹2,000 was debited, ₹1,500 came out, ₹500 is credited back under the same id, and the machine refuses the next card until it is restocked. Her balance afterwards is ₹18,500, which is exactly what she has in her hand.
- Demo 6: two wrong PINs at ATM01, eject, walk to ATM02, one more wrong PIN and the card is blocked. ATM01 now refuses the card at insertion, before asking for a PIN.
- Demo 7: ten threads, standing in for ten machines, each debit ₹1,000 from a ₹5,000 account after a barrier releases them together. Exactly five succeed and the balance ends at zero.
Interviewer follow-ups
“Two people withdraw from the same joint account at two ATMs at the same moment.” The check and the deduction have to be one atomic step on the bank side; the ATMs cannot help, because neither knows the other exists. In the code that is the per-account lock around _try_debit. To show what happens without it, I took the lock out of a ten-thread version of demo 7 and added a 1 ms sleep between the balance check and the deduction, standing in for the call to the core banking system. All ten debits succeeded and the balance went to -₹5,000, in five runs out of five. In a real bank the same thing is a single conditional update (UPDATE accounts SET balance = balance - 1000 WHERE id = ? AND balance >= 1000, then check the row count) or a row lock inside a database transaction. Per-account locks rather than one bank-wide lock, so that withdrawals from different accounts never wait for each other.
“How does this work with thousands of ATMs?” The ATMs stay dumb about balances and talk to the bank through a switch. Each machine’s state, cassette counts and transaction counter are local to it. What has to be globally unique is the transaction id, which is why it starts with the machine id: two machines can each issue -0001 without a coordination service. Balance correctness is entirely the bank’s job, as above. The per-machine part that does need care is the counter: it must survive a reboot, or the machine will reissue ATM01-0001 and the bank’s idempotency check will hand back an old outcome for a new withdrawal. Persist the counter before using it.
“The dispenser jammed half way. What exactly happens?” Demo 5. dispense reports what came out, the ATM reverses the shortfall against the original transaction id, the machine goes out of service. Three details I would add in the interview. Real dispensers count notes as they leave and divert doubtful ones (two stuck together, torn) into a reject bin, so “what came out” is a sensor reading, and the operator reconciles cassette, reject bin and journal at restock. The reversal call can itself time out, so it is idempotent too (REV: plus the original id) and the ATM retries it until the bank acknowledges. And if the machine cannot reach the bank at all, it writes the reversal to its local journal and sends it when the link comes back; the customer gets a slip saying so.
“The ATM crashed after the debit but before dispensing.” This is the case the code does not cover, and it is the best follow-up of the lot. In-memory state is gone; the bank has a debit with no matching dispense. The fix is a write-ahead journal on the machine’s disk: write “txn ATM01-0007, ₹2,000, debit requested” before calling the bank, “debited” after, “dispensed ₹X” after the hardware returns. On restart, any transaction marked debited but not dispensed gets a reversal for the full amount, and any marked dispensed with X less than the amount gets a reversal for the difference. This is where I would introduce Command objects: a journal entry is a serialised command with enough information to complete or undo it.
“Make every transaction idempotent.” Already done for debits and reversals: the bank keys outcomes by transaction id. The things to get right are where the id is created (on the ATM, once per customer request, before the first network call, never regenerated on retry), what is stored (the outcome, including refusals, as explained above), and for how long. Storing outcomes forever per account is a memory leak in a long-lived system; the real rule is “long enough to outlast any retry”, typically the settlement window, after which the ids can be archived.
“Add cash deposit.” The design changes more than it looks. Deposit is the reverse order: notes go in, the machine counts and validates them, the customer confirms the total, then the bank credits. Until the credit is confirmed the notes sit in an escrow tray, so if it fails they can be handed straight back. On the machine side the cassettes now gain notes, so Cassette needs accept(n) and a capacity. On the session side it is a new action in Authenticated and probably a new CountingNotes state, because the customer can cancel while the machine shows the count.
“Restock while a customer is mid-session.” The code refuses: restock checks there is no card in the machine. In reality the operator opens the safe only when the machine is out of service, so you would add an operator-initiated transition into OutOfService that waits for the current session to end.
“How do you test the jam without a jammed machine?” Same answer as the dice in snake and ladder: Hardware is injected, and JammingHardware(3) jams on cue. Every failure path in demo 5 runs on every build.
Mistakes that cost marks
- Storing the balance on the ATM or on a
Cardobject. Then two machines each hold a copy, both approve, and the account is overdrawn. The ATM asks; the bank decides. - Dispensing first and debiting second. Covered above. If the debit fails after the notes are out, there is no way to get them back.
- Debiting before checking the cassettes. Not wrong in money terms, because a reversal fixes it, but it creates a reversal for every “this machine cannot pay ₹600” case and a confusing SMS for the customer.
- Greedy dispensing presented as correct. It is fine with unlimited notes of 100, 200 and 500. With a finite stock it refuses amounts the machine could pay. Know the ₹600-with-no-₹100s example.
- A new transaction id on every retry. Then the retry is a second withdrawal as far as the bank can tell. The id belongs to the customer’s request, not to the network attempt.
- Counting wrong PINs on the ATM. It resets on eject, and the limit is per machine instead of per card.
if self.out_of_service: ...scattered through the methods. Use the state. A guard that has to be remembered in every method is eventually forgotten in one.- One lock for the whole bank. Correct and slow: a withdrawal in Pune waits for a balance check in Chennai. Lock per account.
floatfor money. ₹0.1 + ₹0.2 is not ₹0.3 in binary floating point. The code uses whole rupees inint; a real system uses paise in a 64-bit integer or a decimal type.
The next case study, Splitwise, stays with money but drops the hardware. The hard parts there are a paisa that will not divide evenly, balances that must survive edits and deletes, and a settle-up question where the obvious greedy answer is not the best one.
Key takeaways
- The ATM owns notes; the bank owns balances. Most of the design falls out of keeping those apart.
- State pattern for the session: four states, each overriding only what it allows, with refusals coming from the base class.
- Chain of Responsibility for denominations, but with back-off instead of pure greedy, and with
plan(no side effects) split fromdispense. - Validate on the machine, plan the notes, debit with a transaction id, dispense, reverse any shortfall against the same id.
- Idempotency and per-account locking live in the bank. Without the lock, ten simultaneous ₹1,000 withdrawals from ₹5,000 all succeeded in the test above.
Exercises
- Add an “another transaction?” prompt: after a successful withdrawal, stay in
Authenticatedfor up to one more action, then return the card. Which existing transition changes, and does any state need new data? - Add a
fewest_notesoption toCassette.planusing dynamic programming over the amount (in steps of ₹100), and check it agrees with the back-off chain on every amount from ₹100 to ₹10,000 for the 500x4 + 200x3 load. - Write the crash-recovery journal: append each step of a withdrawal to a list that stands in for the disk, then write a
recover()that, given the journal of a machine that “crashed” after the debit, issues the right reversal. - In the Java version, remove the lock from
Bank.debitand put a 1 ms sleep between the balance check and the deduction. How many of demo 7’s ten debits succeed? Then make the balance anAtomicIntegerand debit with acompareAndSetloop instead of the lock. What gets retried when two threads collide, and why can the balance no longer go negative even with the sleep still there?
Quiz
- Why does the ATM call
planbeforedebit, anddebitbeforedispense? - A machine holds 500x4 + 200x3 and no ₹100s. What does textbook greedy dispensing do with a ₹1,100 request, and what does the back-off chain do?
- The ATM sends a debit, the request times out, and it resends. What must be the same in both requests, and what does the bank do with the second one?
- Why is the wrong-PIN counter kept by the bank rather than by the ATM?
- Dispensing a ₹2,000 withdrawal stops after three ₹500 notes. List what the code does, in order.
Show answers
planfirst so that an amount the cassettes cannot make is refused without touching the account.debitbeforedispensebecause a failed dispense after a debit can be fixed with a reversal, while a failed debit after a dispense means the money is gone.- Greedy takes two ₹500s, is left with ₹100 that no cassette holds, and refuses. The back-off chain tries two ₹500s, fails, tries one ₹500, and pays the remaining ₹600 with three ₹200s: 500x1 + 200x3.
- The transaction id. The bank finds that id already in the account’s outcome map and returns the stored outcome (success or the same refusal) without moving money again.
- A counter on the ATM resets when the card is ejected and only counts tries at that one machine, so a thief could keep moving between machines. The bank sees every attempt on the card from every machine.
- The bank has already debited ₹2,000.
dispensereturns ₹1,500 paid. The ATM callsreversefor ₹500 with the same transaction id, ends the session (card returned), and switches toOutOfService, so the next card is refused untilrestock.