On this page

Design a Vending Machine

The vending machine is the textbook State pattern problem. The machine transitions between well-defined states (idle, selecting, payment, dispensing), and behavior changes entirely depending on the current state. This problem tests your ability to model state machines cleanly.

It also tests two things candidates often miss: money (integer cents, real coins, change the machine can actually make) and concurrency (a keypad, a mobile app and a card reader competing for the same last item). This page follows the LLD interview framework, develops the State pattern in depth, and keeps the original walkthrough code with corrections marked.

Requirements & Use Cases

Clarifying questions

QuestionTypical answerWhy it matters
Coins, notes, cards?Coins now, cards laterCoins mean change-making. Cards are Extension A
Which coins?5¢, 10¢, 25¢, $1Denominations are data, so the change planner can't assume a coin system
Must the machine give change? From what?Yes, from the coins it holds, including ones just insertedChange can be impossible, and the machine must then refund
Select first or pay first?Select firstFixes the state order
Can the customer change their mind?Before paying, yes. After, only by cancellingThat's the difference between Selected and Paying
Any other way to buy?A mobile app may buy remotelyTwo channels compete for stock, so stock must be taken atomically
Operator functions?Restock, collect cashMaintenance mode, Extension B

Functional Requirements

  1. Machine holds an inventory of products with prices and quantities
  2. User selects a product
  3. User inserts coins/bills (supports multiple denominations)
  4. Machine validates sufficient payment
  5. Machine dispenses product and returns change
  6. Machine tracks inventory; out-of-stock products cannot be selected
  7. User can cancel at any point and get a refund

Non-Functional Requirements

  • State transitions must be deterministic and well-defined
  • Change calculation should return fewest coins possible (greedy)
  • Money is held in integer cents, never floating point
  • A purchase never takes money without delivering an item or a full refund

Correction (2026-11-10)

The walkthrough code doesn't calculate change in coins at all. It returns a number, so it can't tell whether change is possible. "Greedy gives the fewest coins" is also only true for canonical coin systems with an unlimited supply. A real machine has a limited supply, and then greedy fails even with US coins: 30¢ from one quarter and three dimes. Greedy takes the quarter, then needs a nickel it doesn't have, while three dimes work. The complete code plans change with dynamic programming over the coins actually held.

- Thread-safe for concurrent button presses (hardware interrupts)

State Machine

stateDiagram-v2
    [*] --> Idle

    Idle --> Selecting : selectProduct()
    Idle --> Idle : insertMoney() [rejected]

    Selecting --> Payment : confirmSelection()
    Selecting --> Idle : cancel()
    Selecting --> Selecting : selectProduct() [change selection]

    Payment --> Dispensing : insertMoney() [sufficient]
    Payment --> Payment : insertMoney() [insufficient]
    Payment --> Idle : cancel() [refund]

    Dispensing --> Idle : dispense()

    note right of Idle : Waiting for user
    note right of Payment : Accumulating coins
    note right of Dispensing : Product drops

Correction (2026-11-10)

This diagram doesn't match the code. There's no confirmSelection() method: in the code, insertMoney() in Selecting moves to Payment or straight to Dispensing, and that Selecting --> Dispensing transition, when the first payment is enough, is missing from the diagram. Dispensing --> Idle happens in dispense(), as shown. The corrected lifecycle, for the complete code, is in Key flows.

Use Cases

ActorUse Case
CustomerSelect a product
CustomerInsert money
CustomerCancel and get refund
SystemDispense product
SystemReturn change
AdminRestock products
AdminCollect cash

Core entities and relationships

EntityResponsibilityNotes
VendingMachineThe context of the State pattern. Holds the session (selection, coins inserted, coin tray) and delegates every event to the current stateThe only public API
State and its subclassesWhat each event means right now: Idle, Selected, Paying, DispensingEach one overrides only the events it accepts
InventoryProducts and stock per slot. tryTake is the atomic check-and-decrementShared by every purchase channel
CoinBoxThe coins the machine holds, and the change plannerChange is planned before anything is committed
Product, CoinImmutable values, priced in cents

The machine composes its states and aggregates the Inventory and CoinBox, which are passed in so tests can preload them and a mobile app can share the inventory. States hold no data. The purchase lives on the machine, so a transition just swaps one object for another.

One physical detail shapes the design: refunds and change go to a coin tray that the customer empties, as on real hardware. That makes refunds state you can assert on.

Class Diagram

classDiagram
    class VendingMachine {
        -inventory: Inventory
        -currentState: State
        -selectedProduct: Product?
        -insertedAmount: number
        +selectProduct(code: string): void
        +insertMoney(amount: number): void
        +cancel(): number
        +dispense(): DispenseResult
        +setState(state: State): void
    }

    class State {
        <<interface>>
        +selectProduct(machine: VendingMachine, code: string): void
        +insertMoney(machine: VendingMachine, amount: number): void
        +cancel(machine: VendingMachine): number
        +dispense(machine: VendingMachine): DispenseResult?
    }

    class IdleState {
        +selectProduct(): void
        +insertMoney(): void
        +cancel(): number
        +dispense(): DispenseResult?
    }

    class SelectingState {
        +selectProduct(): void
        +insertMoney(): void
        +cancel(): number
        +dispense(): DispenseResult?
    }

    class PaymentState {
        +selectProduct(): void
        +insertMoney(): void
        +cancel(): number
        +dispense(): DispenseResult?
    }

    class DispensingState {
        +selectProduct(): void
        +insertMoney(): void
        +cancel(): number
        +dispense(): DispenseResult?
    }

    class Inventory {
        -items: Map~string, ItemSlot~
        +addItem(product: Product, quantity: int): void
        +isAvailable(code: string): boolean
        +getProduct(code: string): Product?
        +decrementStock(code: string): void
    }

    class Product {
        -code: string
        -name: string
        -price: number
    }

    class ItemSlot {
        -product: Product
        -quantity: int
    }

    class DispenseResult {
        -product: Product
        -change: number
    }

    VendingMachine --> State
    VendingMachine *-- Inventory
    State <|.. IdleState
    State <|.. SelectingState
    State <|.. PaymentState
    State <|.. DispensingState
    Inventory *-- ItemSlot
    ItemSlot --> Product

Class diagram for the complete code

The diagram above matches the walkthrough code. The complete code adds the coin box and the tray, and gives the states a base class with default rejections:

classDiagram
    class VendingMachine {
        -State current
        -Product selected
        -List~Coin~ inserted
        -List~Coin~ tray
        +select(code) void
        +insert(coin) void
        +cancel() void
        +dispense() Product
        +collectCoins() List~Coin~
    }
    class State {
        <<abstract>>
        +select(m, code) void
        +insert(m, coin) void
        +cancel(m) void
        +dispense(m) Product
    }
    class Idle
    class Selected
    class Paying
    class Dispensing
    class Inventory {
        +restock(product, quantity) void
        +quantity(code) int
        +tryTake(code) bool
    }
    class CoinBox {
        +add(coins) void
        +remove(coins) void
        +planChange(amount, extra) List~Coin~
    }
    class Product {
        +String code
        +String name
        +int priceCents
    }
    VendingMachine *-- State
    VendingMachine o-- Inventory
    VendingMachine o-- CoinBox
    State <|-- Idle
    State <|-- Selected
    State <|-- Paying
    State <|-- Dispensing
    Inventory --> Product

Key flows

The lifecycle, as the complete code implements it

stateDiagram-v2
    [*] --> Idle
    Idle --> Selected: select, in stock
    Selected --> Selected: select another product
    Selected --> Idle: cancel, or a first coin that is enough but cannot be served
    Selected --> Paying: insert a coin, not enough yet
    Selected --> Dispensing: insert a coin, enough and change possible
    Paying --> Paying: insert a coin, not enough yet
    Paying --> Dispensing: enough money, change planned, item taken
    Paying --> Idle: cancel, all coins to the tray
    Paying --> Idle: change impossible or sold out, all coins to the tray
    Dispensing --> Idle: dispense, product released

Selected to Dispensing happens when the first coin is enough, for example a dollar for a 50¢ item. Every other event in every state is rejected and changes nothing, which is what the base class's defaults guarantee.

A purchase with change

sequenceDiagram
    participant C as Customer
    participant M as VendingMachine
    participant S as Current state
    participant B as CoinBox
    participant I as Inventory
    C->>M: select B2, chips at 50 cents
    M->>S: Idle handles select
    S->>M: choose B2, then switch to Selected
    C->>M: insert a dollar
    M->>S: Selected handles insert
    S->>M: switch to Paying, accept the coin
    M->>B: plan 50 cents of change, counting the new dollar
    B-->>M: two quarters
    M->>I: tryTake B2
    I-->>M: true
    M->>M: commit coins, change to the tray, switch to Dispensing
    C->>M: dispense
    M-->>C: chips, and the tray holds two quarters

The order inside accept is the important part: plan, reserve, then commit. Nothing is written to the coin box until both the change plan and the stock reservation have succeeded. If either fails, the customer's coins go back to the tray and nothing else has changed.

When the machine can't make change

sequenceDiagram
    participant C as Customer
    participant M as VendingMachine
    participant B as CoinBox
    C->>M: select A1, cola at 125 cents
    C->>M: insert a dollar
    M-->>C: insert 25 cents more
    C->>M: insert a dollar
    M->>B: plan 75 cents from two dimes, a nickel and two dollars
    B-->>M: impossible
    M->>M: both dollars to the tray, back to Idle
    M-->>C: display says it can't make change

Design Patterns Used

PatternWhereWhy
StateState interface with Idle, Selecting, Payment, Dispensing implementationsEach state defines different behavior for the same actions; eliminates complex if/else chains
CompositionVendingMachine owns Inventory, delegates to StateClean separation between machine logic and state behavior
RepositoryInventory manages product storageEncapsulates product lookup and stock management

Why State Pattern Over If/Else

Without the State pattern, the vending machine would have a massive switch statement in every method:

// Without State pattern — messy and hard to extend
insertMoney(amount: number): void {
  if (this.state === 'IDLE') throw new Error('Select product first');
  else if (this.state === 'SELECTING') { /* ... */ }
  else if (this.state === 'PAYMENT') { /* ... */ }
  else if (this.state === 'DISPENSING') throw new Error('Wait');
}

With the State pattern, each state is a self-contained class. Adding a new state (e.g., "maintenance mode") means adding one new class without touching existing states.

Correction (2026-11-10)

Two claims above need tightening. Adding a state such as maintenance mode isn't "one new class without touching existing states". Some existing state has to transition into it (here Idle), and if it brings new events, the State interface grows, so every state must implement them. The complete code softens this with a base class whose methods reject by default, so a new event costs one default method plus overrides only where it's accepted. Extension B shows the real diff. And Inventory isn't a Repository in the usual sense, which is an abstraction over persistence. It's a plain in-memory domain object.

Why the State pattern here, and what it costs

The State pattern fits when the same event means different things depending on the mode, and there are several modes and several events. That's exactly this problem: four states times four events gives sixteen cells, and most of them are "reject". With the pattern, each state's class is its row of that table:

EventIdleSelectedPayingDispensing
selectchoose, go to Selectedchange selectionrejectreject
insertrejectaccept, go to Payingacceptreject
cancelnothing to dogo to Idlerefund, go to Idlereject
dispenserejectrejectrejectrelease, go to Idle

Alternatives you should be able to argue against:

AlternativeWhy not here
An enum plus switch in every methodEach method holds all four states, and adding a state means editing every method. The original's "Why State Pattern Over If/Else" box shows it. Fine for two or three states, not for this
A transition table, Map<(State, Event), Handler>Good when transitions are data, such as rules configured per machine model. Here the behaviour per cell is code, and a table of lambdas is the State pattern written sideways
Boolean flags such as hasSelection and isPaidFour booleans allow sixteen combinations, most of them nonsense. Explicit states make illegal combinations unrepresentable

The cost to name: the states need access to the machine's internals (choose, accept, refund), so those methods are package-private in Java and documented as "used by the states" in Python and TypeScript. Keeping the public API to five methods is what stops callers from skipping the state machine.

Implementation

Complete runnable code

Each tab is one complete file. Money is integer cents throughout. Change uses a bounded coin-change planner that also counts the coins the customer just inserted, so a customer's own quarter can come back as change. The Java main runs the scenarios from the flows above and a 100-thread race for the last items. The Python demo runs the same purchases. The TypeScript passes tsc --strict, and we ran the same scenarios against it with node:test.

// file: VendingMachine.java
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

enum Coin {
    NICKEL(5), DIME(10), QUARTER(25), DOLLAR(100);
    final int cents;
    Coin(int cents) { this.cents = cents; }
}

record Product(String code, String name, int priceCents) {}

/** Stock per slot. Shared by every purchase channel, so taking an item is atomic. */
final class Inventory {
    private final Map<String, Product> products = new ConcurrentHashMap<>();
    private final Map<String, AtomicInteger> stock = new ConcurrentHashMap<>();

    void restock(Product p, int quantity) {
        products.put(p.code(), p);
        stock.computeIfAbsent(p.code(), c -> new AtomicInteger()).addAndGet(quantity);
    }
    Product product(String code) {
        Product p = products.get(code);
        if (p == null) throw new IllegalArgumentException("no product " + code);
        return p;
    }
    int quantity(String code) { return stock.getOrDefault(code, new AtomicInteger()).get(); }

    /** Check-and-decrement in one step: two buyers can never both get the last item. */
    boolean tryTake(String code) {
        AtomicInteger q = stock.get(code);
        while (q != null) {
            int now = q.get();
            if (now == 0) return false;
            if (q.compareAndSet(now, now - 1)) return true;
        }
        return false;
    }
}

/** The coins the machine holds, and the change-making algorithm. */
final class CoinBox {
    private final EnumMap<Coin, Integer> coins = new EnumMap<>(Coin.class);

    void add(Collection<Coin> in) { for (Coin c : in) coins.merge(c, 1, Integer::sum); }
    void remove(Collection<Coin> out) { for (Coin c : out) coins.merge(c, -1, Integer::sum); }
    int count(Coin c) { return coins.getOrDefault(c, 0); }

    /** Fewest coins summing to `amount` using what's in the box plus `extra`, or null.
        Bounded coin change by dynamic programming: greedy fails with limited coins. */
    List<Coin> planChange(int amount, Collection<Coin> extra) {
        EnumMap<Coin, Integer> have = new EnumMap<>(coins);
        for (Coin c : extra) have.merge(c, 1, Integer::sum);
        final int INF = Integer.MAX_VALUE / 2;
        int[] best = new int[amount + 1];
        Arrays.fill(best, INF);
        best[0] = 0;
        Coin[] types = Coin.values();
        int[][] used = new int[types.length][amount + 1];      // coins of type i used to reach a
        for (int i = 0; i < types.length; i++) {
            int value = types[i].cents, limit = have.getOrDefault(types[i], 0);
            int[] next = best.clone();
            for (int a = 0; a <= amount; a++) {
                if (best[a] >= INF) continue;
                for (int k = 1; k <= limit && a + k * value <= amount; k++) {
                    int t = a + k * value;
                    if (best[a] + k < next[t]) { next[t] = best[a] + k; used[i][t] = k; }
                }
            }
            best = next;
        }
        if (best[amount] >= INF) return null;
        List<Coin> out = new ArrayList<>();
        for (int i = types.length - 1, a = amount; i >= 0; i--) {
            for (int k = 0; k < used[i][a]; k++) out.add(types[i]);
            a -= used[i][a] * types[i].cents;
        }
        return out;
    }
}

/** State pattern: every event defaults to "not now", so each state overrides only what it accepts. */
abstract class State {
    abstract String name();
    void select(VendingMachine m, String code) { throw reject("select"); }
    void insert(VendingMachine m, Coin coin) { throw reject("take coins"); }
    void cancel(VendingMachine m) { throw reject("cancel"); }
    Product dispense(VendingMachine m) { throw reject("dispense"); }
    private IllegalStateException reject(String what) {
        return new IllegalStateException("can't " + what + " while " + name());
    }
}

final class IdleState extends State {
    String name() { return "IDLE"; }
    void select(VendingMachine m, String code) { m.choose(code); m.setState(new SelectedState()); }
    void cancel(VendingMachine m) { }                          // nothing to give back
}

final class SelectedState extends State {                       // product chosen, no money yet
    String name() { return "SELECTED"; }
    void select(VendingMachine m, String code) { m.choose(code); }   // changing your mind is fine
    void insert(VendingMachine m, Coin coin) { m.setState(new PayingState()); m.accept(coin); }
    void cancel(VendingMachine m) { m.refund("Select a product"); }
}

final class PayingState extends State {                         // some money in, selection locked
    String name() { return "PAYING"; }
    void insert(VendingMachine m, Coin coin) { m.accept(coin); }
    void cancel(VendingMachine m) { m.refund("Cancelled, coins returned"); }
}

final class DispensingState extends State {                     // paid, item reserved, motor running
    String name() { return "DISPENSING"; }
    Product dispense(VendingMachine m) { return m.release(); }
}

public class VendingMachine {
    private final Inventory inventory;
    private final CoinBox box;
    private final List<Coin> inserted = new ArrayList<>();
    private final List<Coin> tray = new ArrayList<>();          // the coin return: refunds and change
    private State state = new IdleState();
    private Product selected;
    private String display = "Select a product";

    VendingMachine(Inventory inventory, CoinBox box) { this.inventory = inventory; this.box = box; }

    // The public API. One lock per machine: a coin and a button press can't interleave.
    public synchronized void select(String code) { state.select(this, code); }
    public synchronized void insert(Coin c) { state.insert(this, c); }
    public synchronized void cancel() { state.cancel(this); }
    public synchronized Product dispense() { return state.dispense(this); }
    public synchronized String state() { return state.name(); }
    public synchronized String display() { return display; }
    public synchronized List<Coin> collectCoins() {
        List<Coin> out = List.copyOf(tray);
        tray.clear();
        return out;
    }

    // Called only by the states, never by customers.
    void setState(State s) { state = s; }

    void choose(String code) {
        Product p = inventory.product(code);
        if (inventory.quantity(code) == 0) throw new IllegalStateException(p.name() + " is sold out");
        selected = p;
        display = p.name() + " " + p.priceCents() + "c";
    }

    void accept(Coin c) {
        inserted.add(c);
        int due = paid() - selected.priceCents();
        if (due < 0) { display = "Insert " + (-due) + "c more"; return; }
        // Enough money. Plan the change first, then take the item. If either fails, refund everything.
        List<Coin> change = box.planChange(due, inserted);
        if (change == null) { refund("Can't make change, coins returned"); return; }
        if (!inventory.tryTake(selected.code())) { refund("Sold out, coins returned"); return; }
        box.add(inserted);
        box.remove(change);
        tray.addAll(change);
        inserted.clear();
        state = new DispensingState();
        display = "Dispensing " + selected.name();
    }

    void refund(String message) {
        tray.addAll(inserted);
        inserted.clear();
        selected = null;
        state = new IdleState();
        display = message;
    }

    Product release() {
        Product p = selected;
        selected = null;
        state = new IdleState();
        display = "Select a product";
        return p;
    }

    private int paid() { return inserted.stream().mapToInt(c -> c.cents).sum(); }

    static int cents(List<Coin> coins) { return coins.stream().mapToInt(c -> c.cents).sum(); }
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) throws Exception {
        Inventory inv = new Inventory();
        inv.restock(new Product("A1", "Cola", 125), 1);
        inv.restock(new Product("B2", "Chips", 50), 5);
        CoinBox box = new CoinBox();
        box.add(List.of(Coin.DIME, Coin.DIME, Coin.NICKEL));
        VendingMachine vm = new VendingMachine(inv, box);

        // Two dollars for a 125c cola: 75c change can't be made from 2 dimes and a nickel.
        vm.select("A1");
        vm.insert(Coin.DOLLAR);
        vm.insert(Coin.DOLLAR);
        check(vm.state().equals("IDLE") && vm.collectCoins().equals(List.of(Coin.DOLLAR, Coin.DOLLAR)), "refunded");
        check(inv.quantity("A1") == 1, "nothing was sold");

        // Exact money vends at once.
        vm.select("A1");
        vm.insert(Coin.DOLLAR);
        vm.insert(Coin.QUARTER);
        check(vm.state().equals("DISPENSING") && vm.dispense().name().equals("Cola"), "cola");
        check(vm.collectCoins().isEmpty() && inv.quantity("A1") == 0, "no change, last cola gone");
        try { vm.select("A1"); check(false, "sold out"); } catch (IllegalStateException expected) { }

        // A dollar for 50c chips: the fewest coins are two quarters the machine took earlier.
        vm.select("B2");
        vm.insert(Coin.QUARTER);
        vm.insert(Coin.QUARTER);
        vm.dispense();
        vm.select("B2");
        vm.insert(Coin.DOLLAR);
        vm.dispense();
        check(vm.collectCoins().equals(List.of(Coin.QUARTER, Coin.QUARTER)), "two quarters change");

        // Cancel returns exactly the coins inserted.
        vm.select("B2");
        vm.insert(Coin.DIME);
        vm.cancel();
        check(vm.collectCoins().equals(List.of(Coin.DIME)) && vm.state().equals("IDLE"), "refund");

        // 100 threads (keypad, app, ...) race for 10 bags of chips: exactly 10 succeed.
        Inventory shared = new Inventory();
        shared.restock(new Product("B2", "Chips", 50), 10);
        AtomicInteger sold = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(16);
        List<Future<?>> fs = new ArrayList<>();
        for (int i = 0; i < 100; i++) fs.add(pool.submit(() -> { if (shared.tryTake("B2")) sold.incrementAndGet(); }));
        for (Future<?> f : fs) f.get();
        pool.shutdown();
        check(sold.get() == 10 && shared.quantity("B2") == 0, "no overselling, got " + sold.get());
        System.out.println("all checks passed");
    }
}
# file: vending_machine.py
from __future__ import annotations

import threading
from collections import Counter
from dataclasses import dataclass
from enum import IntEnum


class Coin(IntEnum):
    NICKEL = 5
    DIME = 10
    QUARTER = 25
    DOLLAR = 100


@dataclass(frozen=True)
class Product:
    code: str
    name: str
    price_cents: int                              # integers, never floats, for money


class Inventory:
    """Stock per slot, shared by every purchase channel. Taking an item is atomic."""

    def __init__(self) -> None:
        self._products: dict[str, Product] = {}
        self._stock: Counter[str] = Counter()
        self._lock = threading.Lock()

    def restock(self, product: Product, quantity: int) -> None:
        with self._lock:
            self._products[product.code] = product
            self._stock[product.code] += quantity

    def product(self, code: str) -> Product:
        if code not in self._products:
            raise KeyError(f"no product {code}")
        return self._products[code]

    def quantity(self, code: str) -> int:
        with self._lock:
            return self._stock[code]

    def try_take(self, code: str) -> bool:
        with self._lock:                          # check and decrement in one step
            if self._stock[code] == 0:
                return False
            self._stock[code] -= 1
            return True


class CoinBox:
    def __init__(self, coins: list[Coin] | None = None) -> None:
        self._coins: Counter[Coin] = Counter(coins or [])

    def add(self, coins: list[Coin]) -> None:
        self._coins.update(coins)

    def remove(self, coins: list[Coin]) -> None:
        self._coins.subtract(coins)

    def plan_change(self, amount: int, extra: list[Coin]) -> list[Coin] | None:
        """Fewest coins summing to `amount`, or None. Greedy fails with limited coins."""
        have = self._coins + Counter(extra)
        best: dict[int, list[Coin]] = {0: []}     # amount -> fewest coins found so far
        for coin in sorted(have, reverse=True):
            nxt = dict(best)
            for reached, coins in best.items():
                for k in range(1, have[coin] + 1):
                    total = reached + k * coin
                    if total > amount:
                        break
                    if total not in nxt or len(coins) + k < len(nxt[total]):
                        nxt[total] = coins + [coin] * k
            best = nxt
        return best.get(amount)


class State:
    """Every event defaults to "not now", so each state overrides only what it accepts."""
    name = "?"

    def select(self, m: VendingMachine, code: str) -> None:
        raise RuntimeError(f"can't select while {self.name}")

    def insert(self, m: VendingMachine, coin: Coin) -> None:
        raise RuntimeError(f"can't take coins while {self.name}")

    def cancel(self, m: VendingMachine) -> None:
        raise RuntimeError(f"can't cancel while {self.name}")

    def dispense(self, m: VendingMachine) -> Product:
        raise RuntimeError(f"can't dispense while {self.name}")


class Idle(State):
    name = "IDLE"

    def select(self, m, code):
        m._choose(code)
        m._state = Selected()

    def cancel(self, m):
        pass                                      # nothing to give back


class Selected(State):
    name = "SELECTED"

    def select(self, m, code):
        m._choose(code)                           # changing your mind is fine

    def insert(self, m, coin):
        m._state = Paying()
        m._accept(coin)

    def cancel(self, m):
        m._refund("Select a product")


class Paying(State):
    name = "PAYING"

    def insert(self, m, coin):
        m._accept(coin)

    def cancel(self, m):
        m._refund("Cancelled, coins returned")


class Dispensing(State):
    name = "DISPENSING"

    def dispense(self, m):
        return m._release()


class VendingMachine:
    def __init__(self, inventory: Inventory, box: CoinBox) -> None:
        self._inventory, self._box = inventory, box
        self._inserted: list[Coin] = []
        self._tray: list[Coin] = []               # the coin return: refunds and change
        self._state: State = Idle()
        self._selected: Product | None = None
        self.display = "Select a product"
        self._lock = threading.Lock()             # one customer session at a time

    # Public API: each event runs under the machine lock.
    def select(self, code: str) -> None:
        with self._lock:
            self._state.select(self, code)

    def insert(self, coin: Coin) -> None:
        with self._lock:
            self._state.insert(self, coin)

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

    def dispense(self) -> Product:
        with self._lock:
            return self._state.dispense(self)

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

    def collect_coins(self) -> list[Coin]:
        with self._lock:
            out, self._tray = self._tray, []
            return out

    # Used by the states only.
    def _choose(self, code: str) -> None:
        p = self._inventory.product(code)
        if self._inventory.quantity(code) == 0:
            raise RuntimeError(f"{p.name} is sold out")
        self._selected = p
        self.display = f"{p.name} {p.price_cents}c"

    def _accept(self, coin: Coin) -> None:
        assert self._selected is not None
        self._inserted.append(coin)
        due = sum(self._inserted) - self._selected.price_cents
        if due < 0:
            self.display = f"Insert {-due}c more"
            return
        change = self._box.plan_change(due, self._inserted)   # plan first, then commit
        if change is None:
            return self._refund("Can't make change, coins returned")
        if not self._inventory.try_take(self._selected.code):
            return self._refund("Sold out, coins returned")
        self._box.add(self._inserted)
        self._box.remove(change)
        self._tray += change
        self._inserted = []
        self._state = Dispensing()
        self.display = f"Dispensing {self._selected.name}"

    def _refund(self, message: str) -> None:
        self._tray += self._inserted
        self._inserted, self._selected = [], None
        self._state = Idle()
        self.display = message

    def _release(self) -> Product:
        p, self._selected = self._selected, None
        assert p is not None
        self._state = Idle()
        self.display = "Select a product"
        return p


if __name__ == "__main__":
    inv = Inventory()
    inv.restock(Product("A1", "Cola", 125), 1)
    inv.restock(Product("B2", "Chips", 50), 5)
    vm = VendingMachine(inv, CoinBox([Coin.DIME, Coin.DIME, Coin.NICKEL]))

    vm.select("A1")
    vm.insert(Coin.DOLLAR)
    vm.insert(Coin.DOLLAR)                        # 75c change is impossible: refund
    assert vm.state == "IDLE" and vm.collect_coins() == [Coin.DOLLAR, Coin.DOLLAR]

    vm.select("A1")
    vm.insert(Coin.DOLLAR)
    vm.insert(Coin.QUARTER)
    assert vm.dispense().name == "Cola" and inv.quantity("A1") == 0

    vm.select("B2")
    vm.insert(Coin.QUARTER)
    vm.insert(Coin.QUARTER)
    vm.dispense()
    vm.select("B2")
    vm.insert(Coin.DOLLAR)
    vm.dispense()
    assert vm.collect_coins() == [Coin.QUARTER, Coin.QUARTER]
    print("all checks passed")
// file: vendingMachine.ts
export const Coin = { NICKEL: 5, DIME: 10, QUARTER: 25, DOLLAR: 100 } as const;
export type Coin = (typeof Coin)[keyof typeof Coin];        // a coin is its value in cents

export interface Product { readonly code: string; readonly name: string; readonly priceCents: number }

const sum = (coins: readonly Coin[]): number => coins.reduce((a, c) => a + c, 0);

export class Inventory {
  private readonly products = new Map<string, Product>();
  private readonly stock = new Map<string, number>();

  restock(p: Product, quantity: number): void {
    this.products.set(p.code, p);
    this.stock.set(p.code, (this.stock.get(p.code) ?? 0) + quantity);
  }
  product(code: string): Product {
    const p = this.products.get(code);
    if (!p) throw new Error(`no product ${code}`);
    return p;
  }
  quantity(code: string): number { return this.stock.get(code) ?? 0; }

  /** Check and decrement with no await in between, so two channels can't both take the last item. */
  tryTake(code: string): boolean {
    const q = this.quantity(code);
    if (q === 0) return false;
    this.stock.set(code, q - 1);
    return true;
  }
}

export class CoinBox {
  private readonly coins = new Map<Coin, number>();
  constructor(initial: Coin[] = []) { this.add(initial); }

  add(coins: readonly Coin[]): void { for (const c of coins) this.coins.set(c, (this.coins.get(c) ?? 0) + 1); }
  remove(coins: readonly Coin[]): void { for (const c of coins) this.coins.set(c, (this.coins.get(c) ?? 0) - 1); }

  /** Fewest coins summing to `amount`, or null. Greedy fails when coin counts are limited. */
  planChange(amount: number, extra: readonly Coin[]): Coin[] | null {
    const have = new Map(this.coins);
    for (const c of extra) have.set(c, (have.get(c) ?? 0) + 1);
    let best = new Map<number, Coin[]>([[0, []]]);
    for (const coin of [...have.keys()].sort((a, b) => b - a)) {
      const next = new Map(best);
      for (const [reached, coins] of best) {
        for (let k = 1; k <= (have.get(coin) ?? 0) && reached + k * coin <= amount; k++) {
          const total = reached + k * coin;
          const known = next.get(total);
          if (!known || coins.length + k < known.length) next.set(total, [...coins, ...Array<Coin>(k).fill(coin)]);
        }
      }
      best = next;
    }
    return best.get(amount) ?? null;
  }
}

/** Every event defaults to "not now", so each state overrides only what it accepts. */
export abstract class State {
  abstract readonly name: string;
  select(_m: VendingMachine, _code: string): void { throw this.reject("select"); }
  insert(_m: VendingMachine, _coin: Coin): void { throw this.reject("take coins"); }
  cancel(_m: VendingMachine): void { throw this.reject("cancel"); }
  dispense(_m: VendingMachine): Product { throw this.reject("dispense"); }
  protected reject(what: string): Error { return new Error(`can't ${what} while ${this.name}`); }
}

export class Idle extends State {
  readonly name = "IDLE";
  override select(m: VendingMachine, code: string): void { m.choose(code); m.setState(new Selected()); }
  override cancel(): void {}
}

export class Selected extends State {
  readonly name = "SELECTED";
  override select(m: VendingMachine, code: string): void { m.choose(code); }
  override insert(m: VendingMachine, coin: Coin): void { m.setState(new Paying()); m.accept(coin); }
  override cancel(m: VendingMachine): void { m.refund("Select a product"); }
}

export class Paying extends State {
  readonly name = "PAYING";
  override insert(m: VendingMachine, coin: Coin): void { m.accept(coin); }
  override cancel(m: VendingMachine): void { m.refund("Cancelled, coins returned"); }
}

export class Dispensing extends State {
  readonly name = "DISPENSING";
  override dispense(m: VendingMachine): Product { return m.release(); }
}

export class VendingMachine {
  private inserted: Coin[] = [];
  private tray: Coin[] = [];                                  // the coin return
  private current: State = new Idle();
  protected selected: Product | null = null;
  display = "Select a product";

  constructor(protected readonly inventory: Inventory, private readonly box: CoinBox) {}

  // Public API. Each call is synchronous, so events never interleave on Node's one thread.
  select(code: string): void { this.current.select(this, code); }
  insert(coin: Coin): void { this.current.insert(this, coin); }
  cancel(): void { this.current.cancel(this); }
  dispense(): Product { return this.current.dispense(this); }
  get state(): string { return this.current.name; }
  collectCoins(): Coin[] { const out = this.tray; this.tray = []; return out; }

  // Used by the states.
  setState(s: State): void { this.current = s; }

  choose(code: string): void {
    const p = this.inventory.product(code);
    if (this.inventory.quantity(code) === 0) throw new Error(`${p.name} is sold out`);
    this.selected = p;
    this.display = `${p.name} ${p.priceCents}c`;
  }

  accept(coin: Coin): void {
    const p = this.selectedProduct();
    this.inserted.push(coin);
    const due = sum(this.inserted) - p.priceCents;
    if (due < 0) { this.display = `Insert ${-due}c more`; return; }
    const change = this.box.planChange(due, this.inserted);    // plan first, then commit
    if (change === null) return this.refund("Can't make change, coins returned");
    if (!this.inventory.tryTake(p.code)) return this.refund("Sold out, coins returned");
    this.box.add(this.inserted);
    this.box.remove(change);
    this.tray.push(...change);
    this.inserted = [];
    this.current = new Dispensing();
    this.display = `Dispensing ${p.name}`;
  }

  refund(message: string): void {
    this.tray.push(...this.inserted);
    this.inserted = [];
    this.selected = null;
    this.current = new Idle();
    this.display = message;
  }

  release(): Product {
    const p = this.selectedProduct();
    this.selected = null;
    this.current = new Idle();
    this.display = "Select a product";
    return p;
  }

  protected selectedProduct(): Product {
    if (!this.selected) throw new Error("nothing selected");
    return this.selected;
  }
}

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

  • Cents, not floats. See the correction below for what floats do.
  • Coins, not amounts. The machine knows which coins it holds, so it can give change and refund the exact coins inserted.
  • No separate confirmSelection. Inserting money is the confirmation.
  • Stock is reserved when payment completes, not at selection, with an atomic tryTake. Another channel may sell the last item while a customer is still paying, and that case ends in a full refund.
  • The base state rejects by default, so each state lists only what it accepts.

Core Classes & Interfaces

This is the original walkthrough. It runs: the TypeScript passes tsc --strict, and the three tests in the testing section pass with a minimal Jest shim.

Correction (2026-11-10)

This code stores money as floating-point dollars, which is a real bug, not a style point. We ran the Python version: a $1.00 product paid with ten 10¢ coins leaves the machine in PaymentState with inserted_amount == 0.9999999999999999, demanding more money. Change can also come out as values like 5.5e-17. The tests below hide this with toBeCloseTo. Use integer cents, as the complete code does.

TypeScript Implementation

// ─── Product & Inventory ─────────────────────────────────

class Product {
  constructor(
    public readonly code: string,
    public readonly name: string,
    public readonly price: number
  ) {}
}

class ItemSlot {
  constructor(
    public readonly product: Product,
    private quantity: number
  ) {}

  isAvailable(): boolean {
    return this.quantity > 0;
  }

  getQuantity(): number {
    return this.quantity;
  }

  decrement(): void {
    if (this.quantity <= 0) {
      throw new Error(`${this.product.name} is out of stock`);
    }
    this.quantity--;
  }

  restock(amount: number): void {
    this.quantity += amount;
  }
}

class Inventory {
  private items: Map<string, ItemSlot> = new Map();

  addItem(product: Product, quantity: number): void {
    const existing = this.items.get(product.code);
    if (existing) {
      existing.restock(quantity);
    } else {
      this.items.set(product.code, new ItemSlot(product, quantity));
    }
  }

  isAvailable(code: string): boolean {
    const slot = this.items.get(code);
    return slot !== undefined && slot.isAvailable();
  }

  getProduct(code: string): Product | null {
    return this.items.get(code)?.product ?? null;
  }

  decrementStock(code: string): void {
    const slot = this.items.get(code);
    if (!slot) throw new Error(`Product ${code} not found`);
    slot.decrement();
  }

  getAllProducts(): Array<{
    product: Product;
    quantity: number;
    available: boolean;
  }> {
    return Array.from(this.items.values()).map((slot) => ({
      product: slot.product,
      quantity: slot.getQuantity(),
      available: slot.isAvailable(),
    }));
  }
}

// ─── Dispense Result ─────────────────────────────────────

interface DispenseResult {
  product: Product;
  change: number;
}

// ─── State Interface ─────────────────────────────────────

interface State {
  selectProduct(machine: VendingMachine, code: string): void;
  insertMoney(machine: VendingMachine, amount: number): void;
  cancel(machine: VendingMachine): number;
  dispense(machine: VendingMachine): DispenseResult | null;
}

// ─── Concrete States ─────────────────────────────────────

class IdleState implements State {
  selectProduct(machine: VendingMachine, code: string): void {
    if (!machine.getInventory().isAvailable(code)) {
      throw new Error(`Product ${code} is out of stock`);
    }
    const product = machine.getInventory().getProduct(code)!;
    machine.setSelectedProduct(product);
    machine.setState(new SelectingState());
  }

  insertMoney(_machine: VendingMachine, _amount: number): void {
    throw new Error('Please select a product first');
  }

  cancel(_machine: VendingMachine): number {
    return 0; // nothing to refund
  }

  dispense(_machine: VendingMachine): DispenseResult | null {
    throw new Error('Please select a product and insert money');
  }
}

class SelectingState implements State {
  selectProduct(machine: VendingMachine, code: string): void {
    // Allow changing selection
    if (!machine.getInventory().isAvailable(code)) {
      throw new Error(`Product ${code} is out of stock`);
    }
    const product = machine.getInventory().getProduct(code)!;
    machine.setSelectedProduct(product);
  }

  insertMoney(machine: VendingMachine, amount: number): void {
    machine.addInsertedAmount(amount);
    const product = machine.getSelectedProduct()!;

    if (machine.getInsertedAmount() >= product.price) {
      machine.setState(new DispensingState());
    } else {
      machine.setState(new PaymentState());
    }
  }

  cancel(machine: VendingMachine): number {
    const refund = machine.getInsertedAmount();
    machine.reset();
    return refund;
  }

  dispense(_machine: VendingMachine): DispenseResult | null {
    throw new Error('Please insert money first');
  }
}

class PaymentState implements State {
  selectProduct(_machine: VendingMachine, _code: string): void {
    throw new Error('Cannot change product during payment. Cancel first.');
  }

  insertMoney(machine: VendingMachine, amount: number): void {
    machine.addInsertedAmount(amount);
    const product = machine.getSelectedProduct()!;

    if (machine.getInsertedAmount() >= product.price) {
      machine.setState(new DispensingState());
    }
    // else stay in PaymentState — need more money
  }

  cancel(machine: VendingMachine): number {
    const refund = machine.getInsertedAmount();
    machine.reset();
    return refund;
  }

  dispense(_machine: VendingMachine): DispenseResult | null {
    const product = _machine.getSelectedProduct()!;
    const remaining = product.price - _machine.getInsertedAmount();
    throw new Error(`Insufficient funds. Insert $${remaining.toFixed(2)} more.`);
  }
}

class DispensingState implements State {
  selectProduct(_machine: VendingMachine, _code: string): void {
    throw new Error('Currently dispensing. Please wait.');
  }

  insertMoney(_machine: VendingMachine, _amount: number): void {
    throw new Error('Currently dispensing. Please wait.');
  }

  cancel(_machine: VendingMachine): number {
    throw new Error('Cannot cancel during dispensing');
  }

  dispense(machine: VendingMachine): DispenseResult {
    const product = machine.getSelectedProduct()!;
    const change = machine.getInsertedAmount() - product.price;

    // Dispense product
    machine.getInventory().decrementStock(product.code);

    const result: DispenseResult = { product, change };

    // Reset machine
    machine.reset();

    return result;
  }
}

// ─── Vending Machine ─────────────────────────────────────

class VendingMachine {
  private inventory: Inventory = new Inventory();
  private currentState: State = new IdleState();
  private selectedProduct: Product | null = null;
  private insertedAmount: number = 0;

  // ── Public API (delegates to current state) ──────────

  selectProduct(code: string): void {
    this.currentState.selectProduct(this, code);
  }

  insertMoney(amount: number): void {
    if (amount <= 0) throw new Error('Amount must be positive');
    this.currentState.insertMoney(this, amount);
  }

  cancel(): number {
    return this.currentState.cancel(this);
  }

  dispense(): DispenseResult | null {
    return this.currentState.dispense(this);
  }

  // ── State management (used by State objects) ─────────

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

  getInventory(): Inventory {
    return this.inventory;
  }

  getSelectedProduct(): Product | null {
    return this.selectedProduct;
  }

  setSelectedProduct(product: Product): void {
    this.selectedProduct = product;
  }

  getInsertedAmount(): number {
    return this.insertedAmount;
  }

  addInsertedAmount(amount: number): void {
    this.insertedAmount += amount;
  }

  reset(): void {
    this.selectedProduct = null;
    this.insertedAmount = 0;
    this.currentState = new IdleState();
  }

  // ── Admin operations ─────────────────────────────────

  addProduct(product: Product, quantity: number): void {
    this.inventory.addItem(product, quantity);
  }

  getProductList(): Array<{
    product: Product;
    quantity: number;
    available: boolean;
  }> {
    return this.inventory.getAllProducts();
  }
}

Python Implementation

from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional


# ─── Product & Inventory ───────────────────────────────

@dataclass(frozen=True)
class Product:
    code: str
    name: str
    price: float


class ItemSlot:
    def __init__(self, product: Product, quantity: int):
        self.product = product
        self._quantity = quantity

    @property
    def is_available(self) -> bool:
        return self._quantity > 0

    @property
    def quantity(self) -> int:
        return self._quantity

    def decrement(self) -> None:
        if self._quantity <= 0:
            raise ValueError(f"{self.product.name} is out of stock")
        self._quantity -= 1

    def restock(self, amount: int) -> None:
        self._quantity += amount


class Inventory:
    def __init__(self):
        self._items: dict[str, ItemSlot] = {}

    def add_item(self, product: Product, quantity: int) -> None:
        if product.code in self._items:
            self._items[product.code].restock(quantity)
        else:
            self._items[product.code] = ItemSlot(product, quantity)

    def is_available(self, code: str) -> bool:
        slot = self._items.get(code)
        return slot is not None and slot.is_available

    def get_product(self, code: str) -> Optional[Product]:
        slot = self._items.get(code)
        return slot.product if slot else None

    def decrement_stock(self, code: str) -> None:
        slot = self._items.get(code)
        if not slot:
            raise ValueError(f"Product {code} not found")
        slot.decrement()


# ─── Dispense Result ───────────────────────────────────

@dataclass
class DispenseResult:
    product: Product
    change: float


# ─── State Interface ──────────────────────────────────

class State(ABC):
    @abstractmethod
    def select_product(self, machine: "VendingMachine", code: str) -> None:
        ...

    @abstractmethod
    def insert_money(self, machine: "VendingMachine", amount: float) -> None:
        ...

    @abstractmethod
    def cancel(self, machine: "VendingMachine") -> float:
        ...

    @abstractmethod
    def dispense(self, machine: "VendingMachine") -> Optional[DispenseResult]:
        ...


# ─── Concrete States ──────────────────────────────────

class IdleState(State):
    def select_product(self, machine: "VendingMachine", code: str) -> None:
        if not machine.inventory.is_available(code):
            raise ValueError(f"Product {code} is out of stock")
        product = machine.inventory.get_product(code)
        machine.selected_product = product
        machine.set_state(SelectingState())

    def insert_money(self, machine: "VendingMachine", amount: float) -> None:
        raise RuntimeError("Please select a product first")

    def cancel(self, machine: "VendingMachine") -> float:
        return 0.0

    def dispense(self, machine: "VendingMachine") -> Optional[DispenseResult]:
        raise RuntimeError("Please select a product and insert money")


class SelectingState(State):
    def select_product(self, machine: "VendingMachine", code: str) -> None:
        if not machine.inventory.is_available(code):
            raise ValueError(f"Product {code} is out of stock")
        machine.selected_product = machine.inventory.get_product(code)

    def insert_money(self, machine: "VendingMachine", amount: float) -> None:
        machine.inserted_amount += amount
        product = machine.selected_product
        assert product is not None

        if machine.inserted_amount >= product.price:
            machine.set_state(DispensingState())
        else:
            machine.set_state(PaymentState())

    def cancel(self, machine: "VendingMachine") -> float:
        refund = machine.inserted_amount
        machine.reset()
        return refund

    def dispense(self, machine: "VendingMachine") -> Optional[DispenseResult]:
        raise RuntimeError("Please insert money first")


class PaymentState(State):
    def select_product(self, machine: "VendingMachine", code: str) -> None:
        raise RuntimeError("Cannot change product during payment. Cancel first.")

    def insert_money(self, machine: "VendingMachine", amount: float) -> None:
        machine.inserted_amount += amount
        product = machine.selected_product
        assert product is not None

        if machine.inserted_amount >= product.price:
            machine.set_state(DispensingState())

    def cancel(self, machine: "VendingMachine") -> float:
        refund = machine.inserted_amount
        machine.reset()
        return refund

    def dispense(self, machine: "VendingMachine") -> Optional[DispenseResult]:
        product = machine.selected_product
        assert product is not None
        remaining = product.price - machine.inserted_amount
        raise RuntimeError(f"Insufficient funds. Insert ${remaining:.2f} more.")


class DispensingState(State):
    def select_product(self, machine: "VendingMachine", code: str) -> None:
        raise RuntimeError("Currently dispensing. Please wait.")

    def insert_money(self, machine: "VendingMachine", amount: float) -> None:
        raise RuntimeError("Currently dispensing. Please wait.")

    def cancel(self, machine: "VendingMachine") -> float:
        raise RuntimeError("Cannot cancel during dispensing")

    def dispense(self, machine: "VendingMachine") -> DispenseResult:
        product = machine.selected_product
        assert product is not None
        change = machine.inserted_amount - product.price

        machine.inventory.decrement_stock(product.code)
        result = DispenseResult(product=product, change=change)
        machine.reset()
        return result


# ─── Vending Machine ──────────────────────────────────

class VendingMachine:
    def __init__(self):
        self.inventory = Inventory()
        self._state: State = IdleState()
        self.selected_product: Optional[Product] = None
        self.inserted_amount: float = 0.0

    # Public API
    def select_product(self, code: str) -> None:
        self._state.select_product(self, code)

    def insert_money(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self._state.insert_money(self, amount)

    def cancel(self) -> float:
        return self._state.cancel(self)

    def dispense(self) -> Optional[DispenseResult]:
        return self._state.dispense(self)

    # State management
    def set_state(self, state: State) -> None:
        self._state = state

    def reset(self) -> None:
        self.selected_product = None
        self.inserted_amount = 0.0
        self._state = IdleState()

    # Admin
    def add_product(self, product: Product, quantity: int) -> None:
        self.inventory.add_item(product, quantity)

Concurrency Considerations

Hardware Interrupts

A physical vending machine has button presses as hardware interrupts. Two buttons pressed simultaneously could corrupt state.

Solutions:

  1. Single event queue — All button presses and coin insertions go into a thread-safe queue. A single event loop processes them sequentially.

  2. Synchronized state transitions — Wrap setState() and all state method calls in a mutex.

class VendingMachine {
  private mutex = new Mutex();

  async selectProduct(code: string): Promise<void> {
    return this.mutex.runExclusive(() => {
      this.currentState.selectProduct(this, code);
    });
  }

  async insertMoney(amount: number): Promise<void> {
    return this.mutex.runExclusive(() => {
      this.currentState.insertMoney(this, amount);
    });
  }
}
  1. Idempotent operations — If dispense() is called twice, the second call should be a no-op (machine already reset to idle).

Correction (2026-11-10)

Two details above are wrong or incomplete. Point 3 says a second dispense() "should be a no-op (machine already reset to idle)". In the walkthrough code it isn't: IdleState.dispense throws. That's arguably the better behaviour, because a stray dispense signal should be loud, but it isn't idempotent. And the TypeScript snippet uses a Mutex class with runExclusive, which isn't built in. It comes from a library such as async-mutex. In plain Node, synchronous methods need no mutex at all, as explained below.

The hardware-interrupt framing above is one source of concurrency. A modern machine has a bigger one: several purchase channels. A keypad session, a mobile app that buys remotely, and a card reader can all act on the same stock.

What's shared.

  • The inventory is shared by every channel.
  • The coin box is shared by the keypad session and the operator who collects cash.
  • The session state (current state, selection, inserted coins, tray) is shared by the coin acceptor, the keypad and any timeout timer.

The races.

  1. The last item. A keypad customer selects the last cola and starts paying. Meanwhile the app sells it. If stock was only checked at selection and decremented at dispense, both purchases succeed and one customer gets nothing for their money. The fix is to make the decrement itself the check: tryTake is a compare-and-set loop in Java, a short critical section in Python, and a synchronous read-then-write in TypeScript. Whoever loses the race gets a clean "sold out", and at the keypad that means a full refund.
  2. A coin during a cancel. A coin lands while the cancel button is being handled. Without a lock, the coin can be appended after the refund copied the list, and it's swallowed. The machine lock makes each event atomic, so the coin arrives either before the cancel, and is refunded, or after it, and is rejected in Idle, which the acceptor returns.
  3. Collecting cash mid-purchase could empty coins a change plan relies on. Plan and commit run under the machine lock, and maintenance is only allowed from Idle.
sequenceDiagram
    participant K as Keypad session
    participant I as Inventory
    participant A as Mobile app
    K->>K: select cola, one left, start paying
    A->>I: tryTake cola
    I-->>A: true, stock is now 0
    K->>K: last coin inserted, payment complete
    K->>I: tryTake cola
    I-->>K: false
    K->>K: refund every coin, display sold out

The locking, and its granularity. There are two levels on purpose. One lock per machine serialises session events, because a session is inherently sequential: one customer, one selection, one set of coins. Inventory is atomic per slot, so the app doesn't wait for a slow keypad customer to finish counting coins. A single global lock would also be correct, just slower for the app. Locking per state object would be wrong, since states are swapped on every transition, so a lock inside one protects nothing.

TypeScript. Node runs JavaScript on one thread, and every machine method is synchronous, so events can't interleave and no mutex is needed. The race comes back the moment a step awaits, for example await bank.charge() in the card extension, between reserving stock and committing. Then reserve first, synchronously, and undo the reservation if the awaited step fails. That's the order Extension A uses. For more, see thread-safe class design and race conditions.

Extensibility: the interviewer adds X

The original summary table is next, then two extensions as real diffs against the complete code. We applied each diff and ran the tests.

Extensions & Follow-ups

ExtensionDesign Impact
Coin denomination trackingTrack inserted coins individually (not just sum); change-making algorithm uses available denominations
Exact change modeIf machine can't make change, enter "exact change only" mode — new ExactChangeState
Multiple item purchaseAdd Cart between Selecting and Payment; accumulate products before paying
Discount codesAdd DiscountService that modifies price before payment check
Admin maintenance modeNew MaintenanceState — all user actions rejected; admin can restock and reset
Touchscreen UISeparate Display interface; states return display messages; UI renders them
Cash collectionCashBox class tracks total cash; admin can collectCash() which empties it

Extension A: card payments

"A card is another way to pay for a selected product, so it's a new event, tapCard. The base state rejects it by default, and only Selected accepts it. The machine gets a CardReader through its constructor. Coins, change and the other states don't change."

--- a/vendingMachine.ts
+++ b/vendingMachine.ts
@@ -6,6 +6,9 @@
 
 const sum = (coins: readonly Coin[]): number => coins.reduce((a, c) => a + c, 0);
 
+/** The card network. In production this calls the payment processor. */
+export interface CardReader { charge(cardId: string, cents: number): boolean }
+
 export class Inventory {
   private readonly products = new Map<string, Product>();
   private readonly stock = new Map<string, number>();
@@ -64,6 +67,7 @@
   insert(_m: VendingMachine, _coin: Coin): void { throw this.reject("take coins"); }
   cancel(_m: VendingMachine): void { throw this.reject("cancel"); }
   dispense(_m: VendingMachine): Product { throw this.reject("dispense"); }
+  tapCard(_m: VendingMachine, _cardId: string): void { throw this.reject("take cards"); }
   protected reject(what: string): Error { return new Error(`can't ${what} while ${this.name}`); }
 }
 
@@ -78,6 +82,7 @@
   override select(m: VendingMachine, code: string): void { m.choose(code); }
   override insert(m: VendingMachine, coin: Coin): void { m.setState(new Paying()); m.accept(coin); }
   override cancel(m: VendingMachine): void { m.refund("Select a product"); }
+  override tapCard(m: VendingMachine, cardId: string): void { m.payByCard(cardId); }
 }
 
 export class Paying extends State {
@@ -98,12 +103,14 @@
   protected selected: Product | null = null;
   display = "Select a product";
 
-  constructor(protected readonly inventory: Inventory, private readonly box: CoinBox) {}
+  constructor(protected readonly inventory: Inventory, private readonly box: CoinBox,
+              private readonly cards?: CardReader) {}
 
   // Public API. Each call is synchronous, so events never interleave on Node's one thread.
   select(code: string): void { this.current.select(this, code); }
   insert(coin: Coin): void { this.current.insert(this, coin); }
   cancel(): void { this.current.cancel(this); }
+  tapCard(cardId: string): void { this.current.tapCard(this, cardId); }
   dispense(): Product { return this.current.dispense(this); }
   get state(): string { return this.current.name; }
   collectCoins(): Coin[] { const out = this.tray; this.tray = []; return out; }
@@ -133,6 +140,18 @@
     this.current = new Dispensing();
     this.display = `Dispensing ${p.name}`;
   }
+
+  payByCard(cardId: string): void {
+    const p = this.selectedProduct();
+    if (!this.cards) throw new Error("this machine has no card reader");
+    if (!this.inventory.tryTake(p.code)) return this.refund("Sold out");      // reserve first
+    if (!this.cards.charge(cardId, p.priceCents)) {
+      this.inventory.restock(p, 1);                                            // undo the reservation
+      return this.refund("Card declined");
+    }
+    this.current = new Dispensing();
+    this.display = `Dispensing ${p.name}`;
+  }
 
   refund(message: string): void {
     this.tray.push(...this.inserted);

The order in payByCard matters: reserve the item, then charge, then undo the reservation if the charge fails. Charging first risks taking money for an item another channel has just sold. With a real processor, charge is asynchronous and usually split into authorize before the vend and capture after the motor confirms, so a jammed spiral never costs the customer anything. Only Selected accepts a card, so a customer who has inserted coins must cancel first. Accepting a card in Paying would mean refunding the coins in the same step, which is a product decision worth raising.

Extension B: maintenance mode and restocking

"The operator needs a mode where customers are refused and restocking is allowed. That's a new state, Maintenance, plus three operator events. Only Idle can enter it, so nobody is cut off mid-purchase."

--- a/vending_machine.py
+++ b/vending_machine.py
@@ -94,6 +94,15 @@
     def dispense(self, m: VendingMachine) -> Product:
         raise RuntimeError(f"can't dispense while {self.name}")
 
+    def enter_maintenance(self, m: VendingMachine) -> None:
+        raise RuntimeError(f"can't start maintenance while {self.name}")
+
+    def restock(self, m: VendingMachine, product: Product, quantity: int) -> None:
+        raise RuntimeError("restocking needs maintenance mode")
+
+    def exit_maintenance(self, m: VendingMachine) -> None:
+        raise RuntimeError(f"not in maintenance, {self.name}")
+
 
 class Idle(State):
     name = "IDLE"
@@ -105,6 +114,10 @@
     def cancel(self, m):
         pass                                      # nothing to give back
 
+    def enter_maintenance(self, m):
+        m._state = Maintenance()                  # only from IDLE: never mid-purchase
+        m.display = "Out of service"
+
 
 class Selected(State):
     name = "SELECTED"
@@ -137,6 +150,20 @@
         return m._release()
 
 
+class Maintenance(State):
+    """Customers get the default rejections. Only the operator's events work."""
+    name = "MAINTENANCE"
+
+    def restock(self, m, product, quantity):
+        if quantity <= 0:
+            raise ValueError("quantity must be positive")
+        m._inventory.restock(product, quantity)
+
+    def exit_maintenance(self, m):
+        m._state = Idle()
+        m.display = "Select a product"
+
+
 class VendingMachine:
     def __init__(self, inventory: Inventory, box: CoinBox) -> None:
         self._inventory, self._box = inventory, box
@@ -164,6 +191,19 @@
         with self._lock:
             return self._state.dispense(self)
 
+    # Operator API, behind the same lock as customer events.
+    def enter_maintenance(self) -> None:
+        with self._lock:
+            self._state.enter_maintenance(self)
+
+    def restock(self, product: Product, quantity: int) -> None:
+        with self._lock:
+            self._state.restock(self, product, quantity)
+
+    def exit_maintenance(self) -> None:
+        with self._lock:
+            self._state.exit_maintenance(self)
+
     @property
     def state(self) -> str:
         with self._lock:

This is the honest cost of the State pattern. Three new events mean three new default methods on the base class. One existing state (Idle) gains a transition, and the new state overrides two events. Selected, Paying and Dispensing are untouched, because the defaults already say no. Restocking goes through the same machine lock as purchases, so it can't interleave with a change plan. In production, enter_maintenance would also check an operator credential.

Testing Strategy

Test TypeWhat to Test
UnitIdleState.selectProduct() transitions to Selecting
UnitPaymentState.insertMoney() — insufficient stays in Payment, sufficient transitions to Dispensing
UnitDispensingState.dispense() — returns product and correct change
UnitInventory.decrementStock() — quantity decreases, throws when zero
IntegrationFull flow: select → insert exact amount → dispense → machine back to idle
IntegrationSelect → insert partial → insert remaining → dispense
IntegrationSelect → cancel → refund equals inserted amount
Edge caseSelect out-of-stock product → error
Edge caseInsert money in idle state → error
Edge caseCancel in idle state → $0 refund
describe('VendingMachine', () => {
  let machine: VendingMachine;

  beforeEach(() => {
    machine = new VendingMachine();
    machine.addProduct(new Product('A1', 'Cola', 1.50), 5);
    machine.addProduct(new Product('A2', 'Chips', 2.00), 3);
  });

  it('should complete a purchase with exact change', () => {
    machine.selectProduct('A1');
    machine.insertMoney(1.50);
    const result = machine.dispense()!;

    expect(result.product.name).toBe('Cola');
    expect(result.change).toBe(0);
  });

  it('should return change on overpayment', () => {
    machine.selectProduct('A1');
    machine.insertMoney(2.00);
    const result = machine.dispense()!;

    expect(result.change).toBeCloseTo(0.50);
  });

  it('should refund on cancel', () => {
    machine.selectProduct('A1');
    machine.insertMoney(0.75);
    const refund = machine.cancel();

    expect(refund).toBeCloseTo(0.75);
  });
});

Sample unit tests

Organise the tests the way the State pattern organises the code:

  1. One test that walks every state on the happy path, asserting the state name after each event.
  2. The rejection matrix. Every "reject" cell in the table above, checked to throw and to change nothing.
  3. Money. Exact payment, overpayment, change made from the customer's own coins, change impossible, cancel returning the exact coins inserted. Compare the change planner against brute force over every subset of a few hundred random coin sets. That's the cheapest way to trust a dynamic programme.
  4. Concurrency. A deterministic test for "another channel sold it mid-payment", and a stress test with many threads racing try_take.
# file: test_vending_machine.py
import random
import threading
import unittest

from vending_machine import Coin, CoinBox, Inventory, Product, VendingMachine


def machine(box=(Coin.DIME, Coin.DIME, Coin.NICKEL), cola=1, chips=5):
    inv = Inventory()
    inv.restock(Product("A1", "Cola", 125), cola)
    inv.restock(Product("B2", "Chips", 50), chips)
    return VendingMachine(inv, CoinBox(list(box))), inv


class StateTest(unittest.TestCase):
    def test_happy_path_walks_every_state(self):
        vm, _ = machine()
        seen = [vm.state]
        vm.select("B2"); seen.append(vm.state)
        vm.insert(Coin.QUARTER); seen.append(vm.state)
        vm.insert(Coin.QUARTER); seen.append(vm.state)
        self.assertEqual(vm.dispense().name, "Chips")
        seen.append(vm.state)
        self.assertEqual(seen, ["IDLE", "SELECTED", "PAYING", "DISPENSING", "IDLE"])

    def test_events_in_the_wrong_state_are_rejected(self):
        vm, _ = machine()
        self.assertRaises(RuntimeError, vm.insert, Coin.DIME)       # idle: select first
        self.assertRaises(RuntimeError, vm.dispense)
        vm.select("B2")
        vm.select("A1")                                             # still allowed: no money yet
        vm.insert(Coin.DIME)
        self.assertRaises(RuntimeError, vm.select, "B2")            # paying: selection locked
        vm.insert(Coin.DOLLAR)
        vm.insert(Coin.QUARTER)                                     # 135c: change is a dime
        self.assertEqual(vm.state, "DISPENSING")
        self.assertRaises(RuntimeError, vm.cancel)                  # too late to cancel

    def test_cancel_returns_exactly_the_coins_inserted(self):
        vm, inv = machine()
        vm.select("A1")
        vm.insert(Coin.QUARTER)
        vm.insert(Coin.DIME)
        vm.cancel()
        self.assertEqual(vm.collect_coins(), [Coin.QUARTER, Coin.DIME])
        self.assertEqual((vm.state, inv.quantity("A1")), ("IDLE", 1))


class ChangeTest(unittest.TestCase):
    def test_greedy_would_fail_but_the_planner_finds_three_dimes(self):
        box = CoinBox([Coin.QUARTER, Coin.DIME, Coin.DIME, Coin.DIME])
        self.assertEqual(box.plan_change(30, []), [Coin.DIME] * 3)

    def test_planner_matches_brute_force(self):
        rng = random.Random(3)
        for _ in range(300):
            coins = [rng.choice(list(Coin)) for _ in range(rng.randint(0, 8))]
            amount = 5 * rng.randint(0, 40)
            got = CoinBox(coins).plan_change(amount, [])
            best = None
            for mask in range(1 << len(coins)):                     # every subset
                pick = [c for i, c in enumerate(coins) if mask >> i & 1]
                if sum(pick) == amount and (best is None or len(pick) < len(best)):
                    best = pick
            self.assertEqual(None if got is None else len(got), None if best is None else len(best))
            if got is not None:
                self.assertEqual(sum(got), amount)

    def test_refund_when_change_is_impossible(self):
        vm, inv = machine()
        vm.select("A1")
        vm.insert(Coin.DOLLAR)
        vm.insert(Coin.DOLLAR)
        self.assertEqual(vm.collect_coins(), [Coin.DOLLAR, Coin.DOLLAR])
        self.assertEqual((vm.state, inv.quantity("A1")), ("IDLE", 1))


class ConcurrencyTest(unittest.TestCase):
    def test_other_channel_takes_the_last_item_mid_payment(self):
        vm, inv = machine()
        vm.select("A1")
        vm.insert(Coin.DOLLAR)
        self.assertTrue(inv.try_take("A1"))                         # the mobile app sells it
        vm.insert(Coin.QUARTER)
        self.assertEqual(vm.state, "IDLE")
        self.assertEqual(vm.display, "Sold out, coins returned")
        self.assertEqual(vm.collect_coins(), [Coin.DOLLAR, Coin.QUARTER])

    def test_no_overselling_under_contention(self):
        _, inv = machine(chips=10)
        sold, start = [], threading.Barrier(50)

        def buy():
            start.wait()
            if inv.try_take("B2"):
                sold.append(1)

        threads = [threading.Thread(target=buy) for _ in range(50)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        self.assertEqual((len(sold), inv.quantity("B2")), (10, 0))


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

Run with python -m unittest test_vending_machine. All 8 pass. A useful extra is a money-conservation invariant: across any sequence of events, the coins in the box plus the tray plus the coins inserted always equal the starting box plus every coin the customer put in. It catches swallowed coins better than any single example.

Common mistakes

  1. Floats for money. Ten dimes in floating point add up to 0.9999999999999999, not 1.0. Use integer cents.
  2. Tracking an amount instead of coins. Then you can't refund the actual coins or know whether change is possible.
  3. Greedy change with limited coins. Taking the biggest coin first fails for 30¢ from a quarter and three dimes. Plan with dynamic programming, or at least backtrack.
  4. Committing before planning. Taking the item or the coins, then finding the change can't be made. Plan, reserve, commit.
  5. Checking stock at selection and decrementing at dispense, which oversells as soon as there's a second channel.
  6. A switch on a state enum in every method, once there are more than two or three states.
  7. States that hold session data. Put the data on the machine and keep states stateless, so a transition is a pointer swap.
  8. Public setState. Any caller can then jump straight to Dispensing. Only states should drive transitions.
  9. No answer for "the motor jammed". The customer paid and got nothing. See the follow-ups.

Interview follow-ups

"The spiral jams and nothing drops. What happens?" Real machines have a drop sensor. Dispensing waits for either "item detected" or a timeout. On timeout it puts the stock back, refunds the payment (coins to the tray, or a card reversal) and goes out of service for that slot. That's another transition out of Dispensing, and the pattern makes it a local change.

"How would you add an inactivity timeout?" A timer posts a timeout event into the same machine lock. Selected and Paying handle it like cancel. Every other state ignores it. Because it's just another event, the race with a last-second coin is handled by the lock.

"Should states be singletons?" They can be, because they hold no data. Statelessness is what makes sharing them safe.

"How does the machine report sales to head office?" Make the machine publish events (ItemSold, CashCollected, SlotEmpty) to listeners, the Observer pattern. The telemetry uploader is one listener, and the restock-alert service is another.

"Different machines take different coins." Make the accepted-coin set and the coin values configuration. The planner already works for any denominations, which is exactly why it isn't greedy.

Further Reading