On this page

Design ATM Machine

The ATM machine is a classic LLD interview problem that tests your ability to model a state machine cleanly. The ATM has a well-defined lifecycle: idle, card inserted, PIN validated, transaction selected, processing, dispensing, and back to idle. Each state has specific allowed transitions, and invalid transitions must be rejected gracefully.

Two more things separate a strong answer. Dispensing notes is a planning problem, and this page solves it with a Chain of Responsibility that can back off when greedy fails. Money is shared: one account can be used at two ATMs at once, so the balance check has to happen atomically in the bank, not in the ATM. The page follows the LLD interview framework and keeps the original walkthrough code, with corrections marked.

Requirements

Clarifying questions

QuestionTypical answerWhy it matters
Which transactions?Balance and withdrawal first, deposit laterDeposit is Extension A
Which notes, and how many cassettes?100, 200, 500 and 2000, one cassette each200 breaks greedy dispensing
Who counts wrong PINs?The bank, per cardA per-session counter resets when the card is re-inserted
Can one account be used at two ATMs at once?YesThe balance check must be atomic at the bank
What if the cash jams?The customer must not be chargedThe debit needs a compensation
More than one transaction per card insertion?YesThe session returns to "authenticated", not "idle"
Limits?A daily withdrawal limit, laterExtension B, enforced in the bank

Functional Requirements

#RequirementDetails
FR-1Card insertionAccept and validate bank cards
FR-2PIN authenticationValidate PIN with max 3 attempts
FR-3Balance inquiryDisplay current account balance
FR-4Cash withdrawalDispense cash if sufficient balance and ATM has funds
FR-5Cash depositAccept and credit cash deposits
FR-6Fund transferTransfer between accounts at the same bank
FR-7Receipt printingPrint transaction receipt
FR-8Card ejectionReturn card on completion or timeout

Non-Functional Requirements

  • Single ATM machine (not distributed)
  • Thread-safe transaction processing
  • Timeout handling (eject card after inactivity)
  • Denomination-aware dispensing
  • Money as integers. A failed step never leaves the customer charged for cash they didn't get

Core Entities

EntityResponsibilityLives in
AtmThe State pattern's context. Holds one card session and delegates each event to the current stateThe machine
AtmState and subclassesWhat each event means now: Idle, CardInserted, AuthenticatedThe machine
CashDispenserThe cassettes. Reserves and releases notes atomicallyThe machine
NoteHandlerOne link in the chain: one denomination, its count, and the next handlerThe machine
BankBalances, cards, PIN attempts, daily limits. Every check-and-update on moneyShared by all ATMs
AccountAn id, a balance and a lockThe bank

The split that matters is machine versus bank. Whatever describes the physical machine (the session, the cassettes) belongs to the ATM. Whatever must hold across machines (balances, attempts, limits) belongs to the bank. Getting this wrong is the source of three of the corrections on this page.

classDiagram
    class ATM {
        -state: ATMState
        -cashDispenser: CashDispenser
        -cardReader: CardReader
        -bankService: BankService
        +insertCard(card)
        +enterPin(pin)
        +selectTransaction(type)
        +confirmTransaction(amount)
        +cancel()
    }

    class ATMState {
        <<interface>>
        +insertCard(atm, card)
        +enterPin(atm, pin)
        +selectTransaction(atm, type)
        +confirmTransaction(atm, amount)
        +cancel(atm)
    }

    class CashDispenser {
        -denominations: Map
        +dispense(amount): Bill[]
        +canDispense(amount): boolean
        +addCash(denomination, count)
    }

    class BankService {
        <<interface>>
        +validateCard(cardNumber): boolean
        +validatePin(cardNumber, pin): boolean
        +getBalance(accountId): number
        +withdraw(accountId, amount): boolean
        +deposit(accountId, amount): boolean
        +transfer(from, to, amount): boolean
    }

    ATM --> ATMState
    ATM --> CashDispenser
    ATM --> BankService

Class diagram for the complete code

The diagram above matches the walkthrough. The complete code splits the bank's state from the ATM's, and replaces the dispenser's loop with a chain of note handlers:

classDiagram
    class Atm {
        -AtmState state
        -String card
        -String account
        +insertCard(card) void
        +enterPin(pin) PinResult
        +balance() long
        +withdraw(amount) Notes
        +eject() void
    }
    class AtmState {
        <<abstract>>
        +insertCard(atm, card) void
        +enterPin(atm, pin) PinResult
        +balance(atm) long
        +withdraw(atm, amount) Notes
        +eject(atm) void
    }
    class IdleState
    class CardInsertedState
    class AuthenticatedState
    class Bank {
        -Map~String, Account~ accounts
        -Map~String, int~ failedPins
        +verifyPin(card, pin) PinResult
        +withdraw(account, amount) bool
        +deposit(account, amount) void
        +transfer(from, to, amount) bool
    }
    class Account {
        +String id
        +long balance
        +Lock lock
    }
    class CashDispenser {
        +reserve(amount) Notes
        +release(notes) void
        +total() long
    }
    class NoteHandler {
        +int note
        +int count
        +plan(amount) Notes
    }
    Atm *-- AtmState
    Atm o-- Bank
    Atm *-- CashDispenser
    AtmState <|-- IdleState
    AtmState <|-- CardInsertedState
    AtmState <|-- AuthenticatedState
    Bank *-- Account
    CashDispenser *-- NoteHandler
    NoteHandler --> NoteHandler : next

The important line is Atm o-- Bank. The bank is shared by every ATM, so anything that must hold across ATMs, such as balances, PIN attempts and daily limits, lives in the bank, under the bank's locks. The ATM owns only what's physically inside it: the session and the cash.

State Machine Design

stateDiagram-v2
    [*] --> Idle
    Idle --> CardInserted: Insert Card
    CardInserted --> PinEntered: Enter PIN (valid)
    CardInserted --> Idle: Invalid Card / Cancel
    PinEntered --> TransactionSelected: Select Transaction
    PinEntered --> CardInserted: Wrong PIN (attempts < 3)
    PinEntered --> Idle: Wrong PIN (3rd attempt - retain card)
    TransactionSelected --> Processing: Confirm Transaction
    TransactionSelected --> TransactionSelected: Change Transaction
    TransactionSelected --> Idle: Cancel
    Processing --> Dispensing: Withdrawal Approved
    Processing --> TransactionSelected: Transaction Complete (non-cash)
    Processing --> Idle: Transaction Failed
    Dispensing --> Idle: Cash Taken / Timeout

Correction (2026-11-10)

This diagram doesn't match the walkthrough code. Wrong-PIN retries happen inside CardInsertedState, which stays put until the third failure, so the PinEntered --> CardInserted edge doesn't exist. Instead there's a self-loop on CardInserted. There are no Processing or Dispensing states in the code, and after every transaction the code resets to Idle. It never returns to TransactionSelected. The corrected lifecycle for the complete code, which does keep the session open between transactions, is in Key flows.

The state machine is the backbone of this design. Every user interaction triggers a state transition, and the ATM only accepts inputs valid for its current state.

Key flows

The lifecycle, as the complete code implements it

stateDiagram-v2
    [*] --> Idle
    Idle --> CardInserted: insert a known card
    CardInserted --> CardInserted: wrong PIN, tries left
    CardInserted --> Authenticated: correct PIN
    CardInserted --> Idle: third wrong PIN, card retained
    CardInserted --> Idle: eject
    Authenticated --> Authenticated: balance, withdraw, or a failed withdrawal
    Authenticated --> Idle: eject

After a transaction the customer stays in Authenticated and can do another. There's no Dispensing state because withdraw runs to completion. Asynchronous hardware would add one (see the follow-ups).

A withdrawal: reserve, debit, dispense

sequenceDiagram
    participant C as Customer
    participant A as Atm in Authenticated
    participant D as CashDispenser
    participant H as Note handlers 2000 to 100
    participant B as Bank
    C->>A: withdraw 600
    A->>D: reserve 600
    D->>H: plan 600
    H->>H: 2000 takes none, 500 tries one, 200 and 100 cannot finish 100
    H->>H: 500 backs off to none, 200 takes three
    H-->>D: three 200s
    D-->>A: notes reserved, removed from the count
    A->>B: withdraw 600 from the account
    B->>B: lock the account, check, debit, unlock
    B-->>A: OK
    A->>A: feed the notes out
    A-->>C: three 200 notes, still signed in

The order is the design. Reserving notes first means a debit is never made for cash the machine can't produce. Debiting before dispensing means cash never leaves for money the account doesn't have. And the last step can fail, so it's the one with a compensation.

A jam: compensate, don't strand the money

sequenceDiagram
    participant A as Atm
    participant D as CashDispenser
    participant B as Bank
    A->>D: reserve 700
    D-->>A: one 500 and one 200
    A->>B: withdraw 700
    B-->>A: OK
    A->>A: feed the notes out, the feeder reports a jam
    A->>B: deposit 700 back
    A->>D: release the reserved notes
    A-->>A: tell the customer they were not charged

In production the reversal carries the original transaction id, so the bank can apply it exactly once even if the ATM retries after a network error.

Design Patterns Used

PatternWhere UsedWhy
StateATM states (Idle, CardInserted, etc.)Each state encapsulates valid operations and transitions
StrategyCash dispensing algorithmCould swap denomination-selection strategies
Dependency InjectionBankService injected into ATMEnables testing with mock bank service
Template MethodTransaction processing flowSame flow for all transaction types with different steps

Correction (2026-11-10)

The Template Method row is inaccurate. Transaction processing in the walkthrough is a switch on the transaction type inside TransactionSelectedState. No base class defines a fixed algorithm with overridable steps. If you want a pattern there, Command fits better: one object per transaction type with an execute(atm) method, which also gives you a natural audit log.

State, and Chain of Responsibility, and why

State fits because the same button means different things in different modes. "Withdraw" before a PIN is an error, after it's a transaction. In the complete code each state overrides only what it accepts, and the abstract base rejects the rest with one message format. That's also where the ATM's security lives. There's no code path from CardInserted to a withdrawal, because CardInsertedState doesn't override withdraw.

Chain of Responsibility fits note dispensing. Each handler owns one cassette. It takes as many of its notes as it can, and hands the remainder to the next, smaller denomination. Two things make it more than a loop:

  • Each link can back off. If the rest of the chain can't finish, the handler tries one note fewer. That's what makes 600 from {500 × 1, 200 × 3} work, where greedy fails. Plain greedy is only guaranteed when every denomination divides the next larger one, as with 100, 500, 1000, 2000. India's 200 note breaks that, because 200 doesn't divide 500.
  • Cassettes can change independently. A cassette that's empty or faulty simply has a count of 0. A new denomination is a new handler in the chain, and nothing else changes.

Planning is separate from committing. plan only reads counts. reserve plans and subtracts under the dispenser lock. A failed plan therefore never removes a note.

ChoiceAlternative rejectedWhy
State with a rejecting base classif (state == ...) in every methodSix events by three or more states, and security depends on every cell being right
Chain of handlers with backtrackingGreedy loop over denominationsGreedy fails with limited notes or non-dividing denominations
Chain of handlersDynamic programming over amountsDP finds the fewest notes, but the chain is simpler and its backtracking is tiny with four cassettes
Balances and PIN attempts in the bankCounters on the ATMATMs don't share memory. Any rule that spans ATMs must live in the shared bank
Injected feeder for the hardwareCalling a device driver directlyTests can simulate a jam. See designing for testability

Implementation

Complete runnable code

Each tab is one complete file. Money is whole rupees as integers. The bank keeps balances and PIN attempts under per-account locks, and the dispenser is a chain of note handlers. The Java main runs a backtracking withdrawal and then eight threads at two ATMs draining one account. The Python demo runs the same session, and its tests cover the concurrency. The TypeScript passes tsc --strict, and we ran the same scenarios against it with node:test. It leaves out transfer, which in Node is a synchronous pair of updates that needs no lock ordering.

// file: Atm.java
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;

enum PinResult { OK, WRONG, LOCKED }

final class Account {
    final String id;
    long balance;                                       // whole rupees, guarded by lock
    final ReentrantLock lock = new ReentrantLock();
    Account(String id, long balance) { this.id = id; this.balance = balance; }
}

/** The bank owns balances and PIN attempts. Every ATM shares it. */
final class Bank {
    static final int MAX_PIN_TRIES = 3;
    private final Map<String, Account> accounts = new ConcurrentHashMap<>();
    private final Map<String, String[]> cards = new ConcurrentHashMap<>();   // card -> {account, pin}
    private final Map<String, Integer> failed = new HashMap<>();             // guarded by this

    void open(String id, long balance) { accounts.put(id, new Account(id, balance)); }
    void issueCard(String card, String accountId, String pin) { cards.put(card, new String[] {accountId, pin}); }
    boolean knows(String card) { return cards.containsKey(card); }
    String accountOf(String card) { return cards.get(card)[0]; }

    synchronized PinResult verifyPin(String card, String pin) {
        int fails = failed.getOrDefault(card, 0);
        if (fails >= MAX_PIN_TRIES) return PinResult.LOCKED;
        if (cards.get(card)[1].equals(pin)) { failed.put(card, 0); return PinResult.OK; }
        failed.put(card, ++fails);
        return fails >= MAX_PIN_TRIES ? PinResult.LOCKED : PinResult.WRONG;
    }

    long balance(String id) {
        Account a = accounts.get(id);
        a.lock.lock();
        try { return a.balance; } finally { a.lock.unlock(); }
    }

    /** Check and debit under the account's lock, so two ATMs can't both spend the same money. */
    boolean withdraw(String id, long amount) {
        Account a = accounts.get(id);
        a.lock.lock();
        try {
            if (a.balance < amount) return false;
            a.balance -= amount;
            return true;
        } finally { a.lock.unlock(); }
    }

    void deposit(String id, long amount) {
        Account a = accounts.get(id);
        a.lock.lock();
        try { a.balance += amount; } finally { a.lock.unlock(); }
    }

    boolean transfer(String from, String to, long amount) {
        Account a = accounts.get(from), b = accounts.get(to);
        Account first = a.id.compareTo(b.id) < 0 ? a : b, second = first == a ? b : a;
        first.lock.lock();                               // always lock in id order: no deadlock
        try {
            second.lock.lock();
            try {
                if (a.balance < amount) return false;
                a.balance -= amount;
                b.balance += amount;
                return true;
            } finally { second.lock.unlock(); }
        } finally { first.lock.unlock(); }
    }
}

/** Chain of Responsibility: each handler takes some notes of its denomination and passes the rest on. */
final class NoteHandler {
    final int note;
    int count;
    final NoteHandler next;
    NoteHandler(int note, int count, NoteHandler next) { this.note = note; this.count = count; this.next = next; }

    /** Most notes first, backing off when the rest of the chain can't finish. null if impossible. */
    Map<Integer, Integer> plan(int amount) {
        for (int k = Math.min(amount / note, count); k >= 0; k--) {
            int rest = amount - k * note;
            Map<Integer, Integer> tail = rest == 0 ? new TreeMap<>(Comparator.reverseOrder())
                                     : next == null ? null : next.plan(rest);
            if (tail != null) {
                if (k > 0) tail.put(note, k);
                return tail;
            }
        }
        return null;
    }
}

final class CashDispenser {
    private NoteHandler chain;                           // largest note first

    CashDispenser(Map<Integer, Integer> cassettes) {
        for (int note : new TreeSet<>(cassettes.keySet())) chain = new NoteHandler(note, cassettes.get(note), chain);
    }

    /** Plan and remove the notes in one step, so two plans can never promise the same notes. */
    synchronized Map<Integer, Integer> reserve(int amount) {
        Map<Integer, Integer> plan = amount > 0 && chain != null ? chain.plan(amount) : null;
        if (plan != null) for (NoteHandler h = chain; h != null; h = h.next) h.count -= plan.getOrDefault(h.note, 0);
        return plan;
    }

    synchronized void release(Map<Integer, Integer> notes) {
        for (NoteHandler h = chain; h != null; h = h.next) h.count += notes.getOrDefault(h.note, 0);
    }

    synchronized long total() {
        long sum = 0;
        for (NoteHandler h = chain; h != null; h = h.next) sum += (long) h.note * h.count;
        return sum;
    }
}

/** State pattern: events default to "not now". Eject works in any state that holds a card. */
abstract class AtmState {
    abstract String name();
    void insertCard(Atm atm, String card) { throw reject("insert a card"); }
    PinResult enterPin(Atm atm, String pin) { throw reject("enter a PIN"); }
    long balance(Atm atm) { throw reject("show a balance"); }
    Map<Integer, Integer> withdraw(Atm atm, int amount) { throw reject("withdraw"); }
    void eject(Atm atm) { atm.endSession(); }
    IllegalStateException reject(String what) { return new IllegalStateException("can't " + what + " while " + name()); }
}

final class IdleState extends AtmState {
    String name() { return "IDLE"; }
    void insertCard(Atm atm, String card) {
        if (!atm.bank.knows(card)) throw new IllegalStateException("card not recognised");
        atm.card = card;
        atm.state = new CardInsertedState();
    }
    void eject(Atm atm) { throw reject("eject"); }
}

final class CardInsertedState extends AtmState {
    String name() { return "CARD_INSERTED"; }
    PinResult enterPin(Atm atm, String pin) {
        PinResult r = atm.bank.verifyPin(atm.card, pin);
        if (r == PinResult.OK) { atm.account = atm.bank.accountOf(atm.card); atm.state = new AuthenticatedState(); }
        else if (r == PinResult.LOCKED) { atm.retained.add(atm.card); atm.endSession(); }
        return r;
    }
}

final class AuthenticatedState extends AtmState {
    String name() { return "AUTHENTICATED"; }
    long balance(Atm atm) { return atm.bank.balance(atm.account); }

    Map<Integer, Integer> withdraw(Atm atm, int amount) {
        Map<Integer, Integer> notes = atm.dispenser.reserve(amount);           // 1. reserve notes
        if (notes == null) throw new IllegalStateException("this ATM can't dispense " + amount);
        if (!atm.bank.withdraw(atm.account, amount)) {                         // 2. debit at the bank
            atm.dispenser.release(notes);
            throw new IllegalStateException("insufficient funds");
        }
        if (!atm.feeder.test(notes)) {                                         // 3. hand over the cash
            atm.bank.deposit(atm.account, amount);                             // compensate
            atm.dispenser.release(notes);
            throw new IllegalStateException("dispense failed, you have not been charged");
        }
        return notes;                                                          // ready for another transaction
    }
}

public class Atm {
    final Bank bank;
    final CashDispenser dispenser;
    final Predicate<Map<Integer, Integer>> feeder;      // the hardware, injected so tests can jam it
    final List<String> retained = new ArrayList<>();
    AtmState state = new IdleState();
    String card, account;

    Atm(Bank bank, CashDispenser dispenser) { this(bank, dispenser, notes -> true); }
    Atm(Bank bank, CashDispenser dispenser, Predicate<Map<Integer, Integer>> feeder) {
        this.bank = bank; this.dispenser = dispenser; this.feeder = feeder;
    }

    // One lock per ATM: the card reader, keypad and timeout timer all drive one session.
    synchronized String stateName() { return state.name(); }
    synchronized void insertCard(String c) { state.insertCard(this, c); }
    synchronized PinResult enterPin(String pin) { return state.enterPin(this, pin); }
    synchronized long balance() { return state.balance(this); }
    synchronized Map<Integer, Integer> withdraw(int amount) { return state.withdraw(this, amount); }
    synchronized void eject() { state.eject(this); }
    void endSession() { card = null; account = null; state = new IdleState(); }

    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) throws Exception {
        Bank bank = new Bank();
        bank.open("ACC1", 10_000);
        bank.issueCard("4111", "ACC1", "1234");
        Atm atm = new Atm(bank, new CashDispenser(Map.of(2000, 2, 500, 1, 200, 3, 100, 0)));
        atm.insertCard("4111");
        check(atm.enterPin("0000") == PinResult.WRONG && atm.enterPin("1234") == PinResult.OK, "PIN");
        check(atm.withdraw(600).equals(Map.of(200, 3)), "greedy would take the 500 and get stuck");
        check(atm.withdraw(4500).equals(Map.of(2000, 2, 500, 1)), "4500");
        check(atm.balance() == 4_900 && atm.dispenser.total() == 0, "balances");
        atm.eject();

        // Two ATMs, one account, many threads: the balance never goes below zero.
        bank.open("ACC2", 5_000);
        bank.issueCard("4222", "ACC2", "1111");
        List<Atm> atms = List.of(new Atm(bank, new CashDispenser(Map.of(100, 100))),
                                 new Atm(bank, new CashDispenser(Map.of(100, 100))));
        for (Atm a : atms) { a.insertCard("4222"); a.enterPin("1111"); }
        ExecutorService pool = Executors.newFixedThreadPool(8);
        List<Future<Long>> got = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            Atm a = atms.get(i % 2);
            got.add(pool.submit(() -> {
                long cash = 0;
                for (int j = 0; j < 20; j++) {
                    try { cash += a.withdraw(100).getOrDefault(100, 0) * 100L; } catch (IllegalStateException e) { }
                }
                return cash;
            }));
        }
        long total = 0;
        for (Future<Long> f : got) total += f.get();
        pool.shutdown();
        check(total == 5_000 && bank.balance("ACC2") == 0, "dispensed " + total);
        System.out.println("all checks passed");
    }
}
# file: atm.py
from __future__ import annotations

import threading
from enum import Enum
from typing import Callable

Notes = dict[int, int]                            # denomination -> count, money in whole rupees


# ---------- The bank: owns balances, PIN attempts and their locks ----------

class PinResult(Enum):
    OK = "OK"
    WRONG = "WRONG"
    LOCKED = "LOCKED"


class Account:
    def __init__(self, account_id: str, balance: int) -> None:
        self.id, self.balance = account_id, balance
        self.lock = threading.Lock()


class Bank:
    MAX_PIN_TRIES = 3

    def __init__(self) -> None:
        self._accounts: dict[str, Account] = {}
        self._cards: dict[str, tuple[str, str]] = {}    # card -> (account, pin); hash PINs in real life
        self._failed: dict[str, int] = {}               # per card, so re-inserting doesn't reset it
        self._pin_lock = threading.Lock()

    def open(self, account_id: str, balance: int) -> None:
        self._accounts[account_id] = Account(account_id, balance)

    def issue_card(self, card: str, account_id: str, pin: str) -> None:
        self._cards[card] = (account_id, pin)

    def knows(self, card: str) -> bool:
        return card in self._cards

    def verify_pin(self, card: str, pin: str) -> PinResult:
        with self._pin_lock:
            if self._failed.get(card, 0) >= self.MAX_PIN_TRIES:
                return PinResult.LOCKED
            if self._cards[card][1] == pin:
                self._failed[card] = 0
                return PinResult.OK
            self._failed[card] = self._failed.get(card, 0) + 1
            return PinResult.LOCKED if self._failed[card] >= self.MAX_PIN_TRIES else PinResult.WRONG

    def account_of(self, card: str) -> str:
        return self._cards[card][0]

    def balance(self, account_id: str) -> int:
        acct = self._accounts[account_id]
        with acct.lock:
            return acct.balance

    def withdraw(self, account_id: str, amount: int) -> bool:
        acct = self._accounts[account_id]
        with acct.lock:                                 # check and debit in one step
            if acct.balance < amount:
                return False
            acct.balance -= amount
            return True

    def deposit(self, account_id: str, amount: int) -> None:
        acct = self._accounts[account_id]
        with acct.lock:
            acct.balance += amount

    def transfer(self, src: str, dst: str, amount: int) -> bool:
        a, b = self._accounts[src], self._accounts[dst]
        first, second = (a, b) if a.id < b.id else (b, a)  # one global order: no deadlock
        with first.lock, second.lock:
            if a.balance < amount:
                return False
            a.balance -= amount
            b.balance += amount
            return True


# ---------- The cash dispenser: a chain of note handlers ----------

class NoteHandler:
    """Chain of Responsibility: take some notes of my denomination, pass the rest on."""

    def __init__(self, note: int, count: int, nxt: NoteHandler | None) -> None:
        self.note, self.count, self.next = note, count, nxt

    def plan(self, amount: int) -> Notes | None:
        # Try the most notes first, and back off if the rest of the chain can't finish.
        for k in range(min(amount // self.note, self.count), -1, -1):
            rest = amount - k * self.note
            tail = {} if rest == 0 else (self.next.plan(rest) if self.next else None)
            if tail is not None:
                return {self.note: k, **tail} if k else tail
        return None


class CashDispenser:
    def __init__(self, cassettes: Notes) -> None:
        chain: NoteHandler | None = None
        for note in sorted(cassettes):                  # build smallest-last: 2000 -> 500 -> 200 -> 100
            chain = NoteHandler(note, cassettes[note], chain)
        self._chain = chain
        self._lock = threading.Lock()                   # the session and the operator's refill

    def _handlers(self):
        h = self._chain
        while h:
            yield h
            h = h.next

    def reserve(self, amount: int) -> Notes | None:
        """Plan and remove the notes in one step, so two plans can't promise the same notes."""
        with self._lock:
            plan = self._chain.plan(amount) if self._chain and amount > 0 else None
            if plan:
                for h in self._handlers():
                    h.count -= plan.get(h.note, 0)
            return plan

    def release(self, notes: Notes) -> None:
        with self._lock:
            for h in self._handlers():
                h.count += notes.get(h.note, 0)

    def total(self) -> int:
        with self._lock:
            return sum(h.note * h.count for h in self._handlers())


# ---------- The ATM: State pattern over one card session ----------

class State:
    name = "?"

    def insert_card(self, atm: ATM, card: str) -> None:
        raise RuntimeError(f"can't insert a card while {self.name}")

    def enter_pin(self, atm: ATM, pin: str) -> PinResult:
        raise RuntimeError(f"can't enter a PIN while {self.name}")

    def balance(self, atm: ATM) -> int:
        raise RuntimeError(f"can't show a balance while {self.name}")

    def withdraw(self, atm: ATM, amount: int) -> Notes:
        raise RuntimeError(f"can't withdraw while {self.name}")

    def eject(self, atm: ATM) -> None:
        atm._end_session()                              # any state with a card can eject it


class Idle(State):
    name = "IDLE"

    def insert_card(self, atm, card):
        if not atm.bank.knows(card):
            raise RuntimeError("card not recognised")
        atm._card, atm._state = card, CardInserted()

    def eject(self, atm):
        raise RuntimeError("no card to eject")


class CardInserted(State):
    name = "CARD_INSERTED"

    def enter_pin(self, atm, pin):
        result = atm.bank.verify_pin(atm._card, pin)
        if result is PinResult.OK:
            atm._account, atm._state = atm.bank.account_of(atm._card), Authenticated()
        elif result is PinResult.LOCKED:
            atm.retained.append(atm._card)              # keep the card, end the session
            atm._end_session()
        return result


class Authenticated(State):
    name = "AUTHENTICATED"

    def balance(self, atm):
        return atm.bank.balance(atm._account)

    def withdraw(self, atm, amount):
        notes = atm.dispenser.reserve(amount)           # 1. reserve notes
        if notes is None:
            raise RuntimeError(f"this ATM can't dispense {amount}")
        if not atm.bank.withdraw(atm._account, amount):  # 2. debit atomically at the bank
            atm.dispenser.release(notes)
            raise RuntimeError("insufficient funds")
        if not atm.feeder(notes):                       # 3. physically dispense
            atm.bank.deposit(atm._account, amount)      # compensate: the customer got nothing
            atm.dispenser.release(notes)                # the jam happened before notes left
            raise RuntimeError("dispense failed, you have not been charged")
        return notes                                    # stay AUTHENTICATED for another transaction


class ATM:
    def __init__(self, bank: Bank, dispenser: CashDispenser,
                 feeder: Callable[[Notes], bool] = lambda notes: True) -> None:
        self.bank, self.dispenser, self.feeder = bank, dispenser, feeder
        self.retained: list[str] = []
        self._state: State = Idle()
        self._card: str | None = None
        self._account: str | None = None
        self._lock = threading.Lock()                   # card reader, keypad and timer share one session

    @property
    def state(self) -> str:
        return self._state.name

    def insert_card(self, card: str) -> None:
        with self._lock:
            self._state.insert_card(self, card)

    def enter_pin(self, pin: str) -> PinResult:
        with self._lock:
            return self._state.enter_pin(self, pin)

    def balance(self) -> int:
        with self._lock:
            return self._state.balance(self)

    def withdraw(self, amount: int) -> Notes:
        with self._lock:
            return self._state.withdraw(self, amount)

    def eject(self) -> None:
        with self._lock:
            self._state.eject(self)

    def _end_session(self) -> None:
        self._card = self._account = None
        self._state = Idle()


if __name__ == "__main__":
    bank = Bank()
    bank.open("ACC1", 10_000)
    bank.issue_card("4111", "ACC1", "1234")
    atm = ATM(bank, CashDispenser({2000: 2, 500: 1, 200: 3, 100: 0}))

    atm.insert_card("4111")
    assert atm.enter_pin("0000") is PinResult.WRONG
    assert atm.enter_pin("1234") is PinResult.OK
    assert atm.withdraw(600) == {200: 3}                # greedy would take the 500 and fail
    assert atm.withdraw(4500) == {2000: 2, 500: 1}
    assert atm.balance() == 4_900 and atm.dispenser.total() == 0
    atm.eject()
    assert atm.state == "IDLE"
    print("all checks passed")
// file: atm.ts
export type Notes = Map<number, number>;                 // denomination -> count, whole rupees
export type PinResult = "OK" | "WRONG" | "LOCKED";

interface Account { readonly id: string; balance: number }

/** The bank owns balances and PIN attempts. Every ATM shares it. */
export class Bank {
  static readonly MAX_PIN_TRIES = 3;
  private readonly accounts = new Map<string, Account>();
  private readonly cards = new Map<string, { account: string; pin: string }>();
  private readonly failed = new Map<string, number>();

  open(id: string, balance: number): void { this.accounts.set(id, { id, balance }); }
  issueCard(card: string, account: string, pin: string): void { this.cards.set(card, { account, pin }); }
  knows(card: string): boolean { return this.cards.has(card); }
  accountOf(card: string): string { return this.must(this.cards.get(card)).account; }

  verifyPin(card: string, pin: string): PinResult {
    const fails = this.failed.get(card) ?? 0;
    if (fails >= Bank.MAX_PIN_TRIES) return "LOCKED";
    if (this.must(this.cards.get(card)).pin === pin) { this.failed.set(card, 0); return "OK"; }
    this.failed.set(card, fails + 1);
    return fails + 1 >= Bank.MAX_PIN_TRIES ? "LOCKED" : "WRONG";
  }

  balance(id: string): number { return this.account(id).balance; }

  // Synchronous check-and-debit: nothing else runs between the two lines. In a real
  // service this is one conditional UPDATE in the database, for the same reason.
  withdraw(id: string, amount: number): boolean {
    const a = this.account(id);
    if (a.balance < amount) return false;
    a.balance -= amount;
    return true;
  }

  deposit(id: string, amount: number): void { this.account(id).balance += amount; }

  private account(id: string): Account { return this.must(this.accounts.get(id)); }
  private must<T>(x: T | undefined): T { if (x === undefined) throw new Error("unknown card or account"); return x; }
}

/** Chain of Responsibility: take some notes of my denomination, pass the rest on. */
export class NoteHandler {
  constructor(readonly note: number, public count: number, readonly next: NoteHandler | null) {}

  plan(amount: number): Notes | null {
    for (let k = Math.min(Math.floor(amount / this.note), this.count); k >= 0; k--) {
      const rest = amount - k * this.note;
      const tail = rest === 0 ? new Map<number, number>() : this.next ? this.next.plan(rest) : null;
      if (tail) {
        if (k > 0) tail.set(this.note, k);
        return tail;
      }
    }
    return null;
  }
}

export class CashDispenser {
  private chain: NoteHandler | null = null;

  constructor(cassettes: Record<number, number>) {
    for (const note of Object.keys(cassettes).map(Number).sort((a, b) => a - b)) {
      this.chain = new NoteHandler(note, cassettes[note], this.chain);   // largest ends up first
    }
  }

  private *handlers(): Generator<NoteHandler> {
    for (let h = this.chain; h; h = h.next) yield h;
  }

  /** Plan and remove in one synchronous step, so two plans can't promise the same notes. */
  reserve(amount: number): Notes | null {
    const plan = amount > 0 && this.chain ? this.chain.plan(amount) : null;
    if (plan) for (const h of this.handlers()) h.count -= plan.get(h.note) ?? 0;
    return plan;
  }

  release(notes: Notes): void { for (const h of this.handlers()) h.count += notes.get(h.note) ?? 0; }
  total(): number { let t = 0; for (const h of this.handlers()) t += h.note * h.count; return t; }
}

/** State pattern: events default to "not now". Eject works in any state holding a card. */
export abstract class AtmState {
  abstract readonly name: string;
  insertCard(_atm: Atm, _card: string): void { throw this.reject("insert a card"); }
  enterPin(_atm: Atm, _pin: string): PinResult { throw this.reject("enter a PIN"); }
  balance(_atm: Atm): number { throw this.reject("show a balance"); }
  withdraw(_atm: Atm, _amount: number): Notes { throw this.reject("withdraw"); }
  eject(atm: Atm): void { atm.endSession(); }
  protected reject(what: string): Error { return new Error(`can't ${what} while ${this.name}`); }
}

export class Idle extends AtmState {
  readonly name = "IDLE";
  override insertCard(atm: Atm, card: string): void {
    if (!atm.bank.knows(card)) throw new Error("card not recognised");
    atm.session = { card, account: null };
    atm.state = new CardInserted();
  }
  override eject(): void { throw this.reject("eject"); }
}

export class CardInserted extends AtmState {
  readonly name = "CARD_INSERTED";
  override enterPin(atm: Atm, pin: string): PinResult {
    const card = atm.currentCard();
    const result = atm.bank.verifyPin(card, pin);
    if (result === "OK") {
      atm.session = { card, account: atm.bank.accountOf(card) };
      atm.state = new Authenticated();
    } else if (result === "LOCKED") {
      atm.retained.push(card);
      atm.endSession();
    }
    return result;
  }
}

export class Authenticated extends AtmState {
  readonly name = "AUTHENTICATED";
  override balance(atm: Atm): number { return atm.bank.balance(atm.currentAccount()); }

  override withdraw(atm: Atm, amount: number): Notes {
    const account = atm.currentAccount();
    const notes = atm.dispenser.reserve(amount);                    // 1. reserve notes
    if (!notes) throw new Error(`this ATM can't dispense ${amount}`);
    if (!atm.bank.withdraw(account, amount)) {                       // 2. debit at the bank
      atm.dispenser.release(notes);
      throw new Error("insufficient funds");
    }
    if (!atm.feeder(notes)) {                                        // 3. hand over the cash
      atm.bank.deposit(account, amount);                             // compensate
      atm.dispenser.release(notes);
      throw new Error("dispense failed, you have not been charged");
    }
    return notes;
  }
}

export class Atm {
  state: AtmState = new Idle();
  session: { card: string; account: string | null } | null = null;
  readonly retained: string[] = [];

  constructor(readonly bank: Bank, readonly dispenser: CashDispenser,
              readonly feeder: (notes: Notes) => boolean = () => true) {}

  insertCard(card: string): void { this.state.insertCard(this, card); }
  enterPin(pin: string): PinResult { return this.state.enterPin(this, pin); }
  balance(): number { return this.state.balance(this); }
  withdraw(amount: number): Notes { return this.state.withdraw(this, amount); }
  eject(): void { this.state.eject(this); }

  endSession(): void { this.session = null; this.state = new Idle(); }
  currentCard(): string { if (!this.session) throw new Error("no card"); return this.session.card; }
  currentAccount(): string {
    if (!this.session?.account) throw new Error("not signed in");
    return this.session.account;
  }
}

Run with javac -d out Atm.java && java -ea -cp out Atm and python atm.py. Compared with the walkthrough below:

  • Integers, not floats. See the correction on the walkthrough's withdrawal code.
  • PIN attempts are counted by the bank, per card, so re-inserting the card doesn't reset them.
  • Withdrawal reserves notes, debits, then dispenses, with a compensation if the hardware fails.
  • The dispenser backtracks. It's a chain of handlers, not a greedy loop.
  • The session survives a transaction, so the customer can withdraw again or eject.

Component walkthrough

The original code follows. It runs: the TypeScript passes tsc --strict and the usage example prints the result shown, and the Python state machine works end to end. The corrections note what we found when we tested it.

Enums and Types

TypeScript:

enum TransactionType {
  BALANCE_INQUIRY = "BALANCE_INQUIRY",
  WITHDRAWAL = "WITHDRAWAL",
  DEPOSIT = "DEPOSIT",
  TRANSFER = "TRANSFER",
}

enum Denomination {
  HUNDRED = 100,
  FIVE_HUNDRED = 500,
  THOUSAND = 1000,
  TWO_THOUSAND = 2000,
}

interface Card {
  cardNumber: string;
  bankCode: string;
  expiryDate: Date;
}

interface TransactionResult {
  success: boolean;
  message: string;
  balance?: number;
  dispensedCash?: Map<Denomination, number>;
}

Python:

from enum import Enum
from dataclasses import dataclass, field
from datetime import datetime
from abc import ABC, abstractmethod

class TransactionType(Enum):
    BALANCE_INQUIRY = "BALANCE_INQUIRY"
    WITHDRAWAL = "WITHDRAWAL"
    DEPOSIT = "DEPOSIT"
    TRANSFER = "TRANSFER"

class Denomination(Enum):
    HUNDRED = 100
    FIVE_HUNDRED = 500
    THOUSAND = 1000
    TWO_THOUSAND = 2000

@dataclass
class Card:
    card_number: str
    bank_code: str
    expiry_date: datetime

@dataclass
class TransactionResult:
    success: bool
    message: str
    balance: float | None = None
    dispensed_cash: dict[Denomination, int] | None = None

Bank Service Interface

TypeScript:

interface BankService {
  validateCard(cardNumber: string): boolean;
  validatePin(cardNumber: string, pin: string): boolean;
  getBalance(accountId: string): number;
  withdraw(accountId: string, amount: number): boolean;
  deposit(accountId: string, amount: number): boolean;
  transfer(fromAccount: string, toAccount: string, amount: number): boolean;
  getAccountId(cardNumber: string): string;
}

class MockBankService implements BankService {
  private accounts: Map<string, { pin: string; balance: number; accountId: string }>;

  constructor() {
    this.accounts = new Map([
      ["4111111111111111", { pin: "1234", balance: 50000, accountId: "ACC001" }],
      ["4222222222222222", { pin: "5678", balance: 30000, accountId: "ACC002" }],
    ]);
  }

  validateCard(cardNumber: string): boolean {
    return this.accounts.has(cardNumber);
  }

  validatePin(cardNumber: string, pin: string): boolean {
    const account = this.accounts.get(cardNumber);
    return account?.pin === pin;
  }

  getBalance(accountId: string): number {
    for (const [, acc] of this.accounts) {
      if (acc.accountId === accountId) return acc.balance;
    }
    return 0;
  }

  withdraw(accountId: string, amount: number): boolean {
    for (const [, acc] of this.accounts) {
      if (acc.accountId === accountId && acc.balance >= amount) {
        acc.balance -= amount;
        return true;
      }
    }
    return false;
  }

  deposit(accountId: string, amount: number): boolean {
    for (const [, acc] of this.accounts) {
      if (acc.accountId === accountId) {
        acc.balance += amount;
        return true;
      }
    }
    return false;
  }

  transfer(fromAccount: string, toAccount: string, amount: number): boolean {
    if (this.withdraw(fromAccount, amount)) {
      if (this.deposit(toAccount, amount)) return true;
      this.deposit(fromAccount, amount); // rollback
    }
    return false;
  }

  getAccountId(cardNumber: string): string {
    return this.accounts.get(cardNumber)?.accountId ?? "";
  }
}

Python:

class BankService(ABC):
    @abstractmethod
    def validate_card(self, card_number: str) -> bool: ...

    @abstractmethod
    def validate_pin(self, card_number: str, pin: str) -> bool: ...

    @abstractmethod
    def get_balance(self, account_id: str) -> float: ...

    @abstractmethod
    def withdraw(self, account_id: str, amount: float) -> bool: ...

    @abstractmethod
    def deposit(self, account_id: str, amount: float) -> bool: ...

    @abstractmethod
    def transfer(self, from_acc: str, to_acc: str, amount: float) -> bool: ...

    @abstractmethod
    def get_account_id(self, card_number: str) -> str: ...

class MockBankService(BankService):
    def __init__(self):
        self.accounts = {
            "4111111111111111": {"pin": "1234", "balance": 50000, "account_id": "ACC001"},
            "4222222222222222": {"pin": "5678", "balance": 30000, "account_id": "ACC002"},
        }

    def validate_card(self, card_number: str) -> bool:
        return card_number in self.accounts

    def validate_pin(self, card_number: str, pin: str) -> bool:
        acc = self.accounts.get(card_number)
        return acc is not None and acc["pin"] == pin

    def get_balance(self, account_id: str) -> float:
        for acc in self.accounts.values():
            if acc["account_id"] == account_id:
                return acc["balance"]
        return 0

    def withdraw(self, account_id: str, amount: float) -> bool:
        for acc in self.accounts.values():
            if acc["account_id"] == account_id and acc["balance"] >= amount:
                acc["balance"] -= amount
                return True
        return False

    def deposit(self, account_id: str, amount: float) -> bool:
        for acc in self.accounts.values():
            if acc["account_id"] == account_id:
                acc["balance"] += amount
                return True
        return False

    def transfer(self, from_acc: str, to_acc: str, amount: float) -> bool:
        if self.withdraw(from_acc, amount):
            if self.deposit(to_acc, amount):
                return True
            self.deposit(from_acc, amount)  # rollback
        return False

    def get_account_id(self, card_number: str) -> str:
        acc = self.accounts.get(card_number)
        return acc["account_id"] if acc else ""

Cash Dispenser

Correction (2026-11-10)

The greedy loop below is only guaranteed to work because 100, 500, 1000 and 2000 each divide the next larger one. Add a 200 note, as India did in 2017, and it fails: with one 500 and three 200s loaded, canDispense(600) takes the 500, needs 100, and says no, although three 200s would do. Separately, calling canDispense and then dispense is check-then-act on the cassette counts. The complete code plans and removes in one locked step.

TypeScript:

class CashDispenser {
  private cash: Map<Denomination, number> = new Map();

  constructor() {
    // Initialize with default cash
    this.cash.set(Denomination.TWO_THOUSAND, 100);
    this.cash.set(Denomination.THOUSAND, 200);
    this.cash.set(Denomination.FIVE_HUNDRED, 300);
    this.cash.set(Denomination.HUNDRED, 500);
  }

  canDispense(amount: number): boolean {
    let remaining = amount;
    const denominations = [
      Denomination.TWO_THOUSAND,
      Denomination.THOUSAND,
      Denomination.FIVE_HUNDRED,
      Denomination.HUNDRED,
    ];

    const tempCash = new Map(this.cash);

    for (const denom of denominations) {
      const available = tempCash.get(denom) ?? 0;
      const needed = Math.floor(remaining / denom);
      const used = Math.min(needed, available);
      remaining -= used * denom;
    }

    return remaining === 0;
  }

  dispense(amount: number): Map<Denomination, number> {
    const result = new Map<Denomination, number>();
    let remaining = amount;

    const denominations = [
      Denomination.TWO_THOUSAND,
      Denomination.THOUSAND,
      Denomination.FIVE_HUNDRED,
      Denomination.HUNDRED,
    ];

    for (const denom of denominations) {
      const available = this.cash.get(denom) ?? 0;
      const needed = Math.floor(remaining / denom);
      const used = Math.min(needed, available);

      if (used > 0) {
        result.set(denom, used);
        this.cash.set(denom, available - used);
        remaining -= used * denom;
      }
    }

    return result;
  }

  totalCash(): number {
    let total = 0;
    for (const [denom, count] of this.cash) {
      total += denom * count;
    }
    return total;
  }
}

Python:

class CashDispenser:
    def __init__(self):
        self.cash: dict[Denomination, int] = {
            Denomination.TWO_THOUSAND: 100,
            Denomination.THOUSAND: 200,
            Denomination.FIVE_HUNDRED: 300,
            Denomination.HUNDRED: 500,
        }

    def can_dispense(self, amount: int) -> bool:
        remaining = amount
        for denom in sorted(self.cash.keys(), key=lambda d: d.value, reverse=True):
            available = self.cash[denom]
            needed = remaining // denom.value
            used = min(needed, available)
            remaining -= used * denom.value
        return remaining == 0

    def dispense(self, amount: int) -> dict[Denomination, int]:
        result: dict[Denomination, int] = {}
        remaining = amount

        for denom in sorted(self.cash.keys(), key=lambda d: d.value, reverse=True):
            available = self.cash[denom]
            needed = remaining // denom.value
            used = min(needed, available)

            if used > 0:
                result[denom] = used
                self.cash[denom] -= used
                remaining -= used * denom.value

        return result

    def total_cash(self) -> int:
        return sum(d.value * c for d, c in self.cash.items())

State Pattern Implementation

Correction (2026-11-10)

Two bugs below, both confirmed by running the Python. First, IdleState.insertCard sets pinAttempts = 0, so the three-attempt limit is per insertion. We entered ten wrong PINs in five insertions and the card still worked. Attempts must be counted by the bank, per card. Second, the Python withdrawal checks and dispenses int(amount) but debits amount. A request for 500.5 dispensed one 500 note and debited 500.5. Use integers for money everywhere.

TypeScript:

interface ATMState {
  insertCard(atm: ATM, card: Card): void;
  enterPin(atm: ATM, pin: string): void;
  selectTransaction(atm: ATM, type: TransactionType): void;
  confirmTransaction(atm: ATM, amount: number, targetAccount?: string): TransactionResult;
  cancel(atm: ATM): void;
}

class IdleState implements ATMState {
  insertCard(atm: ATM, card: Card): void {
    if (atm.bankService.validateCard(card.cardNumber)) {
      atm.currentCard = card;
      atm.pinAttempts = 0;
      atm.setState(new CardInsertedState());
      console.log("Card accepted. Please enter your PIN.");
    } else {
      console.log("Invalid card. Please try another card.");
    }
  }

  enterPin(): void { console.log("Please insert a card first."); }
  selectTransaction(): void { console.log("Please insert a card first."); }
  confirmTransaction(): TransactionResult {
    return { success: false, message: "Please insert a card first." };
  }
  cancel(): void { console.log("No active session."); }
}

class CardInsertedState implements ATMState {
  insertCard(): void { console.log("Card already inserted."); }

  enterPin(atm: ATM, pin: string): void {
    if (atm.bankService.validatePin(atm.currentCard!.cardNumber, pin)) {
      atm.accountId = atm.bankService.getAccountId(atm.currentCard!.cardNumber);
      atm.setState(new PinEnteredState());
      console.log("PIN verified. Select a transaction.");
    } else {
      atm.pinAttempts++;
      if (atm.pinAttempts >= 3) {
        console.log("Too many failed attempts. Card retained.");
        atm.resetSession();
        atm.setState(new IdleState());
      } else {
        console.log(`Wrong PIN. ${3 - atm.pinAttempts} attempts remaining.`);
      }
    }
  }

  selectTransaction(): void { console.log("Please enter your PIN first."); }
  confirmTransaction(): TransactionResult {
    return { success: false, message: "Please enter your PIN first." };
  }
  cancel(atm: ATM): void {
    console.log("Session cancelled. Ejecting card.");
    atm.resetSession();
    atm.setState(new IdleState());
  }
}

class PinEnteredState implements ATMState {
  insertCard(): void { console.log("Card already inserted."); }
  enterPin(): void { console.log("PIN already verified."); }

  selectTransaction(atm: ATM, type: TransactionType): void {
    atm.currentTransaction = type;
    atm.setState(new TransactionSelectedState());
    console.log(`Transaction selected: ${type}`);
  }

  confirmTransaction(): TransactionResult {
    return { success: false, message: "Please select a transaction type." };
  }

  cancel(atm: ATM): void {
    console.log("Session cancelled. Ejecting card.");
    atm.resetSession();
    atm.setState(new IdleState());
  }
}

class TransactionSelectedState implements ATMState {
  insertCard(): void { console.log("Transaction in progress."); }
  enterPin(): void { console.log("Transaction in progress."); }
  selectTransaction(atm: ATM, type: TransactionType): void {
    atm.currentTransaction = type;
    console.log(`Transaction changed to: ${type}`);
  }

  confirmTransaction(atm: ATM, amount: number, targetAccount?: string): TransactionResult {
    const accountId = atm.accountId!;

    switch (atm.currentTransaction) {
      case TransactionType.BALANCE_INQUIRY: {
        const balance = atm.bankService.getBalance(accountId);
        atm.resetSession();
        atm.setState(new IdleState());
        return { success: true, message: `Balance: ${balance}`, balance };
      }

      case TransactionType.WITHDRAWAL: {
        if (!atm.cashDispenser.canDispense(amount)) {
          return { success: false, message: "ATM cannot dispense this amount." };
        }
        if (atm.bankService.withdraw(accountId, amount)) {
          const bills = atm.cashDispenser.dispense(amount);
          const balance = atm.bankService.getBalance(accountId);
          atm.resetSession();
          atm.setState(new IdleState());
          return { success: true, message: "Cash dispensed.", balance, dispensedCash: bills };
        }
        return { success: false, message: "Insufficient funds." };
      }

      case TransactionType.DEPOSIT: {
        if (atm.bankService.deposit(accountId, amount)) {
          const balance = atm.bankService.getBalance(accountId);
          atm.resetSession();
          atm.setState(new IdleState());
          return { success: true, message: `Deposited ${amount}.`, balance };
        }
        return { success: false, message: "Deposit failed." };
      }

      case TransactionType.TRANSFER: {
        if (!targetAccount) {
          return { success: false, message: "Target account required." };
        }
        if (atm.bankService.transfer(accountId, targetAccount, amount)) {
          const balance = atm.bankService.getBalance(accountId);
          atm.resetSession();
          atm.setState(new IdleState());
          return { success: true, message: `Transferred ${amount}.`, balance };
        }
        return { success: false, message: "Transfer failed." };
      }

      default:
        return { success: false, message: "Unknown transaction type." };
    }
  }

  cancel(atm: ATM): void {
    console.log("Transaction cancelled. Ejecting card.");
    atm.resetSession();
    atm.setState(new IdleState());
  }
}

Python:

class ATMState(ABC):
    @abstractmethod
    def insert_card(self, atm: 'ATM', card: Card) -> None: ...

    @abstractmethod
    def enter_pin(self, atm: 'ATM', pin: str) -> None: ...

    @abstractmethod
    def select_transaction(self, atm: 'ATM', tx_type: TransactionType) -> None: ...

    @abstractmethod
    def confirm_transaction(self, atm: 'ATM', amount: float,
                            target_account: str | None = None) -> TransactionResult: ...

    @abstractmethod
    def cancel(self, atm: 'ATM') -> None: ...

class IdleState(ATMState):
    def insert_card(self, atm: 'ATM', card: Card) -> None:
        if atm.bank_service.validate_card(card.card_number):
            atm.current_card = card
            atm.pin_attempts = 0
            atm.set_state(CardInsertedState())
        else:
            print("Invalid card.")

    def enter_pin(self, atm: 'ATM', pin: str) -> None:
        print("Insert a card first.")

    def select_transaction(self, atm: 'ATM', tx_type: TransactionType) -> None:
        print("Insert a card first.")

    def confirm_transaction(self, atm: 'ATM', amount: float,
                            target_account: str | None = None) -> TransactionResult:
        return TransactionResult(success=False, message="Insert a card first.")

    def cancel(self, atm: 'ATM') -> None:
        print("No active session.")

class CardInsertedState(ATMState):
    def insert_card(self, atm: 'ATM', card: Card) -> None:
        print("Card already inserted.")

    def enter_pin(self, atm: 'ATM', pin: str) -> None:
        if atm.bank_service.validate_pin(atm.current_card.card_number, pin):
            atm.account_id = atm.bank_service.get_account_id(atm.current_card.card_number)
            atm.set_state(PinEnteredState())
        else:
            atm.pin_attempts += 1
            if atm.pin_attempts >= 3:
                print("Card retained.")
                atm.reset_session()
                atm.set_state(IdleState())
            else:
                print(f"Wrong PIN. {3 - atm.pin_attempts} attempts left.")

    def select_transaction(self, atm: 'ATM', tx_type: TransactionType) -> None:
        print("Enter PIN first.")

    def confirm_transaction(self, atm: 'ATM', amount: float,
                            target_account: str | None = None) -> TransactionResult:
        return TransactionResult(success=False, message="Enter PIN first.")

    def cancel(self, atm: 'ATM') -> None:
        atm.reset_session()
        atm.set_state(IdleState())

class PinEnteredState(ATMState):
    def insert_card(self, atm: 'ATM', card: Card) -> None:
        print("Card already inserted.")

    def enter_pin(self, atm: 'ATM', pin: str) -> None:
        print("PIN already verified.")

    def select_transaction(self, atm: 'ATM', tx_type: TransactionType) -> None:
        atm.current_transaction = tx_type
        atm.set_state(TransactionSelectedState())

    def confirm_transaction(self, atm: 'ATM', amount: float,
                            target_account: str | None = None) -> TransactionResult:
        return TransactionResult(success=False, message="Select a transaction first.")

    def cancel(self, atm: 'ATM') -> None:
        atm.reset_session()
        atm.set_state(IdleState())

class TransactionSelectedState(ATMState):
    def insert_card(self, atm: 'ATM', card: Card) -> None:
        print("Transaction in progress.")

    def enter_pin(self, atm: 'ATM', pin: str) -> None:
        print("Transaction in progress.")

    def select_transaction(self, atm: 'ATM', tx_type: TransactionType) -> None:
        atm.current_transaction = tx_type

    def confirm_transaction(self, atm: 'ATM', amount: float,
                            target_account: str | None = None) -> TransactionResult:
        account_id = atm.account_id

        if atm.current_transaction == TransactionType.BALANCE_INQUIRY:
            balance = atm.bank_service.get_balance(account_id)
            atm.reset_session()
            atm.set_state(IdleState())
            return TransactionResult(True, f"Balance: {balance}", balance)

        if atm.current_transaction == TransactionType.WITHDRAWAL:
            if not atm.cash_dispenser.can_dispense(int(amount)):
                return TransactionResult(False, "Cannot dispense this amount.")
            if atm.bank_service.withdraw(account_id, amount):
                bills = atm.cash_dispenser.dispense(int(amount))
                balance = atm.bank_service.get_balance(account_id)
                atm.reset_session()
                atm.set_state(IdleState())
                return TransactionResult(True, "Cash dispensed.", balance, bills)
            return TransactionResult(False, "Insufficient funds.")

        if atm.current_transaction == TransactionType.DEPOSIT:
            if atm.bank_service.deposit(account_id, amount):
                balance = atm.bank_service.get_balance(account_id)
                atm.reset_session()
                atm.set_state(IdleState())
                return TransactionResult(True, f"Deposited {amount}.", balance)
            return TransactionResult(False, "Deposit failed.")

        if atm.current_transaction == TransactionType.TRANSFER:
            if not target_account:
                return TransactionResult(False, "Target account required.")
            if atm.bank_service.transfer(account_id, target_account, amount):
                balance = atm.bank_service.get_balance(account_id)
                atm.reset_session()
                atm.set_state(IdleState())
                return TransactionResult(True, f"Transferred {amount}.", balance)
            return TransactionResult(False, "Transfer failed.")

        return TransactionResult(False, "Unknown transaction.")

    def cancel(self, atm: 'ATM') -> None:
        atm.reset_session()
        atm.set_state(IdleState())

ATM Controller

TypeScript:

class ATM {
  private state: ATMState = new IdleState();
  currentCard: Card | null = null;
  accountId: string | null = null;
  currentTransaction: TransactionType | null = null;
  pinAttempts = 0;
  cashDispenser = new CashDispenser();
  bankService: BankService;

  constructor(bankService: BankService) {
    this.bankService = bankService;
  }

  setState(state: ATMState): void {
    this.state = state;
  }

  resetSession(): void {
    this.currentCard = null;
    this.accountId = null;
    this.currentTransaction = null;
    this.pinAttempts = 0;
  }

  insertCard(card: Card): void {
    this.state.insertCard(this, card);
  }

  enterPin(pin: string): void {
    this.state.enterPin(this, pin);
  }

  selectTransaction(type: TransactionType): void {
    this.state.selectTransaction(this, type);
  }

  confirmTransaction(amount = 0, targetAccount?: string): TransactionResult {
    return this.state.confirmTransaction(this, amount, targetAccount);
  }

  cancel(): void {
    this.state.cancel(this);
  }
}

Python:

class ATM:
    def __init__(self, bank_service: BankService):
        self._state: ATMState = IdleState()
        self.current_card: Card | None = None
        self.account_id: str | None = None
        self.current_transaction: TransactionType | None = None
        self.pin_attempts: int = 0
        self.cash_dispenser = CashDispenser()
        self.bank_service = bank_service

    def set_state(self, state: ATMState) -> None:
        self._state = state

    def reset_session(self) -> None:
        self.current_card = None
        self.account_id = None
        self.current_transaction = None
        self.pin_attempts = 0

    def insert_card(self, card: Card) -> None:
        self._state.insert_card(self, card)

    def enter_pin(self, pin: str) -> None:
        self._state.enter_pin(self, pin)

    def select_transaction(self, tx_type: TransactionType) -> None:
        self._state.select_transaction(self, tx_type)

    def confirm_transaction(self, amount: float = 0,
                            target_account: str | None = None) -> TransactionResult:
        return self._state.confirm_transaction(self, amount, target_account)

    def cancel(self) -> None:
        self._state.cancel(self)

Usage Example

TypeScript:

const bank = new MockBankService();
const atm = new ATM(bank);

const card: Card = {
  cardNumber: "4111111111111111",
  bankCode: "MOCK",
  expiryDate: new Date("2028-12-31"),
};

atm.insertCard(card);             // "Card accepted..."
atm.enterPin("1234");             // "PIN verified..."
atm.selectTransaction(TransactionType.WITHDRAWAL);
const result = atm.confirmTransaction(5000);
console.log(result);
// { success: true, message: "Cash dispensed.", balance: 45000, dispensedCash: ... }

Complexity Analysis

OperationTimeSpace
Card validation
PIN check
Balance inquiry
Cash dispensing where = number of denominations
Transfer

Correction (2026-11-10)

The rows for balance, withdraw, deposit and transfer don't match the mock bank above, which loops over every account to find one by id. That's for accounts. Keying the map by account id, as the complete code does, makes them . Card and PIN validation are as stated. The dispensing row is right for greedy. The backtracking chain is in the common case and bounded by the product of note counts in the worst case, which is tiny for four cassettes.

Common Interview Mistakes

  1. No state validation — allowing PIN entry when no card is inserted
  2. No PIN attempt limit — enabling brute-force attacks
  3. Ignoring denominations — dispensing exact amounts without considering available bills
  4. No rollback — failing midway through a transfer without reverting the withdrawal

Concurrency

"Thread-safe transaction processing" hides two separate stories, and interviewers want both.

Cash dispensing, inside one ATM

What's shared. The cassette counts, used by the session, the operator's refill and, in a recycling ATM, deposits.

The race. The walkthrough checks canDispense(amount) and later calls dispense(amount). If the counts change in between, the plan that runs isn't the plan that was checked, and it can dispense less than it debited.

The fix. reserve plans and subtracts in one critical section. From then on the notes belong to this withdrawal: either they're handed over, or release puts them back. The session itself is serialised by one lock per ATM, because the card reader, keypad and timeout timer all drive it.

The account balance, across ATMs

What's shared. The balance, and anything that limits spending. One account can be used at two ATMs at once (a joint account, a cloned card) and by online banking.

The race. Two ATMs read a balance of 5,000, both approve 4,000, and both debit. The balance is now −3,000.

The fix. The ATM never decides. It asks the bank to "debit 4,000 if the balance allows", and the bank checks and debits under the account's lock in one step. In a real bank that's one conditional update, UPDATE account SET balance = balance - 4000 WHERE id = ? AND balance >= 4000. The Java demo and the Python tests run threads at two ATMs against one account and check that the cash dispensed equals the starting balance.

sequenceDiagram
    participant A1 as ATM 1
    participant B as Bank, account lock
    participant A2 as ATM 2
    A1->>B: withdraw 4000
    A2->>B: withdraw 4000
    B->>B: ATM 1 holds the lock, balance 5000, debit to 1000
    B-->>A1: OK
    B->>B: ATM 2 gets the lock, balance 1000, refuse
    B-->>A2: insufficient funds

Transfers and deadlock. If one thread transfers A to B while another transfers B to A, and each locks its source first, they deadlock. The bank always locks the two accounts in id order. The Python test runs opposite transfers in a loop and checks that both finish and the total is conserved.

Ordering. Even with perfect locks, step order decides what a failure costs: reserve notes (cheap to undo), debit (undo with a reversal), then dispense (irreversible). See thread-safe class design, deadlocks and race conditions.

Extensibility: the interviewer adds X

The original list comes first, then two extensions as real diffs against the complete code. We applied each diff and ran the tests.

Extensions to Discuss

  • Multi-language support (Strategy pattern for UI text)
  • Transaction logging and audit trail (Observer pattern)
  • ATM network management (multiple ATMs, central monitoring)
  • Denomination optimization (minimize number of bills dispensed)
  • Daily withdrawal limits per card/account

Extension A: cash deposits

"Deposit is a new event, so the base state gets a default rejection and only Authenticated overrides it. The notes go back into the cassettes, which is what a recycling ATM does, and the bank credits the account. Nothing else changes."

--- a/atm.py
+++ b/atm.py
@@ -128,6 +128,9 @@
             for h in self._handlers():
                 h.count += notes.get(h.note, 0)
 
+    def denominations(self) -> set[int]:
+        return {h.note for h in self._handlers()}
+
     def total(self) -> int:
         with self._lock:
             return sum(h.note * h.count for h in self._handlers())
@@ -150,6 +153,9 @@
     def withdraw(self, atm: ATM, amount: int) -> Notes:
         raise RuntimeError(f"can't withdraw while {self.name}")
 
+    def deposit(self, atm: ATM, notes: Notes) -> int:
+        raise RuntimeError(f"can't deposit while {self.name}")
+
     def eject(self, atm: ATM) -> None:
         atm._end_session()                              # any state with a card can eject it
 
@@ -198,6 +204,14 @@
             raise RuntimeError("dispense failed, you have not been charged")
         return notes                                    # stay AUTHENTICATED for another transaction
 
+    def deposit(self, atm, notes):
+        unknown = set(notes) - atm.dispenser.denominations()
+        if unknown or any(n <= 0 for n in notes.values()):
+            raise RuntimeError(f"notes rejected: {sorted(unknown)}")   # the acceptor hands them back
+        atm.dispenser.release(notes)                    # a recycling ATM refills its cassettes
+        atm.bank.deposit(atm._account, sum(d * n for d, n in notes.items()))
+        return atm.bank.balance(atm._account)
+
 
 class ATM:
     def __init__(self, bank: Bank, dispenser: CashDispenser,
@@ -229,6 +243,10 @@
         with self._lock:
             return self._state.withdraw(self, amount)
 
+    def deposit(self, notes: Notes) -> int:
+        with self._lock:
+            return self._state.deposit(self, notes)
+
     def eject(self) -> None:
         with self._lock:
             self._state.eject(self)

A real acceptor shows the counted total for the customer to confirm, which is another state if the interviewer wants it. The notes are in the machine before the credit, so unlike a withdrawal there's nothing to compensate.

Extension B: a daily withdrawal limit

"The limit spans every ATM, so it can't live in the ATM. It goes in the bank, checked under the same account lock as the balance. Otherwise two ATMs could each approve 800 against a 1,000 limit."

--- a/Atm.java
+++ b/Atm.java
@@ -3,13 +3,18 @@
 import java.util.concurrent.*;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.time.LocalDate;
 
 enum PinResult { OK, WRONG, LOCKED }
+enum Debit { OK, INSUFFICIENT, OVER_DAILY_LIMIT }
 
 final class Account {
     final String id;
     long balance;                                       // whole rupees, guarded by lock
     final ReentrantLock lock = new ReentrantLock();
+    LocalDate day;                                      // also guarded by lock
+    long withdrawnToday;
     Account(String id, long balance) { this.id = id; this.balance = balance; }
 }
 
@@ -19,6 +24,11 @@
     private final Map<String, Account> accounts = new ConcurrentHashMap<>();
     private final Map<String, String[]> cards = new ConcurrentHashMap<>();   // card -> {account, pin}
     private final Map<String, Integer> failed = new HashMap<>();             // guarded by this
+    private final long dailyLimit;
+    private final Supplier<LocalDate> today;            // injected, so tests can move the date
+
+    Bank() { this(Long.MAX_VALUE, LocalDate::now); }
+    Bank(long dailyLimit, Supplier<LocalDate> today) { this.dailyLimit = dailyLimit; this.today = today; }
 
     void open(String id, long balance) { accounts.put(id, new Account(id, balance)); }
     void issueCard(String card, String accountId, String pin) { cards.put(card, new String[] {accountId, pin}); }
@@ -39,14 +49,28 @@
         try { return a.balance; } finally { a.lock.unlock(); }
     }
 
-    /** Check and debit under the account's lock, so two ATMs can't both spend the same money. */
-    boolean withdraw(String id, long amount) {
+    /** Balance and daily limit are checked and updated under the same lock as the debit. */
+    Debit withdraw(String id, long amount) {
         Account a = accounts.get(id);
         a.lock.lock();
         try {
-            if (a.balance < amount) return false;
+            LocalDate d = today.get();
+            if (!d.equals(a.day)) { a.day = d; a.withdrawnToday = 0; }
+            if (a.balance < amount) return Debit.INSUFFICIENT;
+            if (a.withdrawnToday + amount > dailyLimit) return Debit.OVER_DAILY_LIMIT;
             a.balance -= amount;
-            return true;
+            a.withdrawnToday += amount;
+            return Debit.OK;
+        } finally { a.lock.unlock(); }
+    }
+
+    /** Undo a withdrawal whose cash never came out: the money and the day's allowance. */
+    void reverseWithdrawal(String id, long amount) {
+        Account a = accounts.get(id);
+        a.lock.lock();
+        try {
+            a.balance += amount;
+            if (today.get().equals(a.day)) a.withdrawnToday -= amount;
         } finally { a.lock.unlock(); }
     }
 
@@ -157,12 +181,13 @@
     Map<Integer, Integer> withdraw(Atm atm, int amount) {
         Map<Integer, Integer> notes = atm.dispenser.reserve(amount);           // 1. reserve notes
         if (notes == null) throw new IllegalStateException("this ATM can't dispense " + amount);
-        if (!atm.bank.withdraw(atm.account, amount)) {                         // 2. debit at the bank
+        Debit debit = atm.bank.withdraw(atm.account, amount);                  // 2. debit at the bank
+        if (debit != Debit.OK) {
             atm.dispenser.release(notes);
-            throw new IllegalStateException("insufficient funds");
+            throw new IllegalStateException(debit == Debit.INSUFFICIENT ? "insufficient funds" : "over the daily limit");
         }
         if (!atm.feeder.test(notes)) {                                         // 3. hand over the cash
-            atm.bank.deposit(atm.account, amount);                             // compensate
+            atm.bank.reverseWithdrawal(atm.account, amount);                   // compensate
             atm.dispenser.release(notes);
             throw new IllegalStateException("dispense failed, you have not been charged");
         }

Three details are worth saying aloud. The date comes from an injected Supplier<LocalDate>, so a test can move to tomorrow instead of waiting. The result becomes an enum, because "over the limit" and "insufficient funds" need different messages. And a jam now calls reverseWithdrawal, which gives back the day's allowance as well as the money. A plain deposit would have used up part of the customer's limit for cash they never got. Our check for this extension withdraws 800, is refused 300, jams on 200, succeeds with 200, and then withdraws 1,000 the next day.

Testing approach

Everything outside the ATM is injected: the bank, the cassettes, and the feeder that stands in for the hardware. So every failure path can be reached on purpose.

  1. The session. Each event in the wrong state is rejected. Three wrong PINs retain the card. Re-inserting the card doesn't reset the count, which is the regression test for the walkthrough's bug.
  2. The chain. It backtracks where greedy fails, and returns nothing for amounts no combination can make.
  3. Every failure leaves things as they were. Can't dispense: no debit. Insufficient funds: notes back in the cassettes. Jam: the account is refunded and the session survives.
  4. Concurrency. Two ATMs draining one account never overdraw it. Opposite transfers finish without deadlock and conserve the total.
# file: test_atm.py
import threading
import unittest

from atm import ATM, Bank, CashDispenser, PinResult


def setup(balance=10_000, cassettes=None, feeder=lambda notes: True):
    bank = Bank()
    bank.open("ACC1", balance)
    bank.open("ACC2", 0)
    bank.issue_card("4111", "ACC1", "1234")
    atm = ATM(bank, CashDispenser(cassettes or {2000: 5, 500: 10, 200: 10, 100: 10}), feeder)
    return bank, atm


def signed_in(**kw):
    bank, atm = setup(**kw)
    atm.insert_card("4111")
    atm.enter_pin("1234")
    return bank, atm


class SessionTest(unittest.TestCase):
    def test_actions_need_the_right_state(self):
        _, atm = setup()
        self.assertRaises(RuntimeError, atm.withdraw, 100)    # no card
        self.assertRaises(RuntimeError, atm.insert_card, "9999")
        atm.insert_card("4111")
        self.assertRaises(RuntimeError, atm.balance)          # no PIN yet
        self.assertRaises(RuntimeError, atm.insert_card, "4111")

    def test_third_wrong_pin_retains_the_card(self):
        _, atm = setup()
        atm.insert_card("4111")
        self.assertEqual([atm.enter_pin("0") for _ in range(3)],
                         [PinResult.WRONG, PinResult.WRONG, PinResult.LOCKED])
        self.assertEqual((atm.state, atm.retained), ("IDLE", ["4111"]))

    def test_reinserting_the_card_does_not_reset_the_count(self):
        _, atm = setup()
        for _ in range(2):
            atm.insert_card("4111")
            atm.enter_pin("0")
            atm.eject()
        atm.insert_card("4111")
        self.assertIs(atm.enter_pin("0"), PinResult.LOCKED)   # attempts live at the bank


class DispenseTest(unittest.TestCase):
    def test_chain_backtracks_where_greedy_fails(self):
        d = CashDispenser({500: 1, 200: 3, 100: 0})
        self.assertEqual(d.reserve(600), {200: 3})
        self.assertIsNone(d.reserve(150))                     # not a multiple of any note

    def test_cannot_dispense_means_no_debit(self):
        bank, atm = signed_in(cassettes={500: 1})
        self.assertRaises(RuntimeError, atm.withdraw, 1000)
        self.assertEqual(bank.balance("ACC1"), 10_000)

    def test_insufficient_funds_puts_the_notes_back(self):
        bank, atm = signed_in(balance=300)
        before = atm.dispenser.total()
        self.assertRaises(RuntimeError, atm.withdraw, 500)
        self.assertEqual((atm.dispenser.total(), bank.balance("ACC1")), (before, 300))

    def test_a_jam_refunds_the_account(self):
        bank, atm = signed_in(feeder=lambda notes: False)
        self.assertRaises(RuntimeError, atm.withdraw, 700)
        self.assertEqual(bank.balance("ACC1"), 10_000)
        self.assertEqual(atm.state, "AUTHENTICATED")          # the customer can try again


class ConcurrencyTest(unittest.TestCase):
    def test_two_atms_never_overdraw_one_account(self):
        bank, _ = setup(balance=5_000)
        atms = [ATM(bank, CashDispenser({100: 100})) for _ in range(2)]
        for a in atms:
            a.insert_card("4111")
            a.enter_pin("1234")
        dispensed, lock = [], threading.Lock()

        def drain(a):
            for _ in range(40):
                try:
                    notes = a.withdraw(100)
                    with lock:
                        dispensed.append(sum(k * v for k, v in notes.items()))
                except RuntimeError:
                    pass

        threads = [threading.Thread(target=drain, args=(a,)) for a in atms]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        self.assertEqual((sum(dispensed), bank.balance("ACC1")), (5_000, 0))

    def test_opposite_transfers_do_not_deadlock(self):
        bank, _ = setup(balance=1_000)
        bank.deposit("ACC2", 1_000)

        def move(src, dst):
            for _ in range(2_000):
                bank.transfer(src, dst, 1)

        threads = [threading.Thread(target=move, args=p) for p in [("ACC1", "ACC2"), ("ACC2", "ACC1")]]
        for t in threads:
            t.start()
        for t in threads:
            t.join(timeout=10)
            self.assertFalse(t.is_alive(), "deadlock")
        self.assertEqual(bank.balance("ACC1") + bank.balance("ACC2"), 2_000)


if __name__ == "__main__":
    unittest.main()

Run with python -m unittest test_atm. All 9 pass. A strong addition is a conservation property: across any random sequence of withdrawals, deposits and jams, the cash in the cassettes plus all account balances stays constant, apart from cash handed to customers.

Common mistakes

The four in the box above still apply. These are the others we see most:

  1. Floats for money, and truncating them in one place but not another.
  2. PIN attempts counted per session. Eject and re-insert, and the brute-force protection is gone.
  3. Reading the balance at the ATM and deciding there. Two ATMs will both approve.
  4. Check-then-act on the cassettes (canDispense, then dispense).
  5. Debiting with no plan for a failed dispense. The customer is charged for cash that never came out.
  6. Greedy note selection presented as always correct. It isn't with 200 notes, or when a cassette runs low.
  7. Transfers that lock source then destination, which deadlocks on opposite transfers.
  8. A daily limit stored on the ATM, which every other ATM ignores.

Interview follow-ups

"The network to the bank drops after you sent the debit. Did it happen?" You don't know, so you can't dispense, and you can't simply retry. Send every request with a transaction id that the bank treats as idempotent. On reconnect, ask for the outcome of that id. If it was debited and no cash came out, send a reversal with the same id.

"How do you minimise the number of notes?" The chain, trying the most notes first, usually finds a small solution, but not always the smallest. If the interviewer insists on optimal, plan with dynamic programming over amounts, as in the vending machine's change planner. Many banks prefer a mix of notes for usability, which is just a different planning strategy behind the same reserve call.

"Where do timeouts fit?" A timer posts a timeout event through the same ATM lock. CardInserted and Authenticated treat it like eject. If the cash isn't taken within some seconds, real ATMs retract it into a purge bin and reverse the debit. That's the jam flow with a different trigger.

"How is the PIN checked securely?" Not like this sample. The PIN pad encrypts it in hardware and the issuer verifies it. The design point that survives is that the issuer counts failed attempts.

"Why not a Dispensing state?" Because withdraw runs to completion here. With asynchronous hardware (eject, wait for the take sensor, time out), add one. It rejects every customer event until the sensor or the timer fires.

Further Reading