Skip to main content
← PROBLEMS / LLD
An end-to-end domain learning journey

Design a Vending Machine Using
the State Pattern (LLD).

A Vending Machine LLD uses the State pattern (Idle, HasMoney, Dispensing, SoldOut) to eliminate nested if-else branching, isolate aisle inventory, and guarantee atomic change rollback.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, delegate every user action to an explicit State object so invalid transitions fail cleanly, and validate change availability before committing inventory dispense.

TL;DR30-second simplified summary
▾

Core Mechanics: A vending machine processes asynchronous events (insertCoin, selectItem, dispense, cancelRefund) across four distinct modes (Idle, HasMoney, Dispensing, SoldOut).

Visual & Structural Flow: Depicts Idle -> HasMoney -> Dispensing -> Idle / SoldOut (IDLE -> HAS_MONEY -> DISPENSING -> SOLD_OUT); Item Selection, Change Verification & Safe Dispense (Customer -> VendingMachine -> HasMoneyState -> Inventory & Coins).

Trade-Offs & Production: A naive VendingMachine stores String state and branches inside every method: Zero Isolation: Adding a Maintenance or CardTap state requires auditing every method in VendingMachine. Clean LLD delegates behavior to concrete VendingState classes: Zero if-else in Context: VendingMachine forwards insertMoney, selectItem, dispense, and cancel directly to self.state.

Failure Modes & Application: Explicit State objects power complex lifecycle-driven systems beyond vending machines: Order & Payment Lifecycles: CREATED -> AUTHORIZED -> CAPTURED -> REFUNDED with strict transition guards.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Core LLD Behavioral Patterns: State, Strategy & Observer in Practice
Behavioral patterns—State, Strategy, and Observer—eliminate brittle if-else chains in Low-Level Design interviews and production systems by encapsulating lifecycle transitions, interchangeable algorithms, and event notifications behind clean interfaces.
DDD Aggregates, Value Objects & SOLID Principles for Clean LLD
Domain-Driven Design (DDD) pairs with SOLID principles to structure complex business domains around immutable Value Objects, consistency-enforcing Aggregate Roots, and dependency-inverted Repository interfaces.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why the State Pattern matters in Vending Machine LLD.

Why this matters: The mechanism: understand how Why the State Pattern matters in Vending Machine LLD works from first principles.

Think of Why the State Pattern matters in Vending Machine LLD as the intuition layer for Design a Vending Machine Using the State Pattern (LLD): The mechanism: understand how Why the State Pattern matters in Vending Machine LLD works from first principles.

A vending machine processes asynchronous events (insertCoin, selectItem, dispense, cancelRefund) across four distinct modes (Idle, HasMoney, Dispensing, SoldOut). Mixing state checks with business logic inside one VendingMachine class quickly turns into fragile nested if-else branches where coins can be lost or items dispensed without sufficient change.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens without explicit state encapsulation and change rollback.

Why this matters: The problem: see what breaks without What happens without explicit state encapsulation and change rollback under real concurrency or scale.

Procedural switch(state) code introduces three common bugs:

  1. Illegal State Mutations: Pressing dispense twice or inserting coins during Dispensing corrupts balance.
  2. Trapped Change: Dispensing a $1.50 item when the user inserted $2.00 fails mid-way if the machine lacks $0.50 in coins, stranding inventory or money.
  3. Rigid Extensions: Adding NFC/card payments forces edits across every if-else block.
Vending State Machine

Idle -> HasMoney -> Dispensing -> Idle / SoldOut

insertMoney(amt)selectItem (valid + change…dispense + return changeIDLEbalance = 0HAS_MONEYaccepts coins / selectDISPENSINGverify change + ejectSOLD_OUTall slots qty == 0

Each State implementation handles only valid actions for its mode and rejects or refunds invalid transitions.

Engineering Decision Framework
Problem
How to implement Design a Vending Machine Using the State Pattern (LLD) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, delegate every user action to an explicit State object so invalid transitions fail cleanly, and validate change availability before committing inventory dispense.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Vending Machine Using the State Pattern (LLD) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why monolithic if-else switching breaks).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

A naive VendingMachine stores String state and branches inside every method:

  • Zero Isolation: Adding a Maintenance or CardTap state requires auditing every method in VendingMachine.
  • Non-Atomic Dispense: Decrementing slot.qty before checking if the coin tray can make change leaves the machine inconsistent.
Design Trade-Off

Naive solution (and why monolithic if-else switching breaks)

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: GoF State Pattern + Atomic Change Validator.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Clean LLD delegates behavior to concrete VendingState classes:

  • Zero if-else in Context: VendingMachine forwards insertMoney, selectItem, dispense, and cancel directly to self.state.
  • Atomic Change Check: In HasMoneyState.select_item(), verify qty > 0, balance >= price, AND coin_inventory.can_make_change(balance - price) before transitioning to DispensingState; otherwise refund and revert to IdleState.
  • Payment Strategy: Abstract PaymentMethod (CoinAcceptor, CardReader) so new payment rails plug in cleanly.
Atomic Purchase & Rollback

Item Selection, Change Verification & Safe Dispense

CustomerVendingMachineHasMoneyStateInventory & Coins1. insertMoney($2.00)2. selectItem('A1', price=$1.50)3. Check qty>0 & change($0.50) OK4. Transition -> DispensingState5. Eject item + $0.50 change ->Idle

Verifying change availability before decrementing inventory guarantees atomic purchase or full refund.

class HasMoneyState(VendingState):
    def select_item(self, machine, code: str):
        item = machine.inventory.get(code)
        if machine.balance >= item.price:
            machine.set_state(machine.dispensing_state)
public class HasMoneyState implements VendingState {
    public void selectItem(VendingMachine m, String code) {
        Item item = m.getInventory().get(code);
        if (m.getBalance() >= item.price()) m.setState(m.getDispensingState());
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where the State Pattern applies in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Explicit State objects power complex lifecycle-driven systems beyond vending machines:

  • Order & Payment Lifecycles: CREATED -> AUTHORIZED -> CAPTURED -> REFUNDED with strict transition guards.
  • Workflow & Saga Orchestrators: Ensuring compensating transactions only run from valid intermediate states.
  • Connection & Protocol Drivers: Modeling TCP/WebSocket/gRPC channel states cleanly.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why should HasMoneyState verify coin inventory for change before transitioning to DispensingState?

Recommended Learning Flow