Designing an ATM Machine

Difficulty: Beginner Patterns: State, Chain of Responsibility, Strategy Asked at: Amazon, PhonePe, Goldman Sachs, retail banks


An ATM is six verbs: insert card, enter PIN, pick an operation, dispense cash, print a slip, eject card. Candidates write those six verbs in twenty minutes and then spend the rest of the round defending a design that can pay out ₹3,000 of a ₹3,500 withdrawal, or debit an account for money that never left the machine. The six verbs are not the problem. This is the one beginner-level question where the system handles real money, and an interviewer who works at a bank goes looking for the places it can go missing.

The first hard thing is that the session is a state machine and most operations are legal in exactly one state. Written as flags – boolean hasCard, boolean isAuthenticated, boolean isDispensing – eight combinations are representable when five are real, and one of them is a security hole: isAuthenticated true with hasCard false is a machine that pays out to whoever walks up after the previous customer’s card was ejected. Nothing in the type system stops it, so every money-touching method has to remember to check both flags. One SessionState enum makes the bad combinations unrepresentable instead of merely unlikely.

The second hard thing is that dispensing has to be all-or-nothing. The naive dispenser walks the denominations largest first, decrementing each till as it goes, and discovers on the last hop that it cannot make the final ₹100 – by which point three notes are committed and the books are wrong. The fix is the two-phase walk, worked out in full in the Chain of Responsibility lesson, which uses this exact dispenser as its example. This page agrees with that design and builds the rest of the machine around it, so the invariant worth memorising is the one that lesson gives you: a failed withdrawal leaves every till exactly as it was.

The third hard thing separates a real answer from a toy one, and candidates almost never raise it. The money moves in two places that can disagree. Debiting the account and pushing notes through the shutter are two operations on two pieces of hardware, and the machine can lose power between them, or the shutter can jam after the debit has landed. No ordering makes the failure disappear, so the job is to choose which failure you want: authorise and hold first, dispense second, settle third. A crash in the middle then leaves a held amount that reconciliation hands back, rather than cash on the floor with nothing to charge it to.

💡 Minor units = store money as a whole number of the smallest unit (paise, cents) in a long, never a double. Learn more →

💡 Authorisation hold = the amount is subtracted from what the account can spend but not yet from its balance. It is the banking primitive that lets a two-step payout be undone, and it is why a jam costs a customer a few hours of availability rather than the money.

💡 Idempotency key = a caller-supplied id attached to the withdrawal, so the same request arriving twice gets the same answer and one payout. Learn more →

💡 Reconciliation = a scheduled job that compares two records of the same money – the holds the bank carries against the dispenses the machine logged – and resolves the rows that disagree. Learn more →


Functional Requirements

  1. A card session: insert a card, the machine resolves the account, the customer can eject any time before dispensing starts.
  2. PIN authentication with three attempts, after which the card is retained and the account blocked.
  3. Four operations – balance inquiry, withdrawal, deposit, mini statement – legal only once authenticated.
  4. A withdrawal dispenses a note breakdown from the tills, largest denomination first, and reports the breakdown back.
  5. A failed withdrawal leaves every till and the account’s balance exactly as they were.
  6. A deposit credits the account and adds the notes to the tills.
  7. Every withdrawal carries an idempotency key, so a request retried after a timeout pays out once.

Non-Functional Requirements

  1. All-or-nothing dispensing – the read-only canDispense pass and the mutating dispense pass run under one lock, so no till is decremented for a withdrawal that then fails.
  2. Bounded work per withdrawal – the chain visits one handler per denomination, four today, and touches at most four tills. Nothing scans the ledger.
  3. Thread-safe at the right grain – the lock spans both dispenser phases, because a dry run not held against the commit is a check-then-act race. Learn more →
  4. No floating point near money – Money wraps a long of paise and exposes no double at all.

Core Entities

Entity Description
Money Immutable value object over a long of paise; the only money type in the design
Denomination Enum of note faces (₹2000, ₹500, ₹200, ₹100), declared largest first
Card Card number, account id, holder name; prints itself masked
Account Balance, held amount, PIN hash, and the failed-attempt counter
SessionState Enum of the five session states, plus the transition table
CashDispenser Abstract chain handler, one link per denomination; owns canDispense and dispense
CashInventory The tills, the only object allowed to change them, and the append-only note-movement log
Hold One authorised-but-unsettled amount, in state HELD, SETTLED or RELEASED
WithdrawalResult The outcome, separating insufficient funds from insufficient cash from a jam
ATM Facade over dispenser, inventory and bank service, and owner of the session state machine

💡 A Hold is the ledger’s record of an intention. Until it settles the money is in neither place: not spendable by the customer, not taken from the balance, and visible to reconciliation as unfinished business.

💡 WithdrawalResult carries an outcome enum rather than a boolean, because “no” has five meanings here and the ATM has to say which one on the screen. Returning false throws that away.


Two phases for the cash, three steps for the money

A state enum makes the illegal sessions unwriteable. Write the session as flags and the compiler happily lets you express a machine that is authenticated with no card in it:

if (isAuthenticated) { dispense(amount); }   // nothing here mentions the card

That line passes every test you will write in the interview and breaks the first time ejectCard() forgets to clear isAuthenticated. Three booleans give eight states, five of which exist; the other three are bugs you can only prevent by convention. Replace them with one field and AUTHENTICATED with no card stops being a state you can be in, because the only edge into it starts at CARD_INSERTED.

This is a state machine, and the honest question is whether it deserves the full State pattern – a class per state, each knowing its own transitions and legal operations. Unlike a traffic light, there genuinely is per-state behaviour here: AUTHENTICATED accepts four operations that CARD_INSERTED must refuse outright, so the pattern is not absurd and an interviewer may push for it. The call at this size is still enum plus transition table plus a requireState guard. The per-state behaviour is entirely “is this operation allowed”, which a guard expresses in one line per method where five state classes need twenty stub methods that throw, and the logic actually worth writing is the withdrawal, which does not belong split across classes named after screens. When the states grow real behaviour – per-state rendering, timeouts, a card-less flow – the classes earn themselves, and the transition table tells you exactly what they must implement. Until then, every public method opening with one requireState call is the whole mechanism, and a method that forgets it is visible in review as a missing first line.

The dispenser must not be able to half-pay. The two-phase walk is worked out in full in the Chain of Responsibility lesson, which uses this exact dispenser as its example, and this design keeps its shape unchanged: canDispense walks the chain reading tills, dispense walks it again writing them, and the second walk only runs after the first returned true. One thing moves. The lesson’s handlers each hold their own till; here they live in CashInventory and the handlers read through it, which is the answer that lesson gives to its own thread-safety question – push the mutable state out so the concurrency control sits in one object rather than four.

Two things are worth saying before the interviewer says them. First, the walk is greedy, and greedy is not correct. Ask for ₹600 from a machine holding one ₹500 and three ₹200 notes and canDispense returns false: the ₹500 goes first and strands ₹100 that nothing can cover, with 3 x ₹200 sitting right there. The chain is not broken, it is greedy, and largest-note-first is a real ATM policy because it minimises note count and shutter time. The optimal split is a bounded change-making problem, and it belongs in a NoteSelectionPolicy the chain consults rather than in any handler: the policy runs a small dynamic program over the till snapshot and returns a plan, and dispense applies it. Both phases survive, because planning is a read and applying is a write. What you must not do is claim greedy is optimal, or bolt a lookahead onto Note500Dispenser – the moment a handler reasons about the ₹200 till, the chain stops being reorderable and the if-cascade is back across four files.

Second, the dry run only guarantees anything if the commit sees the same tills. If another thread refills or drains a till between the phases, the commit can hit IllegalStateException at the tail of the chain with notes already pulled. So the whole withdrawal runs inside one critical section, and that exception asserts the critical section exists rather than offering a recovery path.

Authorise, dispense, settle – in that order. Two records of the same money, two pieces of hardware, and a machine that can die between them. Three orderings are available and two are wrong.

Dispense then debit loses the bank’s money: the notes are in the customer’s hand, the power goes, and there is no hold, no debit and no record that anyone owes anything. The bank finds out at the end-of-day cash count, with a till ₹5,000 light and nobody to charge. Debit then dispense loses the customer’s money: the balance drops, the shutter jams, and the customer is out ₹5,000 holding a slip that says it worked, with reversal requiring the bank to prove a negative.

Authorise and hold, dispense, settle is the one worth defending. Step one moves the amount out of the account’s available balance into a Hold, changing what the customer can spend without changing what they own. Step two pulls the notes and presents them. Step three settles the hold into a real debit. Every crash window then fails the same way:

  • Crash after the hold, before the dispense: the hold dangles and no cash moved. Reconciliation releases it.
  • Jam after the notes are pulled, before they are presented: the notes go back in their tills and the hold stays held, so reconciliation releases it.
  • Crash after the dispense, before the settle: the cash is gone and the amount is still held, so it cannot be spent twice. Reconciliation sees the DISPENSED entry in the note-movement log and settles rather than releases.

The worst case in all three is a few hours of reduced available balance. That is the point of this ordering: the failure mode is an inconvenience with a paper trail, not a loss.

The last piece is the idempotency key. A customer who taps “withdraw” again after the screen freezes, or a client retrying a timed-out request, must not be paid twice. The key is minted once per customer intent and TransactionService caches the answer against it, so the retry is a map lookup returning the original WithdrawalResult – same breakdown, same transaction id, no second hold, no second dispense.

classDiagram
    class SessionState {
        <<enumeration>>
        IDLE
        CARD_INSERTED
        AUTHENTICATED
        DISPENSING
        CARD_RETAINED
        +canGoTo(next) boolean
    }

    class ATM {
        -SessionState state
        -Account account
        +insertCard(card)
        +enterPin(pin) boolean
        +withdraw(amount, key) WithdrawalResult
        +checkBalance() Money
        +ejectCard()
        -requireState(allowed)
    }

    class CashDispenser {
        <<abstract>>
        -CashDispenser next
        #Denomination denomination
        +setNext(next) CashDispenser
        +canDispense(rupees) boolean
        +dispense(rupees, tally)
        #notesToUse(remaining) int
    }

    class PlainNoteDispenser
    class RationedNoteDispenser {
        -int maxPerWithdrawal
        #notesToUse(remaining) int
    }

    class CashInventory {
        -EnumMap tills
        -List~NoteMovement~ movements
        +available(denomination) int
        +totalAvailable() Money
        +putBack(txId, notes)
    }

    class TransactionService {
        -Map holds
        -Map answered
        +authorise(key, account, amount) Hold
        +settle(hold)
        +release(hold, reason)
        +replay(key) WithdrawalResult
        +reconcile(olderThan) List~Hold~
    }

    class Hold {
        -Money amount
        -HoldState state
        -Instant placedAt
    }

    class Account {
        -Money balance
        -Money held
        +available() Money
        +verifyPin(pin) boolean
    }

    class WithdrawalLimitPolicy {
        <<interface>>
        +permits(account, amount) boolean
    }

    class WithdrawalResult {
        -WithdrawalOutcome outcome
        +breakdown() String
    }

    CashDispenser <|-- PlainNoteDispenser
    CashDispenser <|-- RationedNoteDispenser
    CashDispenser --> CashDispenser : next
    CashDispenser --> CashInventory
    ATM --> SessionState
    ATM --> CashDispenser : head
    ATM --> CashInventory
    ATM --> TransactionService
    ATM --> WithdrawalResult
    TransactionService --> Hold
    TransactionService --> Account
    TransactionService --> WithdrawalLimitPolicy

💡 In a class diagram the hollow triangle means “extends this class”, the plain arrow means “holds a reference to this”, and the self-loop on CashDispenser is the chain. Learn more →

Key classes:

  • ATM – the facade and the only owner of SessionState. It knows the order of the three money steps and nothing else; it holds no tills and no balances, so there is nothing in it to corrupt.
  • SessionState – the enum plus the transition table. canGoTo turns “we would never do that” into a thrown exception, and the table is the one place to read to learn what the machine can do.
  • CashDispenser – the abstract handler. It owns the successor link and both walks as final methods, leaving subclasses one override point: notesToUse, which sees the remaining amount and its own till and never learns who comes next.
  • PlainNoteDispenser – a denomination with no policy. This class existing is the entire cost of adding ₹50 notes.
  • RationedNoteDispenser – a per-withdrawal cap, so the first customer of the morning does not take every ₹2000 note.
  • CashInventory – the tills, the only code allowed to decrement them, and the append-only log of what was dispensed, returned or deposited. Reconciliation reads this log; nobody edits it.
  • TransactionService – authorise, settle, release, the idempotency cache, the ledger and the reconciliation sweep. Because Account’s money-moving methods are package-private, it is the only class that can change a balance.
  • Hold – one amount in flight, with a state and a timestamp. The timestamp is what makes a dangling hold findable.
  • WithdrawalResult – the outcome, the note breakdown, and on failure the amount still held.
  • WithdrawalLimitPolicy – the swappable per-transaction and per-day caps, asked one question: permits.

Design Patterns

Pattern Where Why
Chain of Responsibility CashDispenser and its subclasses, one link per denomination Largest-first becomes data assembled in one place, and adding ₹50 notes is a new class rather than a fifth branch in a working method
State SessionState, its transition table, and requireState Makes “authenticated with no card” unwriteable rather than merely untested, and gives every operation a one-line legality check
Strategy WithdrawalLimitPolicy, and notesToUse as the note-selection hook Caps vary by bank and card tier; note selection varies by greedy, rationed or optimal. Both swap without touching the withdrawal flow
Facade ATM fronting the chain, CashInventory and TransactionService The customer-facing API is six verbs; the three-step money dance and the two-phase cash dance stay inside
Command (extension) Transaction entries in the ledger Promote each to an object with apply and undo and the append-only ledger becomes replayable, which is how you rebuild a day after a hardware swap
Singleton (rejected) Would be ATM or CashInventory A global makes the tills unmockable, so no test can set up “one ₹500 and three ₹200 notes” – the test that finds the greedy bug

💡 Chain of Responsibility = link handlers into a sequence and hand the request to the head, each taking part of it or passing the remainder on. Here each link owns one note face, and the chain short-circuits the moment the remainder hits zero.

💡 State pattern = let the current state decide which operations are legal. This design uses its lightweight state-machine form, because the per-state behaviour here is about legality rather than about doing different work.

💡 Strategy = put each version of an algorithm behind one interface so the caller can swap it. authorise only ever asks limits.permits(account, amount), so a tiered-card policy is a new class and not an edit.

💡 Facade = one object presenting a small API over collaborating parts. ATM is the only class a UI talks to, which is why the ordering of hold, dispense and settle lives in exactly one method.

💡 Command = wrap an action in an object carrying its own data that knows how to undo itself. The ledger is already a list of actions in order, so this is a change of type rather than of design.

💡 Singleton = one global instance with a private constructor. Rejecting it is a deliberate answer: the tills are the thing most worth testing and a global is the thing hardest to test.


Data Structures

Component Structure Why
Tills EnumMap<Denomination, Integer> Array-backed and ordinal-indexed, so lookups are O(1) with no hashing, and a till for a denomination that does not exist is unrepresentable
Dispenser chain Singly linked CashDispenser handlers, assembled in one constructor Largest-first is a fact you read in four lines, not an emergent property of scattered if blocks
Note breakdown TreeMap<Denomination, Integer> under an explicit largest-first comparator The slip and the screen want descending order, and the comparator says so rather than depending on the enum’s declaration order
Transition table EnumMap<SessionState, EnumSet<SessionState>> The legal session graph as data in one static block, which is also the thing you unit-test
Ledger and movement log Append-only List<Transaction> and List<NoteMovement> Reconciliation compares two independent records of the same money, which only works if neither can be edited after the fact
Idempotency cache Map<String, WithdrawalResult> keyed by the caller’s key Turns a retried withdrawal into a map lookup returning the original answer, with no second hold and no second dispense

The EnumMap for tills carries the most weight, and the alternative shows why. Keyed by Integer – 2000, 500, 200, 100 – the map will cheerfully accept a till for ₹300, a refill script can create one by typo, and totalAvailable adds it in. With Denomination as the key the set of possible tills is closed at compile time and the counts live in a plain array indexed by ordinal.

💡 EnumMap = a map whose keys must be constants of one enum, implemented as an array indexed by the constant’s position. Faster than HashMap and, more usefully here, unable to hold a key that is not a real denomination.


Complete Code

Core Models (Money, Denomination, SessionState, Card, Account)

Five small types, grouped because none is interesting alone. Money is a long of paise with no double in sight, Denomination is the closed set of note faces, SessionState carries the transition table, and Account holds the PIN hash plus the failed-attempt counter – which lives here rather than on the session, so ejecting and re-inserting the card does not hand an attacker three fresh guesses.

package atm;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/** Minor units only. No constructor takes a double and no method returns one. */
public final class Money {
    public static final Money ZERO = new Money(0);

    private final long paise;

    private Money(long paise) { this.paise = paise; }

    public static Money rupees(long rupees) { return new Money(rupees * 100L); }

    public Money plus(Money o)      { return new Money(paise + o.paise); }
    public Money minus(Money o)     { return new Money(paise - o.paise); }
    public Money times(long factor) { return new Money(paise * factor); }

    public boolean isLessThan(Money o) { return paise < o.paise; }

    /** The note chain works in whole rupees, because notes are whole rupees. */
    public long wholeRupees() { return paise / 100L; }

    /** A dispensable amount is a positive whole multiple of the smallest note. */
    public boolean isMultipleOf(Denomination d) {
        return paise > 0 && paise % (d.rupees() * 100L) == 0;
    }

    @Override public boolean equals(Object o) { return o instanceof Money m && paise == m.paise; }
    @Override public int hashCode()           { return Long.hashCode(paise); }
    @Override public String toString() {
        return String.format("Rs %d.%02d", paise / 100L, Math.abs(paise % 100L));
    }
}

/** The closed set of note faces, declared largest first. */
public enum Denomination {
    RS_2000(2000), RS_500(500), RS_200(200), RS_100(100);

    /** Stated as a comparator, so re-ordering the declaration cannot flip receipts. */
    public static final Comparator<Denomination> LARGEST_FIRST =
            Comparator.comparingInt((Denomination d) -> d.rupees).reversed();

    public static final Denomination SMALLEST = RS_100;

    private final int rupees;

    Denomination(int rupees) { this.rupees = rupees; }

    public int rupees()  { return rupees; }
    public Money value() { return Money.rupees(rupees); }
}

/** The session lifecycle plus the only legal edges between its states. */
public enum SessionState {
    IDLE, CARD_INSERTED, AUTHENTICATED, DISPENSING, CARD_RETAINED;

    private static final Map<SessionState, Set<SessionState>> ALLOWED =
            new EnumMap<>(SessionState.class);

    static {
        ALLOWED.put(IDLE,          EnumSet.of(CARD_INSERTED));
        ALLOWED.put(CARD_INSERTED, EnumSet.of(AUTHENTICATED, CARD_RETAINED, IDLE));
        ALLOWED.put(AUTHENTICATED, EnumSet.of(DISPENSING, IDLE));
        ALLOWED.put(DISPENSING,    EnumSet.of(AUTHENTICATED));
        // Terminal for the cardholder. The one edge out is the engineer's key,
        // which is why serviceReset is its only caller.
        ALLOWED.put(CARD_RETAINED, EnumSet.of(IDLE));
    }

    public boolean canGoTo(SessionState next) {
        return ALLOWED.getOrDefault(this, EnumSet.noneOf(SessionState.class)).contains(next);
    }
}

/** The full number never reaches a log or a screen. */
public record Card(String cardNumber, String accountId, String holderName) {
    public String maskedNumber() { return "****" + cardNumber.substring(cardNumber.length() - 4); }
}

/**
 * Every money-moving method here is package-private, so TransactionService is the
 * only class that can change a balance or a hold.
 */
public class Account {
    private final String accountId;
    private final String pinHash;      // never the PIN itself
    private Money balance;
    private Money held = Money.ZERO;   // authorised, not yet settled
    private int failedPinAttempts;     // on the account, not on the session
    private boolean blocked;

    public Account(String accountId, String pin, Money opening) {
        this.accountId = accountId;
        this.pinHash = hash(pin);
        this.balance = opening;
    }

    /** What may be spent right now: the balance minus everything already held. */
    public Money available() { return balance.minus(held); }

    public Money balance()    { return balance; }
    public Money heldAmount() { return held; }
    public String accountId() { return accountId; }

    public boolean verifyPin(String pin) {
        // Constant-time compare, so response time cannot leak how much matched. A
        // production ATM does this in an HSM against a salted PIN block; same shape.
        return MessageDigest.isEqual(hash(pin).getBytes(StandardCharsets.UTF_8),
                                     pinHash.getBytes(StandardCharsets.UTF_8));
    }

    public int recordFailedPin()   { return ++failedPinAttempts; }   // three retains
    public void resetFailedPin()   { failedPinAttempts = 0; }
    public int failedPinAttempts() { return failedPinAttempts; }
    public boolean isBlocked()     { return blocked; }
    public void block()            { blocked = true; }

    // ---- package-private: only TransactionService may call these ----
    void hold(Money a)        { held = held.plus(a); }
    void releaseHold(Money a) { held = held.minus(a); }
    void settleHold(Money a)  { held = held.minus(a); balance = balance.minus(a); }
    void credit(Money a)      { balance = balance.plus(a); }

    private static String hash(String pin) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            return Base64.getEncoder()
                         .encodeToString(md.digest(pin.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-256 unavailable", e);
        }
    }
}
# Everything else is as in the Java tab. Only Money differs: a frozen dataclass
# gives immutability, hashing and all six comparison operators in one decorator,
# and Python ints are arbitrary precision, so paise have no overflow bound.
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Money:
    paise: int

    def __post_init__(self) -> None:
        if isinstance(self.paise, float):
            raise TypeError("Money takes paise as an int, never a float")

    @staticmethod
    def rupees(r: int) -> "Money": return Money(r * 100)
    def whole_rupees(self) -> int: return self.paise // 100
// Everything else is as in the Java tab. Only Money differs: it can be a constexpr
// value type, so amounts fold at compile time, and one defaulted spaceship operator
// supplies all six comparisons where Java needs an equals plus a compareTo.
class Money {
    std::int64_t paise_ = 0;
    constexpr explicit Money(std::int64_t p) : paise_(p) {}
public:
    constexpr Money() = default;
    static constexpr Money rupees(std::int64_t r) { return Money(r * 100); }
    constexpr Money operator+(Money o) const      { return Money(paise_ + o.paise_); }
    constexpr Money operator-(Money o) const      { return Money(paise_ - o.paise_); }
    constexpr auto operator<=>(const Money&) const = default;
    constexpr bool operator==(const Money&) const = default;
    constexpr std::int64_t wholeRupees() const    { return paise_ / 100; }
};
// Everything else is as in the Java tab. One difference is not cosmetic:
// JavaScript's Number IS a double, so "store money as an integer" costs real work.
// BigInt is the only honest answer, and refusing a Number in the constructor stops
// the mistake being made quietly three classes away.
class Money {
    #paise; // BigInt, never Number

    constructor(paise) {
        if (typeof paise !== "bigint") throw new TypeError("paise must be a BigInt");
        this.#paise = paise;
        Object.freeze(this);
    }

    static rupees(r) { return new Money(BigInt(r) * 100n); }
    plus(o)          { return new Money(this.#paise + o.#paise); }
    isLessThan(o)    { return this.#paise < o.#paise; }
    wholeRupees()    { return Number(this.#paise / 100n); }   // a count, not an amount
}

CashDispenser.java

The shape the Chain of Responsibility lesson arrives at: the abstract handler owns the successor link and both walks, and subclasses get one override point. Both walks are final on purpose – a subclass that overrode either could break the all-or-nothing invariant for every denomination below it.

package atm;

import java.util.Map;

/**
 * One link per denomination. A handler sees the remaining amount and its own till and
 * never learns who comes after it, which keeps the chain reorderable.
 */
public abstract class CashDispenser {
    protected final Denomination denomination;
    protected final CashInventory inventory;
    private CashDispenser next;

    protected CashDispenser(Denomination denomination, CashInventory inventory) {
        this.denomination = denomination;
        this.inventory = inventory;
    }

    /** Returns the successor, so a whole chain assembles in one fluent statement. */
    public CashDispenser setNext(CashDispenser next) {
        this.next = next;
        return next;
    }

    /**
     * The only override point. Must be pure: both phases call it and the invariant
     * depends on them getting the same number back.
     */
    protected int notesToUse(long rupeesRemaining) {
        long wanted = rupeesRemaining / denomination.rupees();
        return (int) Math.min(wanted, inventory.available(denomination));
    }

    /** Phase one. Walks the chain and mutates nothing, anywhere. */
    public final boolean canDispense(long rupees) {
        long remaining = rupees - (long) notesToUse(rupees) * denomination.rupees();
        if (remaining == 0) return true;
        return next != null && next.canDispense(remaining);
    }

    /**
     * Phase two. Only legal after canDispense returned true under the same lock. The
     * exception at the tail asserts phase one was consulted; it is not a recovery
     * path, because by the time it fires some tills are already decremented.
     */
    public final void dispense(long rupees, Map<Denomination, Integer> tally) {
        int notes = notesToUse(rupees);
        if (notes > 0) {
            inventory.remove(denomination, notes);
            tally.put(denomination, notes);
        }
        long remaining = rupees - (long) notes * denomination.rupees();
        if (remaining == 0) return;
        if (next == null) {
            throw new IllegalStateException(
                "chain short by " + remaining + ": canDispense was not consulted");
        }
        next.dispense(remaining, tally);
    }

    public Denomination denomination() { return denomination; }
}

/** A denomination with no policy. This class is the whole cost of a new note face. */
public class PlainNoteDispenser extends CashDispenser {
    public PlainNoteDispenser(Denomination d, CashInventory inventory) { super(d, inventory); }
}

/**
 * A denomination with a per-withdrawal cap, so the first customer of the morning
 * cannot take every large note. One override, and still no knowledge of the chain.
 */
public class RationedNoteDispenser extends CashDispenser {
    private final int maxPerWithdrawal;

    public RationedNoteDispenser(Denomination d, CashInventory inventory, int maxPerWithdrawal) {
        super(d, inventory);
        this.maxPerWithdrawal = maxPerWithdrawal;
    }

    @Override protected int notesToUse(long rupeesRemaining) {
        return Math.min(super.notesToUse(rupeesRemaining), maxPerWithdrawal);
    }
}
# Structurally as in the Java tab. The one thing worth stating: Python has no
# `final`, so "no subclass may override the two walks" is a convention here rather
# than a compiler guarantee -- and the all-or-nothing invariant leans on exactly that.
    def can_dispense(self, rupees: int) -> bool:
        """Phase one: reads tills, writes nothing, anywhere."""
        remaining = rupees - self._notes_to_use(rupees) * self._denomination.rupees
        return remaining == 0 or (self._next is not None
                                  and self._next.can_dispense(remaining))

    def dispense(self, rupees: int, tally: dict[Denomination, int]) -> None:
        """Phase two: legal only once can_dispense returned True under the same lock."""
        notes = self._notes_to_use(rupees)
        if notes:
            self._inventory.remove(self._denomination, notes)
            tally[self._denomination] = notes
        remaining = rupees - notes * self._denomination.rupees
        if remaining and self._next is None:
            raise RuntimeError(f"chain short by {remaining}")
        if remaining:
            self._next.dispense(remaining, tally)
// Both walks are as in the Java tab. What differs is ownership: the chain owns its
// successor through unique_ptr, so destroying the head tears the whole chain down
// and no handler can outlive the chain it belongs to. canDispense is non-virtual,
// which is how C++ spells `final`, and notesToUse is const so the compiler helps
// keep phase one read-only.
class CashDispenser {
protected:
    CashInventory& inventory_;              // a reference: tills outlive the chain
    std::unique_ptr<CashDispenser> next_;
    virtual int notesToUse(long long remaining) const;
public:
    virtual ~CashDispenser() = default;

    CashDispenser* setNext(std::unique_ptr<CashDispenser> next) {
        next_ = std::move(next);
        return next_.get();                 // raw pointer for fluent assembly
    }

    bool canDispense(long long rupees) const {
        const long long left = rupees - notesToUse(rupees) * rupeesOf(denomination_);
        return left == 0 || (next_ && next_->canDispense(left));
    }
};
// The handler and the ration override are as in the Java tab. JavaScript gives the
// two-phase contract no language support: no `final`, no `protected`, and `#next` is
// the only genuine privacy on offer. What it does give you is the point below.
    /**
     * Synchronous end to end on purpose. One `await` here would yield the event loop
     * between the dry run and the commit, which is exactly the check-then-act race
     * the two phases exist to prevent. Staying synchronous is what buys atomicity in
     * a single-threaded runtime -- no lock required.
     */
    dispense(rupees, tally) {
        const notes = this.notesToUse(rupees);
        if (notes > 0) {
            this.inventory.remove(this.denomination, notes);
            tally.set(this.denomination, notes);
        }
        const remaining = rupees - notes * this.denomination.rupees;
        if (remaining === 0) return;
        if (this.#next === null) throw new Error(`chain short by ${remaining}`);
        this.#next.dispense(remaining, tally);
    }

CashInventory.java

The tills, and the only object allowed to change them. Keeping the counts out of the handlers lets the chain stay reorderable and puts the concurrency control in one place. The second half is the append-only movement log: every note that left, came back or was deposited, tagged with the transaction that caused it. That log is one of the two records reconciliation compares.

package atm;

import java.time.Instant;
import java.util.*;

public class CashInventory {

    public enum MovementKind { DISPENSED, RETURNED, DEPOSITED, REFILLED }

    /** One entry in the append-only log. Nothing ever edits or removes one. */
    public record NoteMovement(String txId, Instant at, MovementKind kind,
                               Map<Denomination, Integer> notes) { }

    private final EnumMap<Denomination, Integer> tills = new EnumMap<>(Denomination.class);
    private final List<NoteMovement> movements = new ArrayList<>();

    public CashInventory(Map<Denomination, Integer> opening) {
        for (Denomination d : Denomination.values()) {
            tills.put(d, opening.getOrDefault(d, 0));
        }
    }

    public synchronized int available(Denomination d) { return tills.get(d); }

    /** What the machine physically holds: the cheap pre-check before the chain walk. */
    public synchronized Money totalAvailable() {
        Money total = Money.ZERO;
        for (Map.Entry<Denomination, Integer> e : tills.entrySet()) {
            total = total.plus(e.getKey().value().times(e.getValue()));
        }
        return total;
    }

    /** A defensive copy, so a caller can prove the tills did not move. */
    public synchronized Map<Denomination, Integer> snapshot() { return new EnumMap<>(tills); }

    public synchronized List<NoteMovement> auditTrail() { return List.copyOf(movements); }

    /**
     * Called only from the commit phase. The underflow check is a tripwire: if it
     * fires, phase one was skipped or the tills moved between the phases.
     */
    synchronized void remove(Denomination d, int notes) {
        int have = tills.get(d);
        if (notes < 0 || notes > have) {
            throw new IllegalStateException(
                "till underflow on " + d + ": asked " + notes + ", have " + have);
        }
        tills.put(d, have - notes);
    }

    synchronized void add(Denomination d, int notes) { tills.put(d, tills.get(d) + notes); }

    /** The notes cleared the tills but never cleared the shutter. Put them back. */
    synchronized void putBack(String txId, Map<Denomination, Integer> notes) {
        notes.forEach(this::add);
        record(txId, MovementKind.RETURNED, notes);
    }

    /** The notes reached the customer. This entry is what lets reconciliation settle. */
    synchronized void recordDispense(String txId, Map<Denomination, Integer> notes) {
        record(txId, MovementKind.DISPENSED, notes);
    }

    synchronized void acceptDeposit(String txId, Map<Denomination, Integer> notes) {
        notes.forEach(this::add);
        record(txId, MovementKind.DEPOSITED, notes);
    }

    private void record(String txId, MovementKind kind, Map<Denomination, Integer> notes) {
        movements.add(new NoteMovement(txId, Instant.now(), kind, Map.copyOf(notes)));
    }
}
# The tills and the movement log are as in the Java tab. The difference: Python's
# RLock is re-entrant and can be handed out, which is what makes "one lock spanning
# both dispenser phases" easy to write at the ATM level -- the ATM grabs the same
# lock, so the nested acquisition inside remove() is free.
import threading
class CashInventory:
    @property
    def lock(self) -> threading.RLock:
        """Exposed so the ATM can hold it across both phases."""
        return self._lock

    def remove(self, d: Denomination, notes: int) -> None:
        with self._lock:
            have = self._tills[d]
            if notes < 0 or notes > have:
                raise RuntimeError(f"till underflow on {d}: asked {notes}, have {have}")
            self._tills[d] = have - notes
// The tills and the movement log are as in the Java tab. The difference worth
// showing is RAII locking: lock_guard releases on every exit path including the
// exception thrown on underflow, so a failed withdrawal can never leave a till
// locked. The mutex is recursive because the ATM holds it across both phases.
class CashInventory {
    mutable std::recursive_mutex mutex_;
    std::map<Denomination, int> tills_;
    using Guard = std::lock_guard<std::recursive_mutex>;
public:
    std::recursive_mutex& mutex() const { return mutex_; }

    void remove(Denomination d, int notes) {
        Guard g(mutex_);
        const int have = tills_.at(d);
        if (notes < 0 || notes > have) throw std::logic_error("till underflow");
        tills_[d] = have - notes;
    }
};
// Same structure as the Java tab, with no lock anywhere -- and that absence is the
// whole point. One event loop means nothing interleaves inside a synchronous method,
// so the two-phase walk is atomic for free. It stops being free the moment any method
// on the withdrawal path becomes async, which is the trap to name if an interviewer
// asks you to "just await the bank call".
class CashInventory {
    #tills = new Map();
    #movements = [];

    remove(denomination, notes) {
        const have = this.#tills.get(denomination);
        if (notes < 0 || notes > have) throw new Error("till underflow");
        this.#tills.set(denomination, have - notes);
    }

    putBack(txId, notes) {
        for (const [d, n] of notes) this.#tills.set(d, this.#tills.get(d) + n);
        this.#movements.push({ txId, kind: "RETURNED", notes: new Map(notes) });
    }
}

TransactionService.java

The bank side, and the owner of all three money steps. authorise places a hold, settle turns it into a real debit, release hands it back, and reconcile is the sweep that finds holds nobody finished. The idempotency cache is four lines and is what makes a retried withdrawal safe.

package atm;

import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/** Why a withdrawal ended the way it did. Six distinct kinds of "no". */
public enum WithdrawalOutcome {
    DISPENSED, INVALID_AMOUNT, LIMIT_EXCEEDED, INSUFFICIENT_FUNDS,
    INSUFFICIENT_CASH,     // the machine holds less than the amount
    UNDISPENSABLE_AMOUNT,  // enough cash, but no note combination fits
    DISPENSER_JAMMED       // notes pulled, never presented, amount still held
}

/** Everything the screen, the slip and the audit log need. */
public record WithdrawalResult(WithdrawalOutcome outcome, String txId, Money amount,
                               Map<Denomination, Integer> notes, String message) {

    public static WithdrawalResult dispensed(String txId, Money amount,
                                             Map<Denomination, Integer> notes) {
        return new WithdrawalResult(WithdrawalOutcome.DISPENSED, txId, amount,
                                    Map.copyOf(notes), "dispensed");
    }

    public static WithdrawalResult refused(WithdrawalOutcome outcome, Money amount, String why) {
        return new WithdrawalResult(outcome, null, amount, Map.of(), why);
    }

    public static WithdrawalResult jammed(String txId, Money amount, String why) {
        return new WithdrawalResult(WithdrawalOutcome.DISPENSER_JAMMED, txId, amount,
                                    Map.of(), why);
    }

    public boolean isSuccess() { return outcome == WithdrawalOutcome.DISPENSED; }

    /** Non-zero only for a jam: the amount still held, waiting on reconciliation. */
    public Money stillHeld() {
        return outcome == WithdrawalOutcome.DISPENSER_JAMMED ? amount : Money.ZERO;
    }

    public String breakdown() {
        if (notes.isEmpty()) return "(no notes)";
        Map<Denomination, Integer> ordered = new TreeMap<>(Denomination.LARGEST_FIRST);
        ordered.putAll(notes);
        StringJoiner joiner = new StringJoiner(" + ");
        ordered.forEach((d, count) -> joiner.add(d.rupees() + " x " + count));
        return joiner.toString();
    }
}

/** Caps vary by bank, card tier and machine, so they live behind an interface. */
public interface WithdrawalLimitPolicy {
    boolean permits(Account account, Money amount);
    void recordWithdrawal(String accountId, Money amount);
    String describe();
}

public class DailyCapPolicy implements WithdrawalLimitPolicy {
    private final Money perTransaction, perDay;
    private final Map<String, Money> usedToday = new HashMap<>();

    public DailyCapPolicy(Money perTransaction, Money perDay) {
        this.perTransaction = perTransaction;
        this.perDay = perDay;
    }

    @Override public boolean permits(Account account, Money amount) {
        if (perTransaction.isLessThan(amount)) return false;
        Money used = usedToday.getOrDefault(account.accountId(), Money.ZERO);
        return !perDay.isLessThan(used.plus(amount));
    }

    /** Only a settled withdrawal counts against the cap. A jam must not. */
    @Override public void recordWithdrawal(String accountId, Money amount) {
        usedToday.merge(accountId, amount, Money::plus);
    }

    @Override public String describe() { return perTransaction + " per txn, " + perDay + " per day"; }
}

public enum HoldState { HELD, SETTLED, RELEASED }

/** One amount in flight. The timestamp is what makes a dangling hold findable. */
public final class Hold {
    private final String holdId, accountId;
    private final Money amount;
    private final Instant placedAt;
    private HoldState state = HoldState.HELD;

    Hold(String holdId, String accountId, Money amount, Instant placedAt) {
        this.holdId = holdId; this.accountId = accountId;
        this.amount = amount; this.placedAt = placedAt;
    }

    public String holdId()    { return holdId; }
    public String accountId() { return accountId; }
    public Money amount()     { return amount; }
    public Instant placedAt() { return placedAt; }
    public HoldState state()  { return state; }

    void markSettled()  { state = HoldState.SETTLED; }
    void markReleased() { state = HoldState.RELEASED; }
}

public enum TxType { HOLD, WITHDRAWAL, DEPOSIT, RELEASE }

/** One line of the append-only ledger, and one line of a mini statement. */
public record Transaction(String txId, String accountId, TxType type,
                          Money amount, Instant at, String note) {
    @Override public String toString() { return type + "  " + amount + "  " + note; }
}

/** Thrown when the bank refuses before a note has been touched. */
public class AuthorisationException extends RuntimeException {
    private final WithdrawalOutcome outcome;

    public AuthorisationException(WithdrawalOutcome outcome, String message) {
        super(message);
        this.outcome = outcome;
    }

    public WithdrawalOutcome outcome() { return outcome; }
}

public class TransactionService {
    private final Map<String, Account> accounts = new HashMap<>();
    private final Map<String, Hold> holds = new LinkedHashMap<>();
    private final Map<String, WithdrawalResult> answered = new HashMap<>();
    private final List<Transaction> ledger = new ArrayList<>();
    private final WithdrawalLimitPolicy limits;
    private final AtomicLong sequence = new AtomicLong();

    public TransactionService(WithdrawalLimitPolicy limits) { this.limits = limits; }

    public synchronized void register(Account a)   { accounts.put(a.accountId(), a); }
    public synchronized Account lookup(String id)  { return accounts.get(id); }

    /** Step one. Policy, then spendable balance, then the hold. Nothing is debited yet. */
    public synchronized Hold authorise(String idempotencyKey, Account account, Money amount) {
        if (!limits.permits(account, amount)) {
            throw new AuthorisationException(WithdrawalOutcome.LIMIT_EXCEEDED, limits.describe());
        }
        if (account.available().isLessThan(amount)) {
            throw new AuthorisationException(WithdrawalOutcome.INSUFFICIENT_FUNDS,
                "available " + account.available() + ", asked " + amount);
        }
        Hold hold = new Hold(nextId("HLD"), account.accountId(), amount, Instant.now());
        account.hold(amount);
        holds.put(hold.holdId(), hold);
        log(hold.holdId(), account.accountId(), TxType.HOLD, amount, "authorised");
        return hold;
    }

    /** Step three, happy path. The notes are out, so the debit becomes real. */
    public synchronized void settle(Hold hold) {
        if (hold.state() != HoldState.HELD) {
            throw new IllegalStateException("cannot settle a hold in state " + hold.state());
        }
        accounts.get(hold.accountId()).settleHold(hold.amount());
        hold.markSettled();
        limits.recordWithdrawal(hold.accountId(), hold.amount());
        log(hold.holdId(), hold.accountId(), TxType.WITHDRAWAL, hold.amount(), "settled");
    }

    /** Step three, unhappy path. Idempotent: calling it twice must not credit twice. */
    public synchronized void release(Hold hold, String reason) {
        if (hold.state() != HoldState.HELD) return;
        accounts.get(hold.accountId()).releaseHold(hold.amount());
        hold.markReleased();
        log(hold.holdId(), hold.accountId(), TxType.RELEASE, hold.amount(), "released: " + reason);
    }

    // ---- idempotency: the same key gets the same answer, and one payout ----

    public synchronized WithdrawalResult replay(String key) { return answered.get(key); }
    public synchronized void remember(String key, WithdrawalResult r) { answered.put(key, r); }

    // ---- deposits, inquiries and the mini statement ----

    /** Returns the transaction id, so the ATM can tag the note movement with it. */
    public synchronized String deposit(Account account, Money amount) {
        String txId = nextId("TXN");
        account.credit(amount);
        log(txId, account.accountId(), TxType.DEPOSIT, amount, "cash deposit");
        return txId;
    }

    /** The mini statement: this account's slice of the append-only ledger. */
    public synchronized List<Transaction> statement(String accountId, int lastN) {
        List<Transaction> mine = new ArrayList<>();
        for (Transaction t : ledger) if (t.accountId().equals(accountId)) mine.add(t);
        return List.copyOf(mine.subList(Math.max(0, mine.size() - lastN), mine.size()));
    }

    /**
     * What a crash between the hold and the settle leaves behind. In production it runs
     * on a timer and cross-checks the note-movement log: a hold with a DISPENSED entry
     * settles, a hold without one is released.
     */
    public synchronized List<Hold> reconcile(Duration olderThan) {
        Instant cutoff = Instant.now().minus(olderThan);
        List<Hold> released = new ArrayList<>();
        for (Hold hold : holds.values()) {
            if (hold.state() == HoldState.HELD && !hold.placedAt().isAfter(cutoff)) {
                release(hold, "reconciliation: no dispense confirmation");
                released.add(hold);
            }
        }
        return released;
    }

    private String nextId(String prefix) { return prefix + "-" + sequence.incrementAndGet(); }

    private void log(String txId, String accountId, TxType type, Money amount, String note) {
        ledger.add(new Transaction(txId, accountId, type, amount, Instant.now(), note));
    }
}
# WithdrawalResult, the limit policy and the ledger are as in the Java tab. Shown
# here: the two halves of step three plus the sweep, the part a reader should be able
# to check line by line in any language.
    def settle(self, hold: Hold) -> None:
        with self._lock:                                   # step three, happy
            if hold.state is not HoldState.HELD:
                raise RuntimeError(f"cannot settle a hold in state {hold.state}")
            self._accounts[hold.account_id].settle_hold(hold.amount)
            hold.state = HoldState.SETTLED

    def release(self, hold: Hold, reason: str) -> None:
        with self._lock:                                   # step three, unhappy
            if hold.state is not HoldState.HELD:
                return                                     # idempotent on purpose
            self._accounts[hold.account_id].release_hold(hold.amount)
            hold.state = HoldState.RELEASED

    def reconcile(self, older_than: timedelta) -> list[Hold]:
        with self._lock:
            cutoff = datetime.now() - older_than
            stale = [h for h in self._holds.values()
                     if h.state is HoldState.HELD and h.placed_at <= cutoff]
            for hold in stale:
                self.release(hold, "reconciliation: no dispense confirmation")
            return stale
// The three money steps and the limit policy are as in the Java tab. Shown here:
// Hold as a shared_ptr, so the ATM and the reconciliation sweep act on the same
// object rather than on copies, and std::optional for "has this key been answered
// before" instead of a nullable return a caller might forget to check.
struct Hold {
    std::string holdId, accountId;
    Money amount;
    Clock::time_point placedAt;
    HoldState state = HoldState::HELD;
};
using HoldPtr = std::shared_ptr<Hold>;

std::optional<WithdrawalResult> TransactionService::replay(const std::string& key) const {
    Guard g(mutex_);
    auto it = answered_.find(key);
    return it == answered_.end() ? std::nullopt : std::optional{it->second};
}
// The three money steps and WithdrawalResult are as in the Java tab. The point worth
// making in JavaScript: the moment any of this becomes async -- a real core-banking
// call between authorise and settle -- every `await` is a place the process can die.
// The cache below is then not an optional extra, it is the only reason the retry
// after that death is safe.
class TransactionService {
    #holds = new Map();
    #answered = new Map();        // idempotency key to WithdrawalResult

    replay(key)           { return this.#answered.get(key) ?? null; }
    remember(key, result) { this.#answered.set(key, result); }

    release(hold, reason) {
        if (hold.state !== HoldState.HELD) return;   // idempotent on purpose
        this.accounts.get(hold.accountId).releaseHold(hold.amount);
        hold.state = HoldState.RELEASED;
    }
}

ATM.java

The facade, and the only owner of SessionState. Every customer-facing method opens with requireState, the chain is assembled in one place, and runWithdrawal is the single method that knows the order of the three money steps. The jam branch is worth reading twice: it puts the notes back and then deliberately leaves the hold alone.

package atm;

import java.util.*;

public class ATM {
    private static final int MAX_PIN_ATTEMPTS = 3;

    /** The note presenter. A real one reports a jam over a serial line. */
    @FunctionalInterface public interface Shutter { void present(Map<Denomination, Integer> notes); }

    public static final Shutter WORKING_SHUTTER = notes -> { };

    public static class ShutterJamException extends RuntimeException {
        public ShutterJamException(String message) { super(message); }
    }

    private final String atmId;
    private final CashInventory inventory;
    private final CashDispenser chainHead;
    private final TransactionService bank;
    private final Shutter shutter;

    private SessionState state = SessionState.IDLE;
    private Card card;
    private Account account;

    public ATM(String atmId, CashInventory inventory, TransactionService bank, Shutter shutter) {
        this.atmId = atmId;
        this.inventory = inventory;
        this.bank = bank;
        this.shutter = shutter;
        // Assembled in one place, so largest-note-first is a fact you can read.
        CashDispenser head = new RationedNoteDispenser(Denomination.RS_2000, inventory, 5);
        head.setNext(new PlainNoteDispenser(Denomination.RS_500, inventory))
            .setNext(new PlainNoteDispenser(Denomination.RS_200, inventory))
            .setNext(new PlainNoteDispenser(Denomination.RS_100, inventory));
        this.chainHead = head;
    }

    public SessionState state() { return state; }

    /** The guard every public method opens with. */
    private void requireState(SessionState... allowed) {
        for (SessionState s : allowed) if (state == s) return;
        throw new IllegalStateException("operation illegal in " + state
            + "; allowed only in " + Arrays.toString(allowed));
    }

    private void transitionTo(SessionState next) {
        if (!state.canGoTo(next)) {
            throw new IllegalStateException("illegal transition " + state + " to " + next);
        }
        state = next;
    }

    // ---- card and PIN ----

    public void insertCard(Card card) {
        requireState(SessionState.IDLE);
        Account resolved = bank.lookup(card.accountId());
        if (resolved == null) throw new IllegalArgumentException("unknown " + card.maskedNumber());
        this.card = card;
        this.account = resolved;
        transitionTo(SessionState.CARD_INSERTED);
    }

    /** The counter lives on the Account, so re-inserting does not give fresh guesses. */
    public boolean enterPin(String pin) {
        requireState(SessionState.CARD_INSERTED);
        if (account.isBlocked()) {
            retainCard("account already blocked");
            return false;
        }
        if (account.verifyPin(pin)) {
            account.resetFailedPin();
            transitionTo(SessionState.AUTHENTICATED);
            return true;
        }
        int attempts = account.recordFailedPin();
        if (attempts >= MAX_PIN_ATTEMPTS) {
            account.block();
            retainCard(attempts + " wrong PINs");
        }
        return false;
    }

    public void ejectCard() {
        requireState(SessionState.CARD_INSERTED, SessionState.AUTHENTICATED);
        transitionTo(SessionState.IDLE);
        card = null;
        account = null;
    }

    /** CARD_RETAINED has exactly one edge out and this is its only caller. */
    public void serviceReset() {
        requireState(SessionState.CARD_RETAINED);
        transitionTo(SessionState.IDLE);
    }

    private void retainCard(String reason) {
        transitionTo(SessionState.CARD_RETAINED);
        card = null;
        account = null;
        System.out.println("        card retained: " + reason);
    }

    // ---- the operations, all legal only once authenticated ----

    public Money checkBalance() {
        requireState(SessionState.AUTHENTICATED);
        return account.available();
    }

    public List<Transaction> miniStatement(int lastN) {
        requireState(SessionState.AUTHENTICATED);
        return bank.statement(account.accountId(), lastN);
    }

    public Money deposit(Map<Denomination, Integer> notes) {
        requireState(SessionState.AUTHENTICATED);
        Money total = Money.ZERO;
        for (Map.Entry<Denomination, Integer> e : notes.entrySet()) {
            total = total.plus(e.getKey().value().times(e.getValue()));
        }
        // Credit first, then the tills: the machine already physically holds the
        // notes, so a crash here leaves cash the end-of-day count finds and the
        // ledger explains, which is the cheap direction to fail in.
        String txId = bank.deposit(account, total);
        inventory.acceptDeposit(txId, notes);
        return total;
    }

    // ---- withdrawal: authorise, dispense, settle ----

    public WithdrawalResult withdraw(Money amount, String idempotencyKey) {
        requireState(SessionState.AUTHENTICATED);
        WithdrawalResult already = bank.replay(idempotencyKey);
        if (already != null) return already;   // a retry already answered
        WithdrawalResult result = runWithdrawal(amount, idempotencyKey);
        bank.remember(idempotencyKey, result);
        return result;
    }

    private WithdrawalResult runWithdrawal(Money amount, String idempotencyKey) {
        if (!amount.isMultipleOf(Denomination.SMALLEST)) {
            return WithdrawalResult.refused(WithdrawalOutcome.INVALID_AMOUNT, amount,
                "not a positive multiple of " + Denomination.SMALLEST.value());
        }

        // Step one. Nothing mechanical has happened yet, so a refusal here is free.
        Hold hold;
        try {
            hold = bank.authorise(idempotencyKey, account, amount);
        } catch (AuthorisationException e) {
            return WithdrawalResult.refused(e.outcome(), amount, e.getMessage());
        }

        transitionTo(SessionState.DISPENSING);
        // One critical section over both dispenser phases: a dry run not held
        // against the commit is a stale read and a check-then-act race.
        synchronized (inventory) {
            try {
                Money inMachine = inventory.totalAvailable();
                if (inMachine.isLessThan(amount)) {
                    bank.release(hold, "machine holds only " + inMachine);
                    return WithdrawalResult.refused(WithdrawalOutcome.INSUFFICIENT_CASH,
                        amount, "machine holds only " + inMachine);
                }

                long rupees = amount.wholeRupees();
                if (!chainHead.canDispense(rupees)) {          // phase one: reads only
                    bank.release(hold, "no note combination for " + amount);
                    return WithdrawalResult.refused(WithdrawalOutcome.UNDISPENSABLE_AMOUNT,
                        amount, "tills cannot make " + amount + " largest-note-first");
                }

                Map<Denomination, Integer> notes = new TreeMap<>(Denomination.LARGEST_FIRST);
                chainHead.dispense(rupees, notes);             // phase two: cannot fail

                try {
                    shutter.present(notes);                    // step two: the physical bit
                } catch (ShutterJamException jam) {
                    inventory.putBack(hold.holdId(), notes);   // every till restored
                    // The hold stays HELD on purpose. A jammed presenter cannot say
                    // whether the customer got two of the five notes out, so this
                    // code must not decide nobody was paid. Reconciliation decides.
                    return WithdrawalResult.jammed(hold.holdId(), amount, jam.getMessage());
                }

                bank.settle(hold);                             // step three
                inventory.recordDispense(hold.holdId(), notes);
                return WithdrawalResult.dispensed(hold.holdId(), amount, notes);
            } finally {
                transitionTo(SessionState.AUTHENTICATED);
            }
        }
    }
}
# The withdrawal flow is as in the Java tab. The one genuinely different thing: in
# Python the guard can be a decorator, so the legal states of a method are part of its
# declaration rather than the first line of its body -- and a test can read
# `ATM.withdraw.allowed_states` directly instead of inferring it.
import functools
from typing import Callable
def requires(*allowed: SessionState) -> Callable:
    def decorate(method: Callable) -> Callable:
        @functools.wraps(method)
        def guarded(self, *args, **kwargs):
            if self._state not in allowed:
                names = ", ".join(s.name for s in allowed)
                raise RuntimeError(f"illegal in {self._state.name}; allowed in {names}")
            return method(self, *args, **kwargs)
        guarded.allowed_states = allowed
        return guarded
    return decorate


class ATM:
    @requires(SessionState.AUTHENTICATED)
    def withdraw(self, amount: Money, key: str) -> WithdrawalResult:
        already = self._bank.replay(key)
        if already is not None:
            return already                      # a retry already answered
        result = self._run_withdrawal(amount, key)
        self._bank.remember(key, result)
        return result
// insertCard, enterPin and the withdrawal body are as in the Java tab. C++ has no
// `finally`, so "whatever happens, leave DISPENSING" becomes an RAII scope guard.
// That is better than a finally block: it fires on every exit path including a thrown
// exception, and you cannot forget to write it at the bottom of a long method,
// because it is declared at the top of one.
class StateScope {
    SessionState& state_;
    SessionState restoreTo_;
public:
    StateScope(SessionState& state, SessionState enter, SessionState restoreTo)
        : state_(state), restoreTo_(restoreTo) {
        if (!canGoTo(state_, enter)) throw std::logic_error("illegal transition");
        state_ = enter;
    }
    ~StateScope() { state_ = restoreTo_; }
    StateScope(const StateScope&) = delete;
};

// Declared once, at the top of the dispensing section, above the lock_guard. Every
// early return below it -- insufficient cash, no note combination, a jam -- releases
// the lock and leaves DISPENSING with no cleanup code written anywhere.
// insertCard, enterPin and the withdrawal body are as in the Java tab, and
// try/finally behaves exactly as it does in Java. Shown here: the guard, which
// carries the whole burden because there is no package-private and no `final`, plus
// the one JavaScript-specific hazard, flagged at the shutter call.
    #requireState(...allowed) {
        if (!allowed.includes(this.#state)) {
            throw new Error(`illegal in ${this.#state}; allowed in ${allowed.join(", ")}`);
        }
    }

    // ... inside #runWithdrawal, once phase two has pulled the notes:
            try {
                // Deliberately NOT awaited. An async presenter would yield the loop
                // with notes already out of the tills, the one place this design must
                // not be interruptible.
                this.shutter(notes);                             // step two
            } catch (jam) {
                this.inventory.putBack(hold.holdId, notes);
                // Hold left HELD on purpose. Reconciliation owns the decision.
                return WithdrawalResult.jammed(hold.holdId, amount, jam.message);
            }

Demo.java (Runnable end-to-end)

Each line prints its label, what it expected and what it got: a successful withdrawal with its note breakdown, the same request retried under the same key, a wrong PIN then a right one, three wrong PINs across two insertions ending in retention, a refusal for insufficient cash with the tills proven unchanged, an amount the greedy chain cannot make even though the cash is there, an operation in the wrong session state, and a jammed shutter leaving a held amount that reconciliation hands back.

package atm;

import java.time.Duration;
import java.util.List;
import java.util.Map;

public class Demo {

    private static void check(String label, Object expected, Object actual) {
        boolean ok = String.valueOf(expected).equals(String.valueOf(actual));
        System.out.printf("  %s  %-32s expected=%s  actual=%s%n",
                          ok ? "PASS" : "FAIL", label, expected, actual);
    }

    public static void main(String[] args) {
        TransactionService bank = new TransactionService(
            new DailyCapPolicy(Money.rupees(20000), Money.rupees(25000)));

        Account asha   = new Account("ACC-1", "1234", Money.rupees(50000));
        Account vikram = new Account("ACC-2", "4321", Money.rupees(1000));
        Account meera  = new Account("ACC-3", "1111", Money.rupees(10000));
        Account dev    = new Account("ACC-4", "2222", Money.rupees(5000));
        for (Account a : List.of(asha, vikram, meera, dev)) bank.register(a);

        Card ashaCard   = new Card("4111111111110001", "ACC-1", "Asha Rao");
        Card vikramCard = new Card("4111111111110002", "ACC-2", "Vikram Shah");
        Card meeraCard  = new Card("4111111111110003", "ACC-3", "Meera Iyer");
        Card devCard    = new Card("4111111111110004", "ACC-4", "Dev Nair");

        // Rs 8000 in the machine: 2x2000 + 4x500 + 5x200 + 10x100
        CashInventory tills = new CashInventory(Map.of(Denomination.RS_2000, 2,
            Denomination.RS_500, 4, Denomination.RS_200, 5, Denomination.RS_100, 10));
        ATM atm = new ATM("ATM-MG-ROAD", tills, bank, ATM.WORKING_SHUTTER);

        System.out.println("=== 1. Withdraw Rs 3700, then retry the same key ===");
        atm.insertCard(ashaCard);
        atm.enterPin("1234");
        WithdrawalResult first = atm.withdraw(Money.rupees(3700), "KEY-1");
        check("outcome", "DISPENSED", first.outcome());
        check("note breakdown", "2000 x 1 + 500 x 3 + 200 x 1", first.breakdown());
        check("spendable balance", "Rs 46300.00", asha.available());
        check("cash left in machine", "Rs 4300.00", tills.totalAvailable());

        Map<Denomination, Integer> afterFirst = tills.snapshot();
        WithdrawalResult retry = atm.withdraw(Money.rupees(3700), "KEY-1");
        check("retry, same transaction id", first.txId(), retry.txId());
        check("retry moved no notes", afterFirst, tills.snapshot());

        System.out.println("\n=== 2. A wrong PIN, then the right one ===");
        atm.ejectCard();
        atm.insertCard(ashaCard);
        check("wrong PIN refused", false, atm.enterPin("9999"));
        check("not authenticated", "CARD_INSERTED", atm.state());
        check("right PIN accepted", true, atm.enterPin("1234"));
        check("counter reset", 0, asha.failedPinAttempts());

        System.out.println("\n=== 3. Three wrong PINs across two insertions ===");
        atm.ejectCard();
        atm.insertCard(vikramCard);
        atm.enterPin("0000");
        atm.enterPin("0000");
        atm.ejectCard();                      // the "start a fresh session" trick
        atm.insertCard(vikramCard);
        check("counter survived the eject", 2, vikram.failedPinAttempts());
        atm.enterPin("0000");                 // third failure in the account's life
        check("session state", "CARD_RETAINED", atm.state());
        check("account blocked", true, vikram.isBlocked());
        atm.serviceReset();                   // engineer's key: the one edge out

        System.out.println("\n=== 4. Insufficient cash, tills untouched ===");
        atm.insertCard(ashaCard);
        atm.enterPin("1234");
        Map<Denomination, Integer> beforeRefusal = tills.snapshot();
        WithdrawalResult tooMuch = atm.withdraw(Money.rupees(5000), "KEY-2");
        check("outcome", "INSUFFICIENT_CASH", tooMuch.outcome());
        check("every till unchanged", beforeRefusal, tills.snapshot());
        check("hold released", "Rs 46300.00", asha.available());
        check("nothing left held", "Rs 0.00", asha.heldAmount());

        System.out.println("\n=== 5. An amount the greedy chain cannot make ===");
        CashInventory smallTill = new CashInventory(
            Map.of(Denomination.RS_500, 1, Denomination.RS_200, 3));   // Rs 1100
        ATM atm2 = new ATM("ATM-SMALL-TILL", smallTill, bank, ATM.WORKING_SHUTTER);
        atm2.insertCard(devCard);
        atm2.enterPin("2222");
        Map<Denomination, Integer> beforeGreedy = smallTill.snapshot();
        WithdrawalResult six = atm2.withdraw(Money.rupees(600), "KEY-3");
        check("machine holds more", "Rs 1100.00", smallTill.totalAvailable());
        check("outcome", "UNDISPENSABLE_AMOUNT", six.outcome());
        check("tills untouched", beforeGreedy, smallTill.snapshot());
        System.out.println("        why: largest-first takes the Rs 500 and strands"
            + " Rs 100; the optimal split is 200 x 3");
        check("greedy, not broken", "200 x 2",
              atm2.withdraw(Money.rupees(400), "KEY-4").breakdown());

        System.out.println("\n=== 6. An operation in the wrong session state ===");
        atm2.ejectCard();
        atm2.insertCard(devCard);
        try {
            atm2.withdraw(Money.rupees(100), "KEY-5");
            check("withdrawal before the PIN", "rejected", "accepted");
        } catch (IllegalStateException e) {
            check("withdrawal before the PIN", "rejected", "rejected");
            System.out.println("        message: " + e.getMessage());
        }
        check("the rejected call held nothing", "Rs 4600.00", dev.available());

        System.out.println("\n=== 7. A jammed shutter, and reconciliation ===");
        CashInventory jamTills = new CashInventory(Map.of(Denomination.RS_500, 4));
        ATM atm3 = new ATM("ATM-JAMMED", jamTills, bank, notes -> {
            throw new ATM.ShutterJamException("presenter belt stalled");
        });
        atm3.insertCard(meeraCard);
        atm3.enterPin("1111");
        WithdrawalResult jam = atm3.withdraw(Money.rupees(1000), "KEY-6");
        check("outcome", "DISPENSER_JAMMED", jam.outcome());
        check("amount still held", "Rs 1000.00", jam.stillHeld());
        check("balance not debited", "Rs 10000.00", meera.balance());
        check("but not spendable yet", "Rs 9000.00", meera.available());
        check("notes back in the till", 4, jamTills.available(Denomination.RS_500));
        List<CashInventory.NoteMovement> trail = jamTills.auditTrail();
        check("movement log says RETURNED", "RETURNED", trail.get(trail.size() - 1).kind());

        List<Hold> released = bank.reconcile(Duration.ZERO);  // production: a real age
        check("one dangling hold swept", 1, released.size());
        check("customer made whole", "Rs 10000.00", meera.available());
        check("cash never left", "Rs 2000.00", jamTills.totalAvailable());
    }
}
# Setup and scenarios 1 to 6 are as in the Java tab. Shown here: the jam and the
# sweep, the two that carry the design.
from datetime import timedelta
jam_tills = CashInventory({Denomination.RS_500: 4})
atm = ATM("ATM-JAMMED", jam_tills, bank, jamming)   # jamming raises ShutterJamError
atm.insert_card(Card("4111111111110003", "ACC-3", "Meera Iyer"))
atm.enter_pin("1111")

jam = atm.withdraw(Money.rupees(1000), "KEY-6")
check("outcome", "DISPENSER_JAMMED", jam.outcome.name)
check("amount still held", "Rs 1000.00", jam.still_held())
check("balance not debited", "Rs 10000.00", meera.balance())
check("notes back in the till", 4, jam_tills.available(Denomination.RS_500))

released = bank.reconcile(timedelta(0))
check("one dangling hold swept", 1, len(released))
check("customer made whole", "Rs 10000.00", meera.available())
// Setup and the other scenarios are as in the Java tab. Shown here: the jam, which
// is also where the RAII scope guard proves itself -- the session leaves DISPENSING
// on the exception path with no finally block anywhere in sight.
std::map<Denomination, int> opening;
opening[Denomination::RS_500] = 4;
CashInventory jamTills(opening);

auto jamming = [](const std::map<Denomination, int>&) {
    throw ShutterJamError("presenter belt stalled with notes staged");
};
ATM atm("ATM-JAMMED", jamTills, bank, jamming);
atm.insertCard(Card{"4111111111110003", "ACC-3", "Meera Iyer"});
atm.enterPin("1111");

WithdrawalResult jam = atm.withdraw(Money::rupees(1000), "KEY-6");
check("amount still held", Money::rupees(1000).toString(), jam.stillHeld().toString());
check("notes back in the till", 4, jamTills.available(Denomination::RS_500));
check("guard restored the session", std::string("AUTHENTICATED"), toString(atm.state()));
// Setup and the other scenarios are as in the Java tab. Shown here: the retry under
// the same idempotency key, because an async client is exactly the thing that retries
// and exactly the thing that dies mid-withdrawal.
const first = atm.withdraw(Money.rupees(3700), "KEY-1");
check("outcome", "DISPENSED", first.outcome);
check("note breakdown", "2000 x 1 + 500 x 3 + 200 x 1", first.breakdown());

const afterFirst = [...tills.snapshot().values()].join(",");
const retry = atm.withdraw(Money.rupees(3700), "KEY-1");
check("retry, same transaction id", first.txId, retry.txId);
check("retry moved no notes", afterFirst, [...tills.snapshot().values()].join(","));
check("retry moved no money", "Rs 46300.00", asha.available());

Sequence Diagram – A Withdrawal, and the Jam That Must Not Lose Money

💡 A sequence diagram reads top to bottom as time passing: each vertical line is one object staying alive, and each horizontal arrow is one call. The three branches are the same withdrawal ending three different ways.

sequenceDiagram
    participant C as Cardholder
    participant A as ATM
    participant B as TransactionService
    participant D as CashDispenser chain
    participant I as CashInventory

    C->>A: withdraw amount with idempotency key
    A->>B: replay key
    B-->>A: no prior answer
    A->>B: authorise and hold the amount
    B-->>A: Hold in state HELD
    Note over A,B: reserved but not debited
    A->>D: canDispense phase one
    D->>I: available per denomination
    I-->>D: till counts only
    D-->>A: verdict

    alt no note combination fits
        A->>B: release the hold
        A-->>C: UNDISPENSABLE_AMOUNT with every till unchanged
    else notes can be made and the shutter clears
        A->>D: dispense phase two
        D->>I: remove notes from each till
        A->>A: present at the shutter
        A->>B: settle the hold into a debit
        A->>I: record the dispense in the movement log
        A-->>C: DISPENSED with the note breakdown
    else notes can be made but the shutter jams
        A->>D: dispense phase two
        D->>I: remove notes from each till
        A->>A: present at the shutter fails
        A->>I: put every note back in its till
        Note over A,B: the hold is deliberately left HELD
        A-->>C: DISPENSER_JAMMED with the amount still held
    end

The third branch is the one to defend out loud. Everything mechanical has been undone, the movement log says so, and the obvious next line is bank.release(hold). The ATM does not write it, because a presenter that jammed mid-stack is the one component that cannot tell you whether two of the five notes made it out. Releasing is a decision about both records, so it belongs to the reconciliation sweep. The cost of that restraint is a few hours of reduced availability for one customer; the cost of guessing wrong the other way is cash out of the door with nothing charged against it.


How to Extend

Extension Implementation
A new denomination (Rs 50 returns) One constant in Denomination and one PlainNoteDispenser in the chain assembly. CashDispenser, CashInventory and ATM are untouched, because none of them names a denomination
Optimal note selection A new NoteSelectionPolicy that notesToUse delegates to. Today’s greedy becomes LargestFirstPolicy; an ExactChangePolicy runs a bounded change-making pass over the till snapshot. Both phases survive, because planning is a read and applying is a write
OUT_OF_SERVICE after a jam One more SessionState constant and two rows in the transition table. requireState already refuses everything it does not list, so no method body changes
Card-less UPI withdrawal A second route into AUTHENTICATED: one new edge in the transition table plus a new authenticator. The withdrawal flow below it is identical
Per-ATM and per-card-tier limits A CompositeLimitPolicy holding a list of WithdrawalLimitPolicy. authorise already asks exactly one question, so nothing in it changes
Replay a day from the ledger Promote Transaction to a Command with apply and undo. The ledger is already append-only and ordered, so replay is a loop over it

What Interviewers Look For

  1. ✅ The session is one enum, not three booleans – and the candidate can name the combination the booleans allow that the enum forbids. “Authenticated with no card inserted” is the answer, and it is a security hole rather than a tidiness complaint.
  2. ✅ The dispense is two phases and the invariant is stated – a read-only canDispense walk, then a mutating dispense walk, and out loud: a failed withdrawal leaves every till exactly as it was.
  3. ✅ Greedy is admitted to be greedy – Rs 600 from one Rs 500 and three Rs 200 notes fails, the candidate says so before being asked, and names where the optimal split would live rather than patching a handler.
  4. ✅ The money ordering is chosen and defended – authorise and hold, dispense, settle, with the three crash windows walked through and the worst case named as a few hours of availability rather than a loss.
  5. ✅ The jam does not release the hold – the candidate explains why the machine is the wrong thing to make that decision, and hands it to reconciliation.
  6. ✅ An idempotency key on the withdrawal – a retried request returns the original result, with no second hold and no second dispense, and the candidate knows this is about a customer pressing a button twice as much as about network retries.
  7. ✅ Money is minor units in a long, and the PIN counter lives on the account – no double anywhere, the PIN is a hash compared in constant time, and ejecting and re-inserting the card does not reset the attempt count.

  • Vending Machine – the same session state machine one size down, plus the change-making problem this page defers to a policy, and where the full State pattern earns its classes
  • Payment Wallet – holds, settlement and idempotency without the hardware, so the two-record problem shows up as a double-spend race instead of a jam
  • Inventory Management – reserve-then-commit over stock rather than cash, the same two-phase shape with a different unit
  • Logging Framework – the other kind of chain, a pipeline where every handler runs rather than a walk that short-circuits

Scale this design past a single process and these are the concepts it runs into:

  • Idempotency → – once the ATM talks to a core banking service over a network, the withdrawal key stops being a nicety and becomes the only thing between a timed-out retry and a double payout
  • Reconciliation → – the sweep in TransactionService is the single-process version of the end-of-day job that compares the bank’s holds against the machine’s note-movement log and resolves every row that disagrees
  • Transaction Isolation → – synchronized across both dispenser phases is a one-machine stand-in for the isolation level you need once tills and balances live in a database, where a dry-run read outside the transaction is exactly the check-then-act race the two phases prevent