LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 29 OF 42

Design an ATM System: Low-Level Design in Java

An ATM designed and coded end to end: requirements, cards, accounts and the bank, PIN checks with a salted hash and a three-strike lockout, the State pattern for a session, note dispensing as a Chain of Responsibility with greedy planning, withdraw with reversal on a jam, deposits, a transaction log, a race-free balance and the follow-ups, with a full Java 17 solution.

Patterns usedStateChain of responsibility

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 23

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 469 lines, with a small main() demo. Save it as Atm.java, then run javac Atm.java && java Atm.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** An ATM: card and PIN with lockout, a State per session step, notes from a chain of cassettes. */
public class Atm {

    // ---------- money and the model ----------
    /** Money is whole cents in a long (100 cents = 1 unit), so sums are always exact. */
    static String money(long cents) { return String.format("%,d.%02d", cents / 100, cents % 100); }

    static final long MAX_PER_WITHDRAWAL = 20_000_00L;
    static final Duration SESSION_TIMEOUT = Duration.ofSeconds(60);

    enum TxType { BALANCE, WITHDRAW, DEPOSIT, REVERSAL }

    record Card(String number, String accountId) {}

    record Transaction(long id, String accountId, TxType type, long cents, boolean ok, Instant at) {}

    /** The balance is the one hot shared number, so it is an AtomicLong changed with compare-and-set. */
    static final class Account {
        final String id;
        private final AtomicLong balance;

        Account(String id, long openingCents) {
            this.id = id;
            this.balance = new AtomicLong(openingCents);
        }

        long balance() { return balance.get(); }

        /** Never goes below zero, even when an ATM, an app and a card machine debit at the same moment. */
        boolean tryDebit(long cents) {
            while (true) {
                long current = balance.get();
                if (current < cents) return false;
                if (balance.compareAndSet(current, current - cents)) return true;
                // another channel changed the balance in between: read it again
            }
        }

        void credit(long cents) { balance.addAndGet(cents); }
    }

    // ---------- the bank: accounts, PIN strikes and the transaction log ----------
    enum PinCheck { OK, WRONG, BLOCKED, UNKNOWN_CARD }

    static final class Bank {
        static final int MAX_WRONG_PINS = 3;
        private final Map<String, Account> accounts = new ConcurrentHashMap<>();
        private final Map<String, String> pinHashByCard = new ConcurrentHashMap<>();
        private final Map<String, AtomicInteger> wrongPins = new ConcurrentHashMap<>();
        private final Queue<Transaction> log = new ConcurrentLinkedQueue<>();
        private final AtomicLong txSeq = new AtomicLong();
        private final Supplier<Instant> clock;

        Bank(Supplier<Instant> clock) { this.clock = clock; }

        void openAccount(String id, long cents) { accounts.put(id, new Account(id, cents)); }

        void issueCard(Card card, String pin) { pinHashByCard.put(card.number(), hash(card.number(), pin)); }

        /** Only a salted hash is stored. Three wrong tries block the card on every ATM. */
        PinCheck verifyPin(Card card, String pin) {
            String expected = pinHashByCard.get(card.number());
            if (expected == null) return PinCheck.UNKNOWN_CARD;
            AtomicInteger wrong = wrongPins.computeIfAbsent(card.number(), k -> new AtomicInteger());
            if (wrong.get() >= MAX_WRONG_PINS) return PinCheck.BLOCKED;
            byte[] want = expected.getBytes(StandardCharsets.UTF_8);
            byte[] got = hash(card.number(), pin).getBytes(StandardCharsets.UTF_8);
            if (MessageDigest.isEqual(want, got)) { // constant-time compare
                wrong.set(0);
                return PinCheck.OK;
            }
            return wrong.incrementAndGet() >= MAX_WRONG_PINS ? PinCheck.BLOCKED : PinCheck.WRONG;
        }

        int triesLeft(Card card) {
            AtomicInteger wrong = wrongPins.get(card.number());
            return MAX_WRONG_PINS - (wrong == null ? 0 : wrong.get());
        }

        long balance(String accountId) {
            long b = account(accountId).balance();
            record(accountId, TxType.BALANCE, 0, true);
            return b;
        }

        Transaction debit(String accountId, long cents) {
            return record(accountId, TxType.WITHDRAW, cents, account(accountId).tryDebit(cents));
        }

        /** Undo a debit when the cash never left the machine. */
        Transaction reverse(Transaction debit) {
            account(debit.accountId()).credit(debit.cents());
            return record(debit.accountId(), TxType.REVERSAL, debit.cents(), true);
        }

        Transaction deposit(String accountId, long cents) {
            account(accountId).credit(cents);
            return record(accountId, TxType.DEPOSIT, cents, true);
        }

        List<Transaction> history(String accountId) {
            return log.stream().filter(t -> t.accountId().equals(accountId)).toList();
        }

        private Account account(String id) {
            Account a = accounts.get(id);
            if (a == null) throw new IllegalArgumentException("No account " + id);
            return a;
        }

        private Transaction record(String accountId, TxType type, long cents, boolean ok) {
            Transaction t = new Transaction(txSeq.incrementAndGet(), accountId, type, cents, ok, clock.get());
            log.add(t);
            return t;
        }

        static String hash(String salt, String pin) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                byte[] digest = md.digest((salt + ":" + pin).getBytes(StandardCharsets.UTF_8));
                return HexFormat.of().formatHex(digest);
            } catch (NoSuchAlgorithmException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    // ---------- cash: a Chain of Responsibility, largest note first ----------
    /** One cassette. It takes as many of its notes as it can and passes the rest down the chain. */
    static final class NoteHandler {
        final long noteCents;
        private int count;
        private NoteHandler next;

        NoteHandler(long noteCents, int count) {
            this.noteCents = noteCents;
            this.count = count;
        }

        void plan(long remaining, Map<Long, Integer> out) {
            int use = (int) Math.min(remaining / noteCents, count);
            if (use > 0) out.put(noteCents, use);
            long rest = remaining - use * noteCents;
            if (rest > 0 && next != null) next.plan(rest, out);
        }
    }

    /** Used only by its own ATM, under that ATM's lock. */
    static final class CashDispenser {
        private final TreeMap<Long, NoteHandler> cassettes = new TreeMap<>(Collections.reverseOrder());
        private final NoteHandler head;
        private final long step; // every amount must be a multiple of this (gcd of the note values)
        private boolean jamNext; // simulates a motor fault in the demo

        CashDispenser(Map<Long, Integer> load) {
            load.forEach((note, n) -> cassettes.put(note, new NoteHandler(note, n)));
            NoteHandler first = null, prev = null;
            long g = 0;
            for (NoteHandler h : cassettes.values()) {
                if (prev == null) first = h;
                else prev.next = h;
                prev = h;
                g = gcd(g, h.noteCents);
            }
            this.head = first;
            this.step = g;
        }

        static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); }

        long step() { return step; }

        boolean accepts(long note) { return cassettes.containsKey(note); }

        /** Plan only, nothing changes. Empty when these cassettes cannot make the amount. */
        Optional<Map<Long, Integer>> plan(long cents) {
            Map<Long, Integer> out = new LinkedHashMap<>();
            head.plan(cents, out);
            long covered = out.entrySet().stream().mapToLong(e -> e.getKey() * e.getValue()).sum();
            return covered == cents ? Optional.of(out) : Optional.empty();
        }

        /** Commit a plan: the motor counts the notes out. False if the hardware jams. */
        boolean dispense(Map<Long, Integer> plan) {
            if (jamNext) {
                jamNext = false;
                return false;
            }
            plan.forEach((note, n) -> cassettes.get(note).count -= n);
            return true;
        }

        void store(Map<Long, Integer> notes) { notes.forEach((note, n) -> cassettes.get(note).count += n); }

        long totalCents() {
            return cassettes.values().stream().mapToLong(h -> h.noteCents * h.count).sum();
        }

        void jamNextDispense() { jamNext = true; }
    }

    // ---------- the State pattern: one class per step of a session ----------
    interface AtmState {
        default String refuse(String action) {
            return "Cannot " + action + " now (" + getClass().getSimpleName() + ")";
        }

        default String insertCard(Atm atm, Card card) { return refuse("insert a card"); }

        default String enterPin(Atm atm, String pin) { return refuse("enter a PIN"); }

        default String balance(Atm atm) { return refuse("show the balance"); }

        default String withdraw(Atm atm, long cents) { return refuse("withdraw"); }

        default String deposit(Atm atm, Map<Long, Integer> notes) { return refuse("deposit"); }

        default String eject(Atm atm) { return refuse("eject"); }
    }

    static final class Idle implements AtmState {
        @Override
        public String insertCard(Atm atm, Card card) {
            atm.card = card;
            atm.touch();
            atm.state = new CardInserted();
            return "Enter your PIN";
        }
    }

    static final class CardInserted implements AtmState {
        @Override
        public String enterPin(Atm atm, String pin) {
            atm.touch();
            return switch (atm.bank.verifyPin(atm.card, pin)) {
                case OK -> {
                    atm.state = new Authenticated();
                    yield "Welcome";
                }
                case WRONG -> {
                    int left = atm.bank.triesLeft(atm.card);
                    yield "Wrong PIN, " + left + (left == 1 ? " try left" : " tries left");
                }
                case BLOCKED -> {
                    atm.endSession();
                    yield "Card blocked and kept by the machine";
                }
                case UNKNOWN_CARD -> {
                    atm.endSession();
                    yield "Card not recognised, returned";
                }
            };
        }

        @Override
        public String eject(Atm atm) {
            atm.endSession();
            return "Card returned";
        }
    }

    static final class Authenticated implements AtmState {
        @Override
        public String balance(Atm atm) {
            atm.touch();
            return "Balance " + money(atm.bank.balance(atm.card.accountId()));
        }

        @Override
        public String withdraw(Atm atm, long cents) {
            atm.touch();
            if (cents <= 0 || cents % atm.cash.step() != 0)
                return "Amount must be a multiple of " + money(atm.cash.step());
            if (cents > MAX_PER_WITHDRAWAL) return "Limit per withdrawal is " + money(MAX_PER_WITHDRAWAL);
            Optional<Map<Long, Integer>> plan = atm.cash.plan(cents); // cheap, no side effects
            if (plan.isEmpty()) return "This ATM cannot make " + money(cents) + " with its notes";
            Transaction debit = atm.bank.debit(atm.card.accountId(), cents);
            if (!debit.ok()) return "Insufficient funds";
            if (!atm.cash.dispense(plan.get())) {
                atm.bank.reverse(debit); // the customer never pays for cash they did not get
                return "Could not dispense, " + money(cents) + " reversed";
            }
            return "Take your cash: " + notes(plan.get());
        }

        @Override
        public String deposit(Atm atm, Map<Long, Integer> notes) {
            atm.touch();
            long total = 0;
            for (Map.Entry<Long, Integer> e : notes.entrySet()) {
                if (!atm.cash.accepts(e.getKey())) return "Note not accepted: " + money(e.getKey());
                total += e.getKey() * e.getValue();
            }
            atm.cash.store(notes);
            atm.bank.deposit(atm.card.accountId(), total);
            return "Deposited " + money(total);
        }

        @Override
        public String eject(Atm atm) {
            atm.endSession();
            return "Card returned";
        }
    }

    static final class OutOfService implements AtmState {
        @Override
        public String insertCard(Atm atm, Card card) { return "Out of service, card returned"; }
    }

    static String notes(Map<Long, Integer> plan) {
        StringBuilder sb = new StringBuilder();
        plan.forEach((note, n) -> sb.append(note / 100).append('x').append(n).append(' '));
        return sb.toString().trim();
    }

    // ---------- the machine: one customer at a time ----------
    private final String id;
    private final Bank bank;
    private final CashDispenser cash;
    private final Supplier<Instant> clock;
    private AtmState state = new Idle();
    private Card card;
    private Instant lastActivity;

    Atm(String id, Bank bank, CashDispenser cash, Supplier<Instant> clock) {
        this.id = id;
        this.bank = bank;
        this.cash = cash;
        this.clock = clock;
    }

    synchronized String insertCard(Card c) { return state.insertCard(this, c); }

    synchronized String enterPin(String pin) { return state.enterPin(this, pin); }

    synchronized String balance() { return state.balance(this); }

    synchronized String withdraw(long cents) { return state.withdraw(this, cents); }

    synchronized String deposit(Map<Long, Integer> notes) { return state.deposit(this, notes); }

    synchronized String eject() { return state.eject(this); }

    /** Called by a timer: ends a session nobody has touched for a minute. */
    synchronized String tick() {
        if (card != null && Duration.between(lastActivity, clock.get()).compareTo(SESSION_TIMEOUT) > 0) {
            endSession();
            return "Session timed out, card returned";
        }
        return "Still active";
    }

    synchronized void jamNextDispense() { cash.jamNextDispense(); }

    private void touch() { lastActivity = clock.get(); }

    private void endSession() {
        card = null;
        state = cash.totalCents() == 0 ? new OutOfService() : new Idle();
    }

    String stateName() { return state.getClass().getSimpleName(); }

    // ---------- demo ----------
    static void step(Atm atm, String action, String result) {
        System.out.printf("%-16s -> %-44s [%s]%n", action, result, atm.stateName());
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-03-01T10:00:00Z"));
        Bank bank = new Bank(now::get);
        bank.openAccount("ACC-1", 12_000_00L);
        bank.openAccount("ACC-2", 5_000_00L);
        Card mine = new Card("4000-0001", "ACC-1");
        Card stolen = new Card("4000-0002", "ACC-2");
        bank.issueCard(mine, "4321");
        bank.issueCard(stolen, "9876");

        Map<Long, Integer> load = new LinkedHashMap<>();
        load.put(2000_00L, 5);
        load.put(500_00L, 10);
        load.put(200_00L, 10);
        Atm atm = new Atm("ATM-7", bank, new CashDispenser(load), now::get);
        System.out.println(atm.id + " loaded with " + money(atm.cash.totalCents()));

        step(atm, "withdraw 1,000", atm.withdraw(1_000_00L));
        step(atm, "insert card", atm.insertCard(mine));
        step(atm, "enter PIN 1111", atm.enterPin("1111"));
        step(atm, "enter PIN 4321", atm.enterPin("4321"));
        step(atm, "balance", atm.balance());
        step(atm, "withdraw 3,700", atm.withdraw(3_700_00L));
        step(atm, "withdraw 300", atm.withdraw(300_00L));
        step(atm, "withdraw 50", atm.withdraw(50_00L));
        atm.jamNextDispense();
        step(atm, "withdraw (jam)", atm.withdraw(1_000_00L));
        step(atm, "deposit 4x500", atm.deposit(Map.of(500_00L, 4)));
        String balance = atm.balance();
        step(atm, "balance", balance);
        if (!balance.equals("Balance 10,300.00")) throw new AssertionError(balance);
        step(atm, "eject", atm.eject());

        // A forgotten session: move the fake clock instead of sleeping.
        step(atm, "insert card", atm.insertCard(mine));
        step(atm, "enter PIN 4321", atm.enterPin("4321"));
        now.set(now.get().plusSeconds(90));
        step(atm, "tick +90s", atm.tick());

        // A thief guesses: the third wrong PIN blocks the card at the bank, for every ATM.
        step(atm, "insert stolen", atm.insertCard(stolen));
        for (String guess : List.of("0000", "1234", "1111"))
            step(atm, "enter PIN " + guess, atm.enterPin(guess));
        step(atm, "insert stolen", atm.insertCard(stolen));
        step(atm, "enter PIN 9876", atm.enterPin("9876"));

        System.out.println("History of ACC-1:");
        for (Transaction t : bank.history("ACC-1"))
            System.out.printf("  #%d %-9s %10s %s%n", t.id(), t.type(), money(t.cents()),
                    t.ok() ? "ok" : "declined");

        // Eight channels (ATMs, an app, card machines) take 2,000 each from a balance of 10,000.
        bank.openAccount("JOINT", 10_000_00L);
        AtomicInteger ok = new AtomicInteger(), declined = new AtomicInteger();
        CountDownLatch start = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            pool.submit(() -> {
                try {
                    start.await();
                    if (bank.debit("JOINT", 2_000_00L).ok()) ok.incrementAndGet();
                    else declined.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        start.countDown();
        pool.shutdown();
        if (!pool.awaitTermination(5, TimeUnit.SECONDS)) throw new AssertionError("race did not finish");
        long left = bank.accounts.get("JOINT").balance();
        System.out.println("Race: " + ok.get() + " ok, " + declined.get() + " declined, balance "
                + money(left));
        if (ok.get() != 5 || left != 0) throw new AssertionError("balance went wrong");
    }
}

Notes

Requirements

Fix the scope. A customer inserts a card and enters a PIN. Three wrong PINs block the card. Once signed in, they can check the balance, withdraw cash, deposit notes, and eject the card. Every transaction is logged, and a session left alone for too long ends by itself. Say out loud what is out of scope: real bank networks, chip cryptography and printed receipts.

Ask the questions that change the code. Is the lockout per machine or per card? Per card, kept at the bank, so a thief cannot just walk to the next ATM. If the notes cannot make the amount, refuse before touching the account. If the cash jams after the account was debited, reverse the debit. And one account can be used by the ATM, a phone app and a card machine at the same time.

Requirements
  • insert card, enter PIN
  • three wrong PINs block the card
  • check balance
  • withdraw cash in fixed notes
  • deposit notes
  • eject card, end the session
  • log every transaction
  • idle session times out
  • out of scope: real network,
  • card chip crypto, receipts
Clarify first
  • lockout per ATM or per card?
  • per card, at the bank
  • which notes?
  • 2000, 500 and 200
  • amount the notes cannot make?
  • refuse before any debit
  • cash jams after the debit?
  • reverse the debit
  • one account, many channels?
  • yes: ATM, app, card swipe
  • limit per withdrawal: 20,000

Entities

The entities. A card is just a number and the account it points to. The bank owns the accounts, checks PINs and writes the transaction log; it is the source of truth that every channel shares. The ATM is a thin client with its own cash dispenser and one session at a time. Keeping the money rules in the bank, and not in the machine, is the key modelling choice here.

Class diagram

Turn them into types. A card and a transaction never change after creation, so they are Java records. The transaction type is an enum. Money is a long number of cents, never a double, so adding and subtracting never drifts. The only hot mutable number in the whole design is the account balance, which is an atomic long. One mutable thing makes the thread safety story short.

Value types
record Card(String number, String accountId)
record Transaction(long id, String account,
    TxType type, long cents, boolean ok,
    Instant at)
enum TxType { BALANCE, WITHDRAW,
    DEPOSIT, REVERSAL }

class Account {
  final String id;
  AtomicLong balance;  // cents
}

PIN and lockout

The PIN check. The bank never stores the PIN itself, only a salted hash, and compares hashes with a constant-time equals so timing reveals nothing. Wrong attempts are counted per card in an atomic integer at the bank. The third strike returns blocked, and every later try is refused, on every ATM. A correct PIN resets the count. In a real bank this runs inside secure hardware, so mention that.

Bank.verifyPin()
expected = pinHashByCard.get(card)
if (expected == null) return UNKNOWN
wrong = strikes(card)
if (wrong.get() >= 3) return BLOCKED
if (isEqual(expected, hash(card, pin))) {
  wrong.set(0); return OK;
}
return wrong.incrementAndGet() >= 3
    ? BLOCKED : WRONG;

Why not if statements

Why not flags and if statements? Because every button would check every flag: is the machine in service, is there a card, was the PIN right. Withdraw, deposit, balance and eject all repeat the same chain. Add one new step, such as asking for a one-time code, and you edit every method. The rules are grouped by button, when they should be grouped by the step the session is in.

The naive version
String withdraw(long cents) {
  if (outOfService) ...
  else if (card == null) ...
  else if (!pinOk) ...
  else ...
}
// balance, deposit, enterPin and eject
// repeat the same chain of flags

State pattern

The State pattern. One interface lists every button. Each step of a session is a class: Idle, CardInserted, Authenticated and OutOfService. The ATM holds the current state and passes every button to it. A neat Java trick: default methods in the interface politely refuse, so each state only overrides the few buttons that make sense for it. Idle only overrides insert card.

Write the transition table before the classes. Idle plus a card moves to CardInserted. The right PIN moves on to Authenticated; a wrong one stays and says how many tries are left; the third wrong one keeps the card and goes back to Idle. Eject or a timeout ends the session. If the cassettes are empty when a session ends, the machine goes out of service until an operator reloads it.

AtmState
interface AtmState {
  default String insertCard(Atm a, Card c)
    { return refuse("insert card"); }
  default String enterPin(Atm a, String p)
    { return refuse("enter PIN"); }
  ... balance, withdraw, deposit, eject
}

synchronized String withdraw(long c) {
  return state.withdraw(this, c);
}
Transition table
  • Idle + card -> CardInserted
  • CardInserted + right PIN
  • -> Authenticated
  • CardInserted + wrong PIN -> stay
  • CardInserted + third wrong
  • -> keep card, Idle
  • Authenticated + eject -> Idle
  • any + timeout -> Idle
  • session ends, no cash left
  • -> OutOfService
  • OutOfService + reload -> Idle

Flow: sign in

Walk the sign-in. The customer types a wrong PIN. The machine passes it to the CardInserted state, which asks the bank. The bank answers wrong, with two tries left, and the state stays where it is. The second attempt is right, so the state switches the machine to Authenticated. Notice that the ATM never decides whether a PIN is right; it only reacts to the bank's answer.

Chain of notes

Cash uses the Chain of Responsibility pattern. Each cassette is a handler for one note value, linked from the largest note to the smallest. A handler takes as many of its notes as the amount and its count allow, then passes what is left to the next handler. Three thousand seven hundred becomes one two-thousand note, three five-hundreds and one two-hundred. Adding a new note value means adding one handler to the chain.

Planning never changes the cassettes; it only returns a map of notes. If the plan does not cover the full amount, the ATM refuses before touching the account. Committing subtracts the counts later. Be honest about one limit: greedy can fail when counts run low. Six hundred with one five-hundred and three two-hundreds fails greedily, though three two-hundreds would work. A small backtracking or dynamic programming search fixes it.

NoteHandler.plan()
void plan(long rest, Map<Long,Integer> out){
  int use = (int) min(rest / note, count);
  if (use > 0) out.put(note, use);
  long left = rest - use * note;
  if (left > 0 && next != null)
    next.plan(left, out);
}

3,700: 2000 x1, 500 x3, 200 x1
Plan, then commit
  • plan() changes nothing
  • covered != amount: refuse
  • 300 with 2000, 500, 200:
  • impossible, refuse early
  • dispense(plan) subtracts counts
  • greedy limit: 600 with one 500
  • and three 200s: greedy takes
  • 500, stuck with 100 left
  • fix: backtrack one note, or DP

Flow: withdraw

The withdraw flow, in the order that keeps everyone safe. Validate the amount. Plan the notes, which is cheap and changes nothing. Then ask the bank to debit the account; if funds are short, stop. Then dispense. If the motor jams, the bank reverses the debit and logs a reversal, so the customer is never charged for cash they did not get. The order matters: cheap checks first, money last.

Authenticated.withdraw()
check: multiple of 100, under limit
plan = cash.plan(cents)
if (plan.isEmpty()) return "cannot make"
tx = bank.debit(account, cents)
if (!tx.ok()) return "insufficient funds"
if (!cash.dispense(plan.get())) {
  bank.reverse(tx);
  return "not dispensed, reversed";
}
return "take your cash"

Flow: deposit

Deposits run the other way. The machine counts the notes and rejects any value it does not know. The notes go into the matching cassettes, which is how recycling ATMs work, and the bank credits the account and logs a deposit. A real bank might hold the deposit as pending until a person checks the notes; that is a nice extension to mention, a new status on the transaction.

Transaction log

The transaction log. Every attempt is recorded by the bank with an id from an atomic counter, the type, the amount, whether it worked, and the time from an injected clock. Failed withdrawals are logged too, because fraud checks and customer disputes need them. A jam shows up as a withdrawal followed by a reversal, so the history explains itself. The log is a concurrent queue, safe for many channels to append.

Bank.record()
Transaction t = new Transaction(
    txSeq.incrementAndGet(), account,
    type, cents, ok, clock.get());
log.add(t);   // ConcurrentLinkedQueue

history(account): filter the log
declined debits are logged too:
  fraud checks and disputes need them

Concurrency

The concurrency question. The ATM, a phone app and a card machine all debit the same account at the same moment. A check-then-subtract would let two of them spend the same money. Instead, the debit reads the balance, checks it is enough, and swaps in the new value with compare-and-set. If another channel changed the balance in between, the swap fails and the loop reads again. The balance can never go below zero.

Give every shared field a safe home. The balance is an atomic long with a compare-and-set loop. PIN strikes are atomic integers per card at the bank. Accounts and PIN hashes sit in concurrent maps, and the log is a concurrent queue. Inside one ATM there is a single customer, so its public methods are simply synchronized, and the cassettes are only touched under that lock. Records need no locking at all.

Account.tryDebit()
while (true) {
  long cur = balance.get();
  if (cur < cents) return false;
  if (balance.compareAndSet(cur,
                            cur - cents))
    return true;
  // someone else changed it: retry
}
Thread safety checklist
  • balance: AtomicLong + CAS loop
  • PIN strikes: AtomicInteger
  • per card, at the bank
  • accounts, hashes:
  • ConcurrentHashMap
  • log: ConcurrentLinkedQueue
  • one ATM: synchronized methods,
  • cassettes used only under it
  • records: immutable, share freely

Session timeout

A forgotten session is a real risk, so a timer calls tick on the ATM. Every button press records the last activity time, and if more than sixty seconds have passed, the session ends and the card comes back. The time comes from an injected clock, a supplier of instants. In the demo we move a fake clock forward ninety seconds instead of sleeping, which keeps the test fast and never flaky.

Atm.tick()
synchronized String tick() {
  if (card != null && Duration.between(
        lastActivity, clock.get())
        .compareTo(TIMEOUT) > 0) {
    endSession();
    return "timed out, card returned";
  }
  return "ok";
}

Extensibility

Interviewers like to add rules. A daily withdrawal limit becomes a small list of withdraw rules checked before the debit. A one-time code after the PIN is one more state between CardInserted and Authenticated. A new note value is one more handler in the chain. Pending deposits are a new status on the transaction. And other banks' cards make the bank an interface with one implementation per card network.

Extension points
  • daily limit: a WithdrawRule
  • chain checked before debit
  • one-time code: a new
  • VerifyingOtp state
  • new note value: one more
  • NoteHandler in the chain
  • pending deposits: a status
  • on Transaction
  • many banks: Bank becomes an
  • interface, one per network

Testing

The full code is below the player. The demo signs in after one wrong PIN, withdraws three thousand seven hundred in mixed notes, is refused an amount the notes cannot make, survives a simulated jam with a reversal, deposits, times out a session with the fake clock, and blocks a card on the third wrong PIN. Then eight threads race to take two thousand each from ten thousand. Exactly five succeed, every time.

Run it
enter PIN 1111 -> Wrong PIN, 2 tries left
withdraw 3,700 -> 2000x1 500x3 200x1
withdraw 300   -> cannot make 300.00
withdraw (jam)  -> 1,000.00 reversed
deposit 4x500  -> Deposited 2,000.00
balance        -> 10,300.00
tick +90s      -> timed out
third wrong PIN -> card blocked
race: 8 debits of 2,000 on 10,000
  -> 5 ok, 3 declined, balance 0

Follow-ups

Expect these follow-ups. Why keep the lockout at the bank? So a blocked card is blocked on every machine. Debit first or dispense first? Plan, debit, dispense, and reverse on failure. What if the ATM loses power mid-dispense? It writes a journal entry before dispensing and reconciles with the cassette counts on boot. Would a synchronized account work? Yes; compare-and-set just avoids threads waiting on a lock.

Follow-ups to expect
  • why lockout at the bank?
  • so every ATM sees it
  • debit first or dispense first?
  • plan, debit, dispense, reverse
  • greedy fails with low counts?
  • backtrack or DP
  • ATM loses power mid-dispense?
  • journal, reconcile on boot
  • why not synchronized Account?
  • fine too; CAS avoids waiting

Say it like this

Here is the short version to say out loud. The bank owns the accounts, the PIN strikes and the transaction log. The ATM passes every button to its current state. Cash is a chain of note handlers that plan before anything moves. A withdrawal plans the notes, debits the account with compare-and-set, dispenses, and reverses the debit if the cash jams.

In the interview
  • "The bank owns accounts, PIN
  • strikes and the log. The ATM
  • passes each button to its
  • State. Cash is a chain of note
  • handlers that plan first. A
  • withdrawal plans, debits with
  • compare-and-set, dispenses,
  • and reverses on a jam."

Interview questions

Why use the State pattern for an ATM session?

The same buttons mean different things at different steps: withdraw before the PIN must be refused, after it must work. One class per step keeps each step’s rules together, the ATM just delegates, and a new step such as an OTP check is a new class rather than edits to every method.

How do you lock a card after three wrong PINs?

Count wrong attempts per card at the bank in an AtomicInteger. The third strike returns BLOCKED and every later attempt is refused; a correct PIN resets the count. Keeping it at the bank means a thief cannot simply try the next ATM.

How should the PIN be stored and checked?

Never store the PIN itself. Store a salted hash and compare with a constant-time check such as MessageDigest.isEqual. In real banking the check runs inside a hardware security module and the PIN travels encrypted from the keypad.

How does the ATM decide which notes to dispense?

A Chain of Responsibility of note handlers from the largest note down: each takes as many notes as the amount and its cassette count allow and passes the rest on. If the chain cannot cover the full amount, the withdrawal is refused before the account is touched.

When does greedy note selection fail, and how would you fix it?

With limited counts, greedy can take a big note that leaves a remainder nothing can make, for example 600 from one 500 and three 200s. Backtracking one note at a time, or a small dynamic programming search over the counts, finds a valid mix when one exists.

What order of steps makes a withdrawal safe?

Validate, plan the notes (no side effects), debit the account atomically, then dispense. If dispensing fails, reverse the debit and log the reversal, so the customer is never charged for cash they did not receive.

How do you keep the balance correct when the ATM and a mobile app debit at the same time?

Make the debit atomic. A compare-and-set loop on an AtomicLong reads the balance, checks it is enough and swaps in the new value only if nobody changed it meanwhile; otherwise it retries. A lock on the account works too, and a database would use a conditional update.

Why is money stored as a long number of cents?

Floating point cannot represent most decimal amounts exactly, so sums drift over many transactions. Whole cents in a long are exact; format them as currency only for display.

What happens if the ATM loses power while dispensing?

Before dispensing, write a journal entry with the planned notes and the debit id. On restart, compare the journal with the cassette counts and either confirm the withdrawal or reverse the debit, so the bank and the machine agree again.