LLD

Full Designs

ATM

A weak answer draws a card reader, a keypad and a cash box, and calls withdraw. We build one that holds up when the interviewer pushes: which notes make $60, what happens when the bank does not answer, and what the machine owes the customer when the dispenser jams half way.

"Design an ATM" sounds like a list of screens. A weak answer draws a CardReader, a Keypad, a CashDispenser and an Account, adds a withdraw method that subtracts from a balance, and stops. The boxes look right, and the parts that make a cash machine hard have not been touched.

The interviewer is checking what happens between the bank and the cash. The bank holds the money, and the machine holds the notes. A withdrawal changes both, over a network that can stop answering and with hardware that can jam. The design has to say which happens first, how the two stay in step, and what the customer is owed when something fails half way. There is also a smaller puzzle: $60 from a machine that holds $100, $50 and $20 notes.

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

An ATM at a glance
A customer inserts a card, enters a PIN and asks for $60 (1). The bank checks the PIN through verifyPin. The ATM works out which notes make the amount from what is in its cassettes (2). The bank debits the account, with a transaction id (3). The dispenser counts the notes out (4). Anything debited that did not reach the customer is asked back from the bank with the same id (5).A customer inserts a card, enters a PIN and asks for $60 (1). The bank checks the PIN through verifyPin. The ATM works out which notes make the amount from what is in its cassettes (2). The bank debits the account, with a transaction id (3). The dispenser counts the notes out (4). Anything debited that did not reach the customer is asked back from the bank with the same id (5).
The machine plans the notes, the bank takes the money, then the dispenser counts it out. A customer inserts a card, enters a PIN and asks for $60 (1). The bank checks the PIN through verifyPin. The ATM works out which notes make the amount from what is in its cassettes (2). The bank debits the account, with a transaction id (3). The dispenser counts the notes out (4). Anything debited that did not reach the customer is asked back from the bank with the same id (5).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Which notes does the machine hold?$20, $50 and $100, one cassette eachA Note enum, and a cash plan that works from the count in each cassette
How much can one withdrawal be?A multiple of $10, up to $1,000The amount is checked before the bank is asked
Who decides whether the money is there?The bank, over the networkBank is an interface. The ATM never sees a balance
How is the PIN checked?By the bank, which blocks a card after wrong PINs at any machine. After three wrong PINs in one visit, the machine keeps the cardA BLOCKED answer from the bank, and a counter for each visit
What if the bank does not answer?Retry once, then stop and ask for any money backTransaction ids that the bank recognises when it sees one twice
What if the dispenser jams?Give back what did not come out, and stop serving customersA reject bin, a reversal, and an out-of-service state
What can a customer do?Withdraw cash. Balance, deposits and transfers come laterOne main flow
Who refills the cash?An operator, only when nobody is using the machineA refill is refused during a visit
How many customers at once?One, standing at the machineOne visit at a time

The bank question matters most. The account does not live in the ATM, so the ATM cannot check a balance and subtract. It asks another system to move money, and that system can say yes, say no, or say nothing at all. Most of the design follows from that third answer.

Requirements

Functional:

  1. A customer inserts a card and enters a PIN, which the bank checks. If the bank has blocked the card, or after three wrong PINs in one visit, the machine keeps the card.
  2. A customer asks for a multiple of $10, up to $1,000. The machine hands out notes that add up to exactly that amount, using only the notes in its cassettes, or says that it cannot make the amount.
  3. Each withdrawal is debited from the account at most once.
  4. If the bank does not answer, or the dispenser jams, the machine asks the bank to return whatever was taken and not handed out, and keeps the request until the bank confirms it. If the machine cannot tell how much cash came out, it stops and leaves the account for a person to settle.
  5. An operator can refill the cassettes when nobody is using the machine, and can put a machine that stopped serving back in service.

Out of scope: deposits, balance checks, mini statements, changing the PIN, transfers and printed receipts. We come back to these at the end, because each is a natural follow-up.

Everything lives in memory, as is normal for a low-level design interview. The bank and the dispenser are interfaces, and the project has fake versions of both.

What the code itself must handle:

  • Two records of one withdrawal. The bank's balance and the cassettes' counts must agree with what the customer got, even when a step fails.
  • Calls that fail or never answer. A network call has three outcomes, not two.
  • A rule that may change. The way the machine picks notes is one rule among several.
  • Two threads. The customer's screen and the operator's panel run separately.

Finding the classes

A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.

From nouns to classes
ATM becomes the Atm class, and the cassettes a small class inside it. A card, a plan of notes, what the dispenser did and a journal entry become records. Note and the session's states become enums. The bank, the dispenser and the rule for picking notes become interfaces. Three nouns are crossed out. The account and its balance live at the bank. The keypad and the screen are the user interface, which calls Atm.ATM becomes the Atm class, and the cassettes a small class inside it. A card, a plan of notes, what the dispenser did and a journal entry become records. Note and the session's states become enums. The bank, the dispenser and the rule for picking notes become interfaces. Three nouns are crossed out. The account and its balance live at the bank. The keypad and the screen are the user interface, which calls Atm.
The machine, its notes and its record stay. The account belongs to the bank. ATM becomes the Atm class, and the cassettes a small class inside it. A card, a plan of notes, what the dispenser did and a journal entry become records. Note and the session's states become enums. The bank, the dispenser and the rule for picking notes become interfaces. Three nouns are crossed out. The account and its balance live at the bank. The keypad and the screen are the user interface, which calls Atm.

The noun that needs the most thought is account, because an Account with a balance looks like the obvious class to start with.

Decision

Should the ATM have an Account class?

An Account with a balance, and withdraw subtracts from it

This makes withdraw one line, and it is easy to test. But it moves the bank into the machine. A real account is shared with the branch, the app and every other ATM, so a balance held in one machine is wrong as soon as anything else changes it.

No account. The ATM asks the bank, through an interfaceOur pick

The ATM knows a card number, and nothing else about the account. It asks the bank to check a PIN and to move money, and it treats every answer as something that can fail. This is more work in the ATM, but it is the real shape of the problem, and the hard parts of the design live in exactly this gap.

Data or behaviour?

Some classes only carry data and never change once created: a card, a plan of notes, what the dispenser reports, a journal entry. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString without writing them.

cash/NotePlan.javalines 9–25 of 78
public record NotePlan(Map<Note, Integer> counts) {    public static final NotePlan EMPTY = new NotePlan(Map.of());     public NotePlan {        Objects.requireNonNull(counts, "counts");        EnumMap<Note, Integer> copy = new EnumMap<>(Note.class);        for (Map.Entry<Note, Integer> entry : counts.entrySet()) {            int count = Objects.requireNonNull(entry.getValue(), "count");            if (count < 0) {                throw new IllegalArgumentException("A count cannot be negative: " + entry);            }            if (count > 0) {                copy.put(Objects.requireNonNull(entry.getKey(), "note"), count);            }        }        counts = Map.copyOf(copy);    }

A NotePlan says how many of each note: a plan to hand out, or what was handed out. The compact constructor refuses a negative count, drops the zeros and keeps an unmodifiable copy. Because the zeros are dropped, two plans with the same notes are always equals, which the rest of the design compares often.

The class diagram

The classes and how they connect
Atm owns the Cassettes, the journal of Transactions, the reject bin and the list of reversals still waiting. It uses three interfaces: Bank and Dispenser for the systems outside the code, and CashPlanner for the rule that picks notes. FewestNotesPlanner and GreedyPlanner implement CashPlanner. Card, NotePlan, DispenseResult, Transaction and WithdrawResult are records. Note, SessionState and the outcomes are enums.Atm owns the Cassettes, the journal of Transactions, the reject bin and the list of reversals still waiting. It uses three interfaces: Bank and Dispenser for the systems outside the code, and CashPlanner for the rule that picks notes. FewestNotesPlanner and GreedyPlanner implement CashPlanner. Card, NotePlan, DispenseResult, Transaction and WithdrawResult are records. Note, SessionState and the outcomes are enums.
Atm runs the visit. Three interfaces stand for everything it does not control. Atm owns the Cassettes, the journal of Transactions, the reject bin and the list of reversals still waiting. It uses three interfaces: Bank and Dispenser for the systems outside the code, and CashPlanner for the rule that picks notes. FewestNotesPlanner and GreedyPlanner implement CashPlanner. Card, NotePlan, DispenseResult, Transaction and WithdrawResult are records. Note, SessionState and the outcomes are enums.

The classes fall into three groups:

  • Data: Card, NotePlan, DispenseResult, Transaction and WithdrawResult are records. Note, SessionState, PinOutcome, Outcome, RefillResult and TransactionStatus are enums, and so are the bank's answers, PinCheck and DebitResult.
  • The core: Atm and the Cassettes inside it. They hold everything that changes: whose visit it is, the notes, the journal and the reversals still to send.
  • Rules and outside systems: CashPlanner with two implementations, and the Bank and Dispenser interfaces. The project's FakeBank and FakeDispenser stand in for the real ones.

The rest of the article builds these one at a time.

Building it

Notes and amounts

The machine holds three kinds of note, and each knows its value in dollars:

cash/Note.javalines 6–17 of 31
public enum Note {    TWENTY(20),    FIFTY(50),    HUNDRED(100);     private static final List<Note> LARGEST_FIRST = List.of(HUNDRED, FIFTY, TWENTY);     private final int dollars;     Note(int dollars) {        this.dollars = dollars;    }

Amounts in this design are whole dollars in a long. A bank keeps cents, but a cash machine only ever moves whole notes, so its smallest unit is a dollar. NotePlan.total() adds in a long, and plus() and noteCount() add counts with Math.addExact, so a count too large for an int throws instead of wrapping round.

One visit, six states

A visit moves through a fixed set of situations. While the bank checks a PIN, the keypad must not accept another one. While the notes are being counted, the cancel button must not end the visit.

A visit, state by state
The machine waits in IDLE. A card moves it to CARD_INSERTED, and a PIN to CHECKING_PIN while the bank answers. A correct PIN leads to CHOOSING. A wrong one goes back to CARD_INSERTED. The third wrong one, a card the bank has blocked, or no answer from the bank ends the visit in IDLE. A withdrawal moves to DISPENSING while the bank and the dispenser work, then back to IDLE, or to CHOOSING after a decline. A jam or a dispenser fault leads to OUT_OF_SERVICE, which only an operator ends. Cancel works from CARD_INSERTED and CHOOSING.The machine waits in IDLE. A card moves it to CARD_INSERTED, and a PIN to CHECKING_PIN while the bank answers. A correct PIN leads to CHOOSING. A wrong one goes back to CARD_INSERTED. The third wrong one, a card the bank has blocked, or no answer from the bank ends the visit in IDLE. A withdrawal moves to DISPENSING while the bank and the dispenser work, then back to IDLE, or to CHOOSING after a decline. A jam or a dispenser fault leads to OUT_OF_SERVICE, which only an operator ends. Cancel works from CARD_INSERTED and CHOOSING.
Every action is allowed in one state, or a few. The machine waits in IDLE. A card moves it to CARD_INSERTED, and a PIN to CHECKING_PIN while the bank answers. A correct PIN leads to CHOOSING. A wrong one goes back to CARD_INSERTED. The third wrong one, a card the bank has blocked, or no answer from the bank ends the visit in IDLE. A withdrawal moves to DISPENSING while the bank and the dispenser work, then back to IDLE, or to CHOOSING after a decline. A jam or a dispenser fault leads to OUT_OF_SERVICE, which only an operator ends. Cancel works from CARD_INSERTED and CHOOSING.

The states are an enum, and each action checks it before doing anything:

atm/Atm.javalines 62–70 of 356
    public void insertCard(Card newCard) {        Objects.requireNonNull(newCard, "card");        synchronized (lock) {            requireState(SessionState.IDLE);            card = newCard;            wrongPins = 0;            state = SessionState.CARD_INSERTED;        }    }
atm/Atm.javalines 351–355 of 356
    private void requireState(SessionState expected) {        if (state != expected) {            throw new IllegalStateException("The machine is " + state + ", not " + expected);        }    }

insertCard asks requireState for IDLE. A card arriving at any other moment means the code calling Atm has a bug, because the card slot is shut during a visit, so requireState throws an IllegalStateException and nothing changes. Outcomes a customer can cause, such as a wrong PIN or a declined debit, come back as values for the screen to show. That split runs through the whole class: exceptions for programmer mistakes, returned values for people. The State pattern page describes an ATM that ignores "withdraw" until a PIN is accepted. That is the same rule seen from the screen. The screen never offers withdraw before the PIN, and the one button a person can press at any time, cancel, is ignored when it does not apply: cancel returns false. Only a call the screen should never make reaches requireState and throws.

Decision

One class per state, or an enum?

The State pattern: IdleState, CardInsertedState and four more

Each state's rules sit in one class. But each of six states would answer each of six actions, which means 36 small methods, and most of them only refuse. The states differ only in which moves they allow, which a class per state says at much greater length.

An enum, and a check at the top of each actionOur pick

Every action names the state it needs. The six states fit in one file, and every change of state is a line in Atm that sets state. Adding a state means adding an enum value and the checks that allow it.

The PIN

The bank checks the PIN, so enterPin makes a network call. The machine marks itself as CHECKING_PIN before the call and lets go of its lock, so a slow bank does not hold up anything else.

atm/Atm.javalines 72–114 of 356
    public PinOutcome enterPin(String pin) {        Objects.requireNonNull(pin, "pin");        Card current;        synchronized (lock) {            requireState(SessionState.CARD_INSERTED);            current = card;            state = SessionState.CHECKING_PIN;        }        PinCheck answer = null;        try {            answer = Objects.requireNonNull(bank.verifyPin(current.number(), pin), "answer");        } catch (BankUnavailableException e) {            // answer stays null: the card comes back below.        } finally {            if (answer == null) {                synchronized (lock) {                    endSession();                }            }        }        if (answer == null) {            return PinOutcome.BANK_UNAVAILABLE;        }        synchronized (lock) {            if (answer == PinCheck.CORRECT) {                state = SessionState.CHOOSING;                return PinOutcome.ACCEPTED;            }            if (answer == PinCheck.BLOCKED) {                retainedCards.add(current);                endSession();                return PinOutcome.CARD_BLOCKED;            }            wrongPins++;            if (wrongPins >= MAX_PIN_TRIES) {                retainedCards.add(current);                endSession();                return PinOutcome.CARD_RETAINED;            }            state = SessionState.CARD_INSERTED;            return PinOutcome.WRONG_PIN;        }    }

Notice four things.

  1. The bank is called without the lock (line 82). The state CHECKING_PIN stops a second PIN or a cancel from getting in while the bank answers.
  2. Every call without an answer ends the visit (lines 85 to 90). If the bank does not answer, answer stays null and the card comes back without counting a try (line 93). If the bank client throws anything else, the finally block still ends the visit before the exception goes on, so the machine is never left in CHECKING_PIN.
  3. A card the bank has blocked is kept (lines 100 to 104).
  4. The third wrong PIN in one visit keeps the card (lines 105 to 109). The counter belongs to the visit, so it starts at zero with each card.
Decision

Where are wrong PINs counted?

Only at the machine, for each visit

This is a rule the machine can enforce on its own. But cancelling and inserting the card again starts the count at zero, and so does moving to the next machine. On its own it stops nobody who keeps guessing.

At the bank across every machine, and at the machine for each visitOur pick

The bank counts wrong PINs across visits and machines, and answers BLOCKED once it stops the card, so the cancel-and-retry trick ends at the bank. The machine keeps a blocked card. Its own count adds one thing. It keeps a card after three wrong PINs in one visit, even when the bank has not blocked it, such as a card the bank does not recognise.

Which notes make the amount

The customer asks for an amount. The machine has to turn it into notes from its own cassettes. The simple way is greedy: take as many of the largest note as fit, then the next, and so on.

cash/GreedyPlanner.javalines 9–26 of 26
public final class GreedyPlanner implements CashPlanner {    @Override    public Optional<NotePlan> plan(long amount, Map<Note, Integer> available) {        Objects.requireNonNull(available, "available");        if (amount < 0) {            throw new IllegalArgumentException("An amount cannot be negative: " + amount);        }        EnumMap<Note, Integer> counts = new EnumMap<>(Note.class);        long left = amount;        for (Note note : Note.largestFirst()) {            long wanted = left / note.dollars();            int taken = (int) Math.min(wanted, available.getOrDefault(note, 0));            counts.put(note, taken);            left -= (long) taken * note.dollars();        }        return left == 0 ? Optional.of(new NotePlan(counts)) : Optional.empty();    }}

Greedy works for many amounts, and it fails on some that the machine can make. For $60, greedy takes one $50, and $10 is left, which nothing else can make. So greedy says no. But three $20 notes make $60. This happens even when every cassette is full.

Greedy refuses $60
The cassettes hold ten notes of each kind. On the left, greedy takes one $50 and is left with $10, which no note in the machine can make, so it refuses. On the right, the fewest-notes search also tries zero $50 notes, finds three $20 notes, and hands out $60.The cassettes hold ten notes of each kind. On the left, greedy takes one $50 and is left with $10, which no note in the machine can make, so it refuses. On the right, the fewest-notes search also tries zero $50 notes, finds three $20 notes, and hands out $60.
Taking the biggest note first can leave a remainder nothing fits. The cassettes hold ten notes of each kind. On the left, greedy takes one $50 and is left with $10, which no note in the machine can make, so it refuses. On the right, the fewest-notes search also tries zero $50 notes, finds three $20 notes, and hands out $60.

The way to pick notes is a rule, and the design already has two of them to compare. That is the place for a pattern.

cash/CashPlanner.javalines 6–13 of 13
/** Decides which notes make up an amount, from the notes the machine holds. */public interface CashPlanner {    /**     * A plan whose total is exactly {@code amount} and which uses no more of     * any note than {@code available} holds, or empty if no such plan exists.     */    Optional<NotePlan> plan(long amount, Map<Note, Integer> available);}

The machine uses FewestNotesPlanner. It tries every count of $100 notes from the most that fit down to none. For each, it tries every count of $50 notes the same way. Whatever is left must be made of $20 notes, so that count is worked out, not tried.

cash/FewestNotesPlanner.javalines 37–63 of 65
        void tryCounts(int index, long left, int notesSoFar) {            Note note = NOTES.get(index);            int stock = available.getOrDefault(note, 0);            if (index == NOTES.size() - 1) {                if (left % note.dollars() == 0 && left / note.dollars() <= stock) {                    counts[index] = (int) (left / note.dollars());                    keepIfFewer(notesSoFar + counts[index]);                }                return;            }            int most = (int) Math.min(stock, left / note.dollars());            for (int count = most; count >= 0; count--) {                counts[index] = count;                tryCounts(index + 1, left - (long) count * note.dollars(), notesSoFar + count);            }        }         private void keepIfFewer(int notes) {            if (notes < bestNotes) {                EnumMap<Note, Integer> plan = new EnumMap<>(Note.class);                for (int i = 0; i < NOTES.size(); i++) {                    plan.put(NOTES.get(i), counts[i]);                }                best = new NotePlan(plan);                bestNotes = notes;            }        }

The search keeps a plan only if it uses fewer notes than the best so far (line 55). A plan exists only if the last note divides the remainder and its cassette holds enough (line 41). With a $1,000 cap there are at most 11 counts of $100 notes. For each, only the counts of $50 notes that fit in what is left are tried, so the search checks at most 121 combinations.

Decision

Greedy, or a search for the fewest notes?

Greedy, the biggest note first

Greedy is short and fast. But with these three note sizes it refuses amounts the machine can make, such as $60 above, even when every cassette is full. Once one cassette runs low, it refuses more. The customer sees "cannot make this amount" from a machine full of cash.

Search every count, keep the fewest notesOur pick

The search finds a plan whenever one exists, and among those it keeps the one with the fewest notes. Three note sizes and a $1,000 cap keep it to at most 121 combinations. With many more note sizes or a much bigger cap, the same idea would become a dynamic-programming table over amounts, behind the same interface.

Asking for cash: plan, then the bank

A withdrawal has three steps, in this order: check and plan, debit at the bank, then dispense. The first step runs under the lock:

atm/Atm.javalines 126–151 of 356
    public WithdrawResult withdraw(long dollars) {        NotePlan plan;        String id;        Card current;        synchronized (lock) {            requireState(SessionState.CHOOSING);            if (dollars <= 0 || dollars % 10 != 0 || dollars > MAX_WITHDRAWAL) {                return WithdrawResult.refused(Outcome.INVALID_AMOUNT,                        "Choose a multiple of $10, up to " + Dollars.format(MAX_WITHDRAWAL));            }            Optional<NotePlan> found = planner.plan(dollars, cassettes.counts());            if (found.isEmpty()) {                return WithdrawResult.refused(Outcome.CANNOT_MAKE_AMOUNT,                        "This machine cannot make " + Dollars.format(dollars) + " right now");            }            plan = found.get();            if (plan.total() != dollars || !cassettes.hold(plan)) {                throw new IllegalStateException("The planner offered " + plan + " for "                        + Dollars.format(dollars));            }            id = nextTransactionId();            current = card;            record(new Transaction(id, current.number(), dollars, 0, 0,                    TransactionStatus.IN_PROGRESS));            state = SessionState.DISPENSING;        }

The amount is checked first (line 132). A bad amount is a person's mistake, so it comes back as INVALID_AMOUNT and the customer can choose again. Then the plan is made from the cassettes (line 136). The machine does not trust the planner. If a plan does not add up to the amount, or uses notes the cassettes do not hold, withdraw throws before anything moves (line 142). Only then does the withdrawal get a transaction id (line 146), a journal entry marked IN_PROGRESS (line 148), and the state DISPENSING (line 150).

Decision

Plan the notes before asking the bank, or after?

Ask the bank first, then work out the notes

This keeps the bank call first, where it is easy to see. But if the cassettes cannot make the amount, the customer has already been debited, and the machine must ask for the money back for a withdrawal that never had a chance.

Plan first, and ask the bank only for an amount the machine can payOur pick

A refusal for missing notes then costs nothing: no debit, no reversal and no transaction id. The plan stays valid while the bank answers, because no other visit and no refill can touch the cassettes while the state is DISPENSING.

Everything after this point runs without the lock and calls the bank and the dispenser, which can fail in ways nobody planned for. So the rest of the withdrawal runs inside a safety net:

atm/Atm.javalines 153–163 of 356
        boolean settled = false;        try {            WithdrawResult result = debitAndDispense(id, current, dollars, plan);            settled = true;            return result;        } finally {            if (!settled) {                markUnknown(id, current, dollars);            }        }    }
atm/Atm.javalines 321–334 of 356
    /** Anything unexpected before this withdrawal was recorded: stop, and leave it to a person. */    private void markUnknown(String id, Card current, long dollars) {        synchronized (lock) {            if (journal.get(id).status() != TransactionStatus.IN_PROGRESS) {                return;            }            record(new Transaction(id, current.number(), dollars, 0, 0,                    TransactionStatus.UNKNOWN));            if (state == SessionState.DISPENSING) {                endSession();                state = SessionState.OUT_OF_SERVICE;            }        }    }

If anything escapes before this withdrawal has been recorded, even an Error, markUnknown records it as UNKNOWN. If the machine is still dispensing, it also takes the machine out of service (lines 329 to 331), so the machine is never left stuck in DISPENSING. It checks this withdrawal's own journal entry, not the machine's state (line 324). A withdrawal already recorded, say as BANK_UNAVAILABLE with its reversal sent, is left alone, and so is the next customer's visit.

The bank sits behind an interface, and its contract is where the safety comes from:

bank/Bank.javalines 7–25 of 25
public interface Bank {    /** BLOCKED once the bank has stopped the card, for example after wrong PINs at any machine. */    PinCheck verifyPin(String cardNumber, String pin);     /**     * Takes {@code dollars} from the card's account. A second call with the     * same transaction id returns the first call's answer and moves no money.     * A debit whose id was already reversed is CANCELLED and moves no money.     */    DebitResult debit(String transactionId, String cardNumber, long dollars);     /**     * Gives back up to {@code dollars} of that transaction's debit, which must     * be more than zero. A second reversal for the same id does nothing. A     * reversal for an id the bank has not seen cancels that id, so a debit     * that arrives later with it moves no money.     */    void reverse(String transactionId, long dollars);}

Three promises matter. A debit repeated with the same transaction id returns the first answer and moves no money. A second reversal with the same id does nothing. A reversal for an id the bank has not seen cancels that id, so a debit that was only slow, and arrives after the reversal, is cancelled and moves no money. A bank that a machine retries against has to offer all three, because any call over a network can arrive twice, or late.

The debit itself runs without the lock:

atm/Atm.javalines 300–307 of 356
    private DebitResult debitWithOneRetry(String id, Card current, long dollars) {        try {            return bank.debit(id, current.number(), dollars);        } catch (BankUnavailableException first) {            // The same id, so the bank cannot take the money twice.            return bank.debit(id, current.number(), dollars);        }    }

If the first call gets no answer, the machine cannot tell whether the bank took the money and the reply was lost, or the call never arrived. So it asks again with the same id (line 305). If the first call did debit, the bank returns the first answer and takes nothing more.

atm/Atm.javalines 165–191 of 356
    private WithdrawResult debitAndDispense(String id, Card current, long dollars, NotePlan plan) {        DebitResult debit;        try {            debit = Objects.requireNonNull(debitWithOneRetry(id, current, dollars), "answer");        } catch (RuntimeException e) {            // Nobody knows whether the account was debited, so ask for all of it back.            synchronized (lock) {                pendingReversals.put(id, dollars);                record(new Transaction(id, current.number(), dollars, 0, dollars,                        TransactionStatus.BANK_UNAVAILABLE));                endSession();            }            sendReversal(id, dollars);            if (e instanceof BankUnavailableException) {                return WithdrawResult.refused(Outcome.BANK_UNAVAILABLE,                        "Your bank did not answer. Any money taken will be returned");            }            throw e;        }        if (debit != DebitResult.APPROVED) {            synchronized (lock) {                record(new Transaction(id, current.number(), dollars, 0, 0,                        TransactionStatus.DECLINED));                state = SessionState.CHOOSING;            }            return WithdrawResult.refused(Outcome.DECLINED, "Your bank declined: " + debit);        }

A null answer is a bug in the bank client, and nobody knows what it did, so requireNonNull sends it down the same path as no answer (line 168). If the bank still does not answer, the machine first writes down what it owes. The id goes into pendingReversals, and the journal says the whole amount was asked back (lines 172 to 175). Then it sends the reversal with the same id (line 177). If the debit happened, the reversal undoes it. If the debit never arrived, or is only late, the reversal cancels the id. If the reversal fails too, the id stays in pendingReversals to be sent again. A decline is an ordinary answer: it is recorded, and the customer goes back to CHOOSING to try a smaller amount (line 188).

Decision

What does the machine do when the bank does not answer?

Tell the customer it failed, and do nothing else

This is the simple answer. But a lost reply can hide a debit that happened, so the customer would be charged for cash they never got, and the machine would have no record that anything was owed.

Retry with the same id, then ask for the money backOur pick

The retry turns most lost replies into a normal withdrawal. When the bank stays silent, the reversal covers every case. If the debit happened, it is undone. If it did not arrive, or is still on its way, the id is cancelled. The cost is that the bank must recognise transaction ids, which it needs anyway for any retry.

When the cash does not come out

After an approved debit, the dispenser counts the notes. A dispenser can jam. Notes that reached the customer are handed out, and notes it picked but could not present go to a reject bin inside the machine. The contract says the two together are never more than the plan. A fault before any note moves gives an empty result, and the dispenser throws only when it cannot tell which notes moved:

hardware/Dispenser.javalines 6–14 of 14
public interface Dispenser {    /**     * Counts out the plan. Notes that reach the customer are handed out;     * notes picked but caught in a jam go to the reject bin. Together they     * are never more than the plan. A fault before any note moves returns     * an empty result. It throws only when it cannot tell which notes moved.     */    DispenseResult dispense(NotePlan plan);}
atm/Atm.javalines 193–219 of 356
        DispenseResult result = dispenser.dispense(plan);        NotePlan picked = result.handedOut().plus(result.rejected());        if (!plan.covers(picked)) {            throw new IllegalStateException("The dispenser reported " + picked + " for " + plan);        }        long given = result.handedOut().total();        long missing = dollars - given;        synchronized (lock) {            cassettes.remove(picked);            rejectBin = rejectBin.plus(result.rejected());            endSession();            if (missing == 0) {                record(new Transaction(id, current.number(), dollars, dollars, 0,                        TransactionStatus.COMPLETED));                return new WithdrawResult(Outcome.DISPENSED, result.handedOut(),                        "Please take your cash");            }            pendingReversals.put(id, missing);            record(new Transaction(id, current.number(), dollars, given, missing,                    TransactionStatus.SHORT_DISPENSE));            state = SessionState.OUT_OF_SERVICE;        }        sendReversal(id, missing);        return new WithdrawResult(Outcome.SHORT_DISPENSE, result.handedOut(),                "Only " + Dollars.format(given) + " could be given. "                        + Dollars.format(missing) + " will be returned");    }

A report of more notes than the plan held is a fault (line 195), and the safety net takes over. Otherwise the machine works out how much did not reach the customer (lines 198 and 199). Then, under the lock and before calling anyone, it does the bookkeeping. The notes that left the cassettes, handed out or rejected, come off the counts, and the rejected ones go into the reject bin (lines 201 and 202). The missing amount goes into pendingReversals, the journal records the short dispense, and the machine goes out of service (lines 210 to 213). Only then does it ask the bank for the missing amount, with the same transaction id (line 215). A dispenser that jammed once should be looked at before the next customer.

A jam, a missed reversal and a retry
Asha asks for $300, and the plan is three $100 notes. The bank debits $300 (1). The dispenser hands out one note, jams on the second and leaves the third in the cassette (2). The machine writes $200 against ATM7-000005 into pendingReversals and goes out of service. Then it asks the bank to reverse $200 with the same id, but the call times out (3), so the entry stays. Later, the retry reaches the bank and Asha gets $200 back (4). The cassettes lost two notes, one handed out and one in the reject bin.Asha asks for $300, and the plan is three $100 notes. The bank debits $300 (1). The dispenser hands out one note, jams on the second and leaves the third in the cassette (2). The machine writes $200 against ATM7-000005 into pendingReversals and goes out of service. Then it asks the bank to reverse $200 with the same id, but the call times out (3), so the entry stays. Later, the retry reaches the bank and Asha gets $200 back (4). The cassettes lost two notes, one handed out and one in the reject bin.
The customer is owed what was debited and not handed out, until the bank confirms it. Asha asks for $300, and the plan is three $100 notes. The bank debits $300 (1). The dispenser hands out one note, jams on the second and leaves the third in the cassette (2). The machine writes $200 against ATM7-000005 into pendingReversals and goes out of service. Then it asks the bank to reverse $200 with the same id, but the call times out (3), so the entry stays. Later, the retry reaches the bank and Asha gets $200 back (4). The cassettes lost two notes, one handed out and one in the reject bin.

A reversal that fails is not forgotten. It waits in pendingReversals until the bank takes it:

atm/Atm.javalines 246–258 of 356
    /** Sends every reversal the bank has not confirmed yet. Returns how many are still waiting. */    public int retryPendingReversals() {        Map<String, Long> waiting;        synchronized (lock) {            waiting = new LinkedHashMap<>(pendingReversals);        }        for (Map.Entry<String, Long> entry : waiting.entrySet()) {            sendReversal(entry.getKey(), entry.getValue());        }        synchronized (lock) {            return pendingReversals.size();        }    }
atm/Atm.javalines 309–319 of 356
    /** Asks for the money back. It leaves pendingReversals only once the bank has taken it. */    private void sendReversal(String id, long dollars) {        try {            bank.reverse(id, dollars);        } catch (RuntimeException e) {            return;        }        synchronized (lock) {            pendingReversals.remove(id);        }    }

retryPendingReversals copies the waiting reversals under the lock and sends each one without it (lines 250 and 253). sendReversal leaves an id in the list when the call fails (line 314), and removes it only after the bank has taken it (line 317). Two retries running at once could both send the same reversal, and the bank's promise makes the second one do nothing.

One case is handled differently. If the dispenser throws instead of reporting, or reports more notes than the plan held, nobody knows how much cash came out. The safety net records the withdrawal as UNKNOWN, takes the machine out of service, and lets the exception go on to the caller.

Decision

What if nobody knows how much cash came out?

Reverse the whole amount, to be safe for the customer

This protects the customer if no cash came out. But if the notes did come out, the customer keeps both the cash and the money, and nothing in the machine records that anything went wrong.

Reverse nothing, stop the machine, and leave it to a personOur pick

The journal entry says UNKNOWN, the account stays debited and the machine stops. An operator counts the cassettes and the reject bin, which shows what came out, and the bank settles the difference. A machine should not guess about money when it has a way to find out.

The operator, and two threads

The operator's panel runs on its own thread. A refill is accepted only when nobody is using the machine, and the panel learns why one was refused: BUSY during a visit, FULL when a cassette would pass 2,500 notes:

atm/Atm.javalines 223–234 of 356
    public RefillResult refill(Note note, int count) {        Objects.requireNonNull(note, "note");        if (count <= 0) {            throw new IllegalArgumentException("A refill adds at least one note: " + count);        }        synchronized (lock) {            if (state != SessionState.IDLE && state != SessionState.OUT_OF_SERVICE) {                return RefillResult.BUSY;            }            return cassettes.add(note, count) ? RefillResult.ADDED : RefillResult.FULL;        }    }

Every field that changes is guarded by lock, a private object, so no code outside Atm can hold it by accident. The lock is held only for checks and bookkeeping. The bank and the dispenser are never called while it is held. The states CHECKING_PIN and DISPENSING do the guarding while the PIN check, the debit and the dispense run. During DISPENSING the operator's refill returns BUSY and cancel returns false. The screen disables withdraw after the first tap, so a second call is a bug in the screen. The lock makes it harmless: the second call finds DISPENSING, and requireState throws with nothing changed. Reversals run without a guarding state, after the visit has ended or from retryPendingReversals, and rely on the bank ignoring a repeat.

Two taps on withdraw
On the left, there is no lock. Tap A and tap B both read the state as CHOOSING at the same moment, both make a plan, and both ask the bank for $100, so the customer can be debited and paid twice. On the right, the first step is synchronized. Tap A sets DISPENSING before letting go of the lock, so tap B finds DISPENSING and is refused with nothing changed. The screen should have disabled the button, so tap B is a screen bug that the lock makes harmless.On the left, there is no lock. Tap A and tap B both read the state as CHOOSING at the same moment, both make a plan, and both ask the bank for $100, so the customer can be debited and paid twice. On the right, the first step is synchronized. Tap A sets DISPENSING before letting go of the lock, so tap B finds DISPENSING and is refused with nothing changed. The screen should have disabled the button, so tap B is a screen bug that the lock makes harmless.
Without the lock, both taps see CHOOSING and both go to the bank. On the left, there is no lock. Tap A and tap B both read the state as CHOOSING at the same moment, both make a plan, and both ask the bank for $100, so the customer can be debited and paid twice. On the right, the first step is synchronized. Tap A sets DISPENSING before letting go of the lock, so tap B finds DISPENSING and is refused with nothing changed. The screen should have disabled the button, so tap B is a screen bug that the lock makes harmless.
Decision

Hold the lock while the bank answers, or mark the machine busy?

Hold the lock for the whole withdrawal

This is the simplest code, and nothing can get in half way. But the bank can take many seconds to answer, and the operator's panel and every reader of the machine's state would wait the whole time behind one network call.

Hold the lock only to change the state, and let the state guard the slow partOur pick

The lock is held for a few field changes at a time. The state says what may happen next, so nothing can start a second withdrawal or a refill while the debit or the dispense runs. The cost is that every action must check the state, which the design does anyway.

The project includes a check, demo/RaceCheck.java. It sends two taps on withdraw at the same moment, 2,000 times. Then one thread makes 2,000 visits while an operator thread keeps trying to refill, and it counts every note:

$ java demo.RaceCheck
Two taps on withdraw, 2,000 times: paid twice 0 times, debited twice 0 times
Customer and operator at once: 2000 of 2,000 visits paid
Every note accounted for: true
Bank debits match cash handed out: true

No tap was paid twice, every note is accounted for, and the bank's debits match the cash handed out. We also ran the check with the lock removed from the first step of withdraw. Those runs crashed: one tap read the card after the other tap had already ended the visit. In a version of the check that caught those errors, some rounds paid out twice or debited the account twice. The exact numbers change from run to run and from machine to machine.

The final design

Atm is the core. It owns the Cassettes, the journal, the reject bin, the waiting reversals and the one lock. It reaches the bank and the dispenser, which are outside the code, and the rule for picking notes, which may change, only through three interfaces: Bank, Dispenser and CashPlanner.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Atm carries 3, 5, 6, 7 and 8. Bank carries 1, SessionState carries 2, and FewestNotesPlanner carries 4. CashPlanner carries a Strategy tag.The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Atm carries 3, 5, 6, 7 and 8. Bank carries 1, SessionState carries 2, and FewestNotesPlanner carries 4. CashPlanner carries a Strategy tag.
Each decision lands on one class. One interface carries a pattern. The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Atm carries 3, 5, 6, 7 and 8. Bank carries 1, SessionState carries 2, and FewestNotesPlanner carries 4. CashPlanner carries a Strategy tag.
S.No.The questionWhat we choseWhy
1Should the ATM have an Account class?No account. The ATM asks the bank, through an interfaceA balance held in one machine is wrong as soon as anything else changes it
2One class per state, or an enum?An enum, and a check at the top of each actionThe states differ only in which moves they allow
3Where are wrong PINs counted?At the bank across every machine, and at the machine for each visitThe bank ends the cancel-and-retry trick, and the machine still keeps a card after three wrong PINs in one visit
4Greedy, or a search for the fewest notes?Search every count, keep the fewest notesThe search finds a plan whenever one exists, so $60 comes out as three $20 notes
5Plan the notes before asking the bank, or after?Plan first, and ask the bank only for an amount the machine can payA refusal for missing notes costs no debit, no reversal and no transaction id
6What does the machine do when the bank does not answer?Retry with the same id, then ask for the money backA lost reply can hide a debit, and the same id stops either call moving money twice
7What if nobody knows how much cash came out?Reverse nothing, stop the machine, and leave it to a personAn operator can count the cassettes and the reject bin, so the machine does not have to guess
8Hold the lock while the bank answers, or mark the machine busy?Hold the lock only to change the state, and let the state guard the slow partA slow bank never holds up the operator's panel or any reader of the state

Here is one withdrawal of $60, end to end:

  1. The screen calls withdraw(60), which takes the lock in a synchronized (lock) block. requireState checks for CHOOSING, withdraw checks the amount, and planner.plan makes a plan from cassettes.counts(). Then cassettes.hold confirms the plan. If the amount is wrong or no plan exists, withdraw returns a refusal and nothing changes.
  2. Still under the lock, nextTransactionId gives the withdrawal its id, and record writes an IN_PROGRESS entry in the journal. The state becomes DISPENSING, and the lock is released. If anything later throws while this entry is still IN_PROGRESS, markUnknown records it as UNKNOWN.
  3. debitAndDispense calls debitWithOneRetry, which calls Bank.debit and retries once with the same id if the bank does not answer. This runs outside the lock. The state DISPENSING keeps out a second withdrawal, a cancel and a refill.
  4. After an approved debit, Dispenser.dispense counts out the notes and reports what was handed out and what went to the reject bin. This also runs outside the lock, guarded by DISPENSING.
  5. debitAndDispense takes the lock again. cassettes.remove takes the notes off the counts, and endSession sets the state back to IDLE. Then record replaces the journal entry with a COMPLETED one. The lock is released, and withdraw returns DISPENSED with the notes.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

atmAtm.java
package atm; import bank.Bank;import bank.BankUnavailableException;import bank.DebitResult;import bank.PinCheck;import card.Card;import cash.CashPlanner;import cash.Dollars;import cash.Note;import cash.NotePlan;import hardware.DispenseResult;import hardware.Dispenser;import journal.Transaction;import journal.TransactionStatus; import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional; /** * One cash machine: a customer's visit, the cash in its cassettes, and its * record of every withdrawal. */public final class Atm {    public static final int MAX_PIN_TRIES = 3;    public static final long MAX_WITHDRAWAL = 1_000;     private final String machineId;    private final Bank bank;    private final Dispenser dispenser;    private final CashPlanner planner;     // Every field below is guarded by lock. The bank and the dispenser are    // never called while it is held.    private final Object lock = new Object();    private final Cassettes cassettes = new Cassettes();    private final List<Card> retainedCards = new ArrayList<>();    private final Map<String, Transaction> journal = new LinkedHashMap<>();    private final Map<String, Long> pendingReversals = new LinkedHashMap<>();    private NotePlan rejectBin = NotePlan.EMPTY;    private SessionState state = SessionState.IDLE;    private Card card;    private int wrongPins;    private long sequence;     public Atm(String machineId, Bank bank, Dispenser dispenser, CashPlanner planner) {        if (machineId == null || machineId.isBlank()) {            throw new IllegalArgumentException("A machine needs an id");        }        this.machineId = machineId;        this.bank = Objects.requireNonNull(bank, "bank");        this.dispenser = Objects.requireNonNull(dispenser, "dispenser");        this.planner = Objects.requireNonNull(planner, "planner");    }     // ------------------------------------------------------------ customer     public void insertCard(Card newCard) {        Objects.requireNonNull(newCard, "card");        synchronized (lock) {            requireState(SessionState.IDLE);            card = newCard;            wrongPins = 0;            state = SessionState.CARD_INSERTED;        }    }     public PinOutcome enterPin(String pin) {        Objects.requireNonNull(pin, "pin");        Card current;        synchronized (lock) {            requireState(SessionState.CARD_INSERTED);            current = card;            state = SessionState.CHECKING_PIN;        }        PinCheck answer = null;        try {            answer = Objects.requireNonNull(bank.verifyPin(current.number(), pin), "answer");        } catch (BankUnavailableException e) {            // answer stays null: the card comes back below.        } finally {            if (answer == null) {                synchronized (lock) {                    endSession();                }            }        }        if (answer == null) {            return PinOutcome.BANK_UNAVAILABLE;        }        synchronized (lock) {            if (answer == PinCheck.CORRECT) {                state = SessionState.CHOOSING;                return PinOutcome.ACCEPTED;            }            if (answer == PinCheck.BLOCKED) {                retainedCards.add(current);                endSession();                return PinOutcome.CARD_BLOCKED;            }            wrongPins++;            if (wrongPins >= MAX_PIN_TRIES) {                retainedCards.add(current);                endSession();                return PinOutcome.CARD_RETAINED;            }            state = SessionState.CARD_INSERTED;            return PinOutcome.WRONG_PIN;        }    }     public boolean cancel() {        synchronized (lock) {            if (state != SessionState.CARD_INSERTED && state != SessionState.CHOOSING) {                return false;            }            endSession();            return true;        }    }     public WithdrawResult withdraw(long dollars) {        NotePlan plan;        String id;        Card current;        synchronized (lock) {            requireState(SessionState.CHOOSING);            if (dollars <= 0 || dollars % 10 != 0 || dollars > MAX_WITHDRAWAL) {                return WithdrawResult.refused(Outcome.INVALID_AMOUNT,                        "Choose a multiple of $10, up to " + Dollars.format(MAX_WITHDRAWAL));            }            Optional<NotePlan> found = planner.plan(dollars, cassettes.counts());            if (found.isEmpty()) {                return WithdrawResult.refused(Outcome.CANNOT_MAKE_AMOUNT,                        "This machine cannot make " + Dollars.format(dollars) + " right now");            }            plan = found.get();            if (plan.total() != dollars || !cassettes.hold(plan)) {                throw new IllegalStateException("The planner offered " + plan + " for "                        + Dollars.format(dollars));            }            id = nextTransactionId();            current = card;            record(new Transaction(id, current.number(), dollars, 0, 0,                    TransactionStatus.IN_PROGRESS));            state = SessionState.DISPENSING;        }         boolean settled = false;        try {            WithdrawResult result = debitAndDispense(id, current, dollars, plan);            settled = true;            return result;        } finally {            if (!settled) {                markUnknown(id, current, dollars);            }        }    }     private WithdrawResult debitAndDispense(String id, Card current, long dollars, NotePlan plan) {        DebitResult debit;        try {            debit = Objects.requireNonNull(debitWithOneRetry(id, current, dollars), "answer");        } catch (RuntimeException e) {            // Nobody knows whether the account was debited, so ask for all of it back.            synchronized (lock) {                pendingReversals.put(id, dollars);                record(new Transaction(id, current.number(), dollars, 0, dollars,                        TransactionStatus.BANK_UNAVAILABLE));                endSession();            }            sendReversal(id, dollars);            if (e instanceof BankUnavailableException) {                return WithdrawResult.refused(Outcome.BANK_UNAVAILABLE,                        "Your bank did not answer. Any money taken will be returned");            }            throw e;        }        if (debit != DebitResult.APPROVED) {            synchronized (lock) {                record(new Transaction(id, current.number(), dollars, 0, 0,                        TransactionStatus.DECLINED));                state = SessionState.CHOOSING;            }            return WithdrawResult.refused(Outcome.DECLINED, "Your bank declined: " + debit);        }         DispenseResult result = dispenser.dispense(plan);        NotePlan picked = result.handedOut().plus(result.rejected());        if (!plan.covers(picked)) {            throw new IllegalStateException("The dispenser reported " + picked + " for " + plan);        }        long given = result.handedOut().total();        long missing = dollars - given;        synchronized (lock) {            cassettes.remove(picked);            rejectBin = rejectBin.plus(result.rejected());            endSession();            if (missing == 0) {                record(new Transaction(id, current.number(), dollars, dollars, 0,                        TransactionStatus.COMPLETED));                return new WithdrawResult(Outcome.DISPENSED, result.handedOut(),                        "Please take your cash");            }            pendingReversals.put(id, missing);            record(new Transaction(id, current.number(), dollars, given, missing,                    TransactionStatus.SHORT_DISPENSE));            state = SessionState.OUT_OF_SERVICE;        }        sendReversal(id, missing);        return new WithdrawResult(Outcome.SHORT_DISPENSE, result.handedOut(),                "Only " + Dollars.format(given) + " could be given. "                        + Dollars.format(missing) + " will be returned");    }     // ------------------------------------------------------------ operator     public RefillResult refill(Note note, int count) {        Objects.requireNonNull(note, "note");        if (count <= 0) {            throw new IllegalArgumentException("A refill adds at least one note: " + count);        }        synchronized (lock) {            if (state != SessionState.IDLE && state != SessionState.OUT_OF_SERVICE) {                return RefillResult.BUSY;            }            return cassettes.add(note, count) ? RefillResult.ADDED : RefillResult.FULL;        }    }     public boolean putBackInService() {        synchronized (lock) {            if (state != SessionState.OUT_OF_SERVICE) {                return false;            }            state = SessionState.IDLE;            return true;        }    }     /** Sends every reversal the bank has not confirmed yet. Returns how many are still waiting. */    public int retryPendingReversals() {        Map<String, Long> waiting;        synchronized (lock) {            waiting = new LinkedHashMap<>(pendingReversals);        }        for (Map.Entry<String, Long> entry : waiting.entrySet()) {            sendReversal(entry.getKey(), entry.getValue());        }        synchronized (lock) {            return pendingReversals.size();        }    }     // ------------------------------------------------------------ reading     public SessionState state() {        synchronized (lock) {            return state;        }    }     public NotePlan cash() {        synchronized (lock) {            return new NotePlan(cassettes.counts());        }    }     public NotePlan rejectBin() {        synchronized (lock) {            return rejectBin;        }    }     public List<Card> retainedCards() {        synchronized (lock) {            return List.copyOf(retainedCards);        }    }     public List<Transaction> journal() {        synchronized (lock) {            return List.copyOf(journal.values());        }    }     public Map<String, Long> pendingReversals() {        synchronized (lock) {            return Map.copyOf(pendingReversals);        }    }     // ------------------------------------------------------------ helpers     private DebitResult debitWithOneRetry(String id, Card current, long dollars) {        try {            return bank.debit(id, current.number(), dollars);        } catch (BankUnavailableException first) {            // The same id, so the bank cannot take the money twice.            return bank.debit(id, current.number(), dollars);        }    }     /** Asks for the money back. It leaves pendingReversals only once the bank has taken it. */    private void sendReversal(String id, long dollars) {        try {            bank.reverse(id, dollars);        } catch (RuntimeException e) {            return;        }        synchronized (lock) {            pendingReversals.remove(id);        }    }     /** Anything unexpected before this withdrawal was recorded: stop, and leave it to a person. */    private void markUnknown(String id, Card current, long dollars) {        synchronized (lock) {            if (journal.get(id).status() != TransactionStatus.IN_PROGRESS) {                return;            }            record(new Transaction(id, current.number(), dollars, 0, 0,                    TransactionStatus.UNKNOWN));            if (state == SessionState.DISPENSING) {                endSession();                state = SessionState.OUT_OF_SERVICE;            }        }    }     private void record(Transaction transaction) {        journal.put(transaction.id(), transaction);    }     private String nextTransactionId() {        sequence++;        return String.format("%s-%06d", machineId, sequence);    }     private void endSession() {        card = null;        wrongPins = 0;        state = SessionState.IDLE;    }     private void requireState(SessionState expected) {        if (state != expected) {            throw new IllegalStateException("The machine is " + state + ", not " + expected);        }    }}
Click a class name in the code to open its fileJava · 356 lines · 1232 in the project

demo/Main.java runs a morning at one machine. It is loaded with ten $100, ten $50 and ten $20 notes. Asha draws $60, Ravi tries a few amounts, a stranger gets the PIN wrong three times, a bank reply is lost, and the dispenser jams:

$ java demo.Main
Loaded: 10 × $100 + 10 × $50 + 10 × $20 = $1,700
Greedy plan for $60: none
Fewest-notes plan for $60: 3 × $20

Asha: card in
  PIN 1111: WRONG_PIN
  PIN 2580: ACCEPTED
  $60: DISPENSED (3 × $20). Please take your cash
  Balance now $2,440

Ravi: card in
  PIN 1234: ACCEPTED
  $25: INVALID_AMOUNT. Choose a multiple of $10, up to $1,000
  $30: CANNOT_MAKE_AMOUNT. This machine cannot make $30 right now
  $200: DECLINED. Your bank declined: INSUFFICIENT_FUNDS
  $100: DISPENSED (1 × $100). Please take your cash

A stranger: card in
  PIN 0001: WRONG_PIN
  PIN 0002: WRONG_PIN
  PIN 0003: CARD_RETAINED
  Cards kept by the machine: 1

Asha: card in, and the bank's first reply is lost
  $300: DISPENSED (3 × $100). Please take your cash
  Balance now $2,140, debited once

Asha: card in, the dispenser jams, and the first reversal times out
  $300: SHORT_DISPENSE (1 × $100). Only $100 could be given. $200 will be returned
  Machine: OUT_OF_SERVICE, reversals waiting: {ATM7-000005=200}
  Balance now $1,840

Operator: refill and retry
  Refill 50 × $100: ADDED
  Reversals still waiting: 0
  Asha's balance now $2,040
  Back in service: true, machine IDLE

Cassettes: 54 × $100 + 10 × $50 + 7 × $20 = $6,040
Reject bin: 1 × $100 = $100
Journal:
  ATM7-000001 4111-0001: asked $60, handed out $60, asked back $0, COMPLETED
  ATM7-000002 4111-0002: asked $200, handed out $0, asked back $0, DECLINED
  ATM7-000003 4111-0002: asked $100, handed out $100, asked back $0, COMPLETED
  ATM7-000004 4111-0001: asked $300, handed out $300, asked back $0, COMPLETED
  ATM7-000005 4111-0001: asked $300, handed out $100, asked back $200, SHORT_DISPENSE

Notice five things in the output. Asha's $60 comes out as three $20 notes, which greedy would have refused. Ravi's $30 is refused before the bank is asked, so it uses no transaction id, while his declined $200 uses ATM7-000002. After the lost reply Asha's balance drops by $300 once, not twice. And after the jam she is $200 short until the retry reaches the bank. Finally, the cassettes hold $6,040 and the reject bin $100, which is the $6,700 loaded less the $560 handed out.

Follow-up questions

After the core design, the interviewer adds requirements to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Add a balance check."Atm gains a balance() action allowed in CHOOSING, a state for while the bank answers, and a Bank method that reads the balance.The cash plan, the dispenser, the withdrawal flow.
"Add $10 notes."A new Note value, added to its largest-first list. The search tries one more note size, so it checks more combinations.Atm, Bank, the journal.
"Keep $20 notes for small amounts."A new CashPlanner that prefers larger notes once the $20 cassette runs low.Atm and every other class.
"Deposits."New states for the envelope or the note reader, a credit call on Bank, and a cassette for deposited notes. This is where state classes might start to pay off.The withdrawal flow and the cash plan.
"Cancel the visit if the customer walks away."A timer that calls cancel() after a minute with no key pressed.The withdrawal flow. While the bank or the dispenser works, cancel returns false, so a timer cannot cut a withdrawal in half.
"Take back cash the customer leaves."The dispenser pulls the notes back after a timeout and reports them. DispenseResult gains a retracted part, those notes go to the reject bin, and the machine reverses their value with the same id, as for a short dispense.The order of plan, debit and dispense, and the list of reversals.
"Print a receipt."A Printer interface, called after the visit ends. A failed print must not undo a withdrawal.The order of debit and dispense.
"The bank's reversal is down for hours."Something must call retryPendingReversals on a timer, and the waiting list must survive a restart, so it moves to storage. So does the transaction sequence, or a boot id goes inside every id, or a reused id gets the old answer from the bank.The rule that a reversal is sent until the bank confirms it.
"Daily limit per card."Nothing in the ATM. The bank declines, and the screen shows DAILY_LIMIT_REACHED.The whole ATM.

In most rows the change lands in a new planner, a new interface method, or the bank. The order of plan, debit and dispense stays the same in every row.

What the interviewer looks for

Mid-level

A mid-level candidate shows the main flow: card, PIN, amount, notes. They keep the account at the bank rather than in the machine, refuse amounts that are not multiples of $10, and keep the card after three wrong PINs. Their cash plan makes most amounts correctly.

Senior

A senior candidate shows everything above and gives the order of the steps and the reason for it. They plan the notes before the debit, debit before dispensing, and give back what was not handed out. They know greedy refuses some amounts the machine can make, such as $60, and they put the rule behind an interface. They name the lock, say what it guards, and say why the bank is called without it.

Staff+

A staff candidate leads with the failure cases. They point out that a call to the bank has three outcomes, and use the same transaction id for the retry and the reversal, so neither can move money twice. They separate "short and known" from "unknown", and stop the machine rather than guess. They can say what must be stored so that a reversal survives a restart: the waiting reversals and the transaction sequence, or a reused id gets the old answer.

Common mistakes

  • An Account inside the ATM. The balance belongs to the bank, and a copy in the machine goes stale as soon as anything else changes it.
  • Dispensing before the debit. If the debit is then declined, the cash is already gone.
  • Treating no answer as a no. A lost reply can hide a debit that happened, and the customer pays for cash they never got.
  • A new transaction id for the retry. The bank sees two withdrawals and can take the money twice.
  • Greedy notes without a check. A machine full of $50 and $20 notes refuses $60.
  • Holding a lock across the bank call. The operator's panel and every reader of the state wait behind a slow network.

Summary

  • The account lives at the bank. The ATM asks for money to move, and every answer can fail or be missing.
  • Plan the notes first, then debit, then dispense, so a refusal for missing notes costs nothing.
  • One transaction id covers the debit, its retry and its reversal, so no step can move money twice.
  • What was debited and not handed out goes back, and a reversal waits until the bank confirms it.
  • When nobody knows how much cash came out, the machine stops and a person counts.
  • Greedy notes fail on amounts such as $60, even from full cassettes. A search over at most 121 combinations finds the fewest notes, behind a CashPlanner interface.
  • A private lock guards a few field changes at a time, and the states guard the slow calls.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.