System design interview: design a vending machine

"Design a vending machine" is a state machine question in disguise. You model states such as idle, collecting money and dispensing, define what each input does in each state, and handle money correctly: give exact change from the coins actually inside the machine, or refuse the sale and refund. A larger version adds card payments and a backend that tracks stock and faults across a fleet of machines.

By Published 8 min read

1. Clarify the requirements

Like the parking lot, this prompt can be an object-oriented exercise for one machine or a system for many. Start with the single machine and offer the fleet version if time remains. The interview framework explains how to pace that switch.

  • Functional: show products and prices per slot; accept coins (and perhaps notes and cards); let the user select a product; dispense it and return change; cancel and refund before a product is dispensed; report sold-out slots.
  • Non-functional: never keep money without dispensing or refunding; never dispense without payment; handle a jammed product; prices and products configurable without new code.
  • Ask about: which coins and notes are accepted, whether exact change only is acceptable when coins run low, card payments, and whether the machine is connected to a network.

2. Estimate the scale

Scale if the interviewer extends it to a fleet (assumed figures)
QuantityAssumptionResult
Machines50,000 across many sitesthe base for the fleet numbers
Telemetryone status report every 5 minutesabout 170 reports a second
Sales60 per machine a day3 million a day, about 35 a second
Single machineone customer at a timeno concurrency inside the machine beyond hardware events
Scale if the interviewer extends it to a fleet (assumed figures). Scroll sideways on a small screen.

Throughput is not the problem here. The interview is about modeling states, money and failure handling, and, for a fleet, about machines that are offline much of the time.

3. Define the interface

Machine.insert(coin)        -> credit updated, or coin rejected
Machine.select(slot)        -> vend + change | insert more | sold out | exact change only
Machine.cancel()            -> refund of the coins inserted
Machine.restock(slot, n)    (service mode)

POST /v1/machines/{id}/telemetry   { sales[], stock{}, coinLevels{}, faults[], sentAt }
GET  /v1/machines/{id}/config      -> { prices{}, products{}, version }
Inputs to one machine, and the fleet service calls

4. Sketch the states and classes

What each input does in each state
Stateinsert coinselect slotcancel
IDLEadd credit, go to HAS_CREDITshow price, staynothing to refund
HAS_CREDITadd creditif enough credit and stock and change: DISPENSING; else show messagerefund inserted coins, go to IDLE
DISPENSINGreject (return coin)ignoreignore (too late)
OUT_OF_SERVICErejectshow "out of service"refund any credit
What each input does in each state. Scroll sideways on a small screen.
  • `VendingMachine` holds the state, current credit, coin inventory and slots, and applies the transition table.
  • `Slot` has a product, price and count.
  • `CoinInventory` knows how many of each coin are held and can compute change.
  • `PaymentMethod` is an interface with cash and card implementations, so adding cards does not touch the state logic.
  • `Dispenser` wraps the motor and drop sensor and reports success or a jam.

The State pattern (one class per state with methods for each input) is a fine answer if the interviewer likes patterns. A transition table plus a small switch is shorter and easier to test. Name both and pick one.

5. The core logic: change you can actually give

The classic trap: with coins of 25, 10 and 5 cents and no nickels left, 30 cents of change is possible (three dimes), but a greedy algorithm takes a quarter first and then gets stuck. With a limited supply of each coin, use a small dynamic program that finds the fewest coins or reports that exact change is impossible, and run it before dispensing.

def make_change(amount, stock):
    """Fewest coins for `amount` (cents) using at most stock[c] coins of each
    denomination c. Returns {coin: count} or None if exact change is impossible."""
    INF = float("inf")
    best = [0] + [INF] * amount          # best[a] = fewest coins to make a
    used = [None] * (amount + 1)         # used[a] = coin counts for best[a]
    used[0] = {}
    for coin, count in stock.items():    # bounded knapsack, one coin type at a time
        for a in range(amount, -1, -1):
            for k in range(1, count + 1):
                prev = a - k * coin
                if prev < 0:
                    break
                if best[prev] + k < best[a]:
                    best[a] = best[prev] + k
                    used[a] = {**used[prev], coin: used[prev].get(coin, 0) + k}
    return used[amount] if best[amount] < INF else None


class VendingMachine:
    def __init__(self, prices, coins):
        self.prices = dict(prices)       # slot -> price in cents
        self.items = {s: 0 for s in prices}
        self.coins = dict(coins)         # coin value in cents -> count held
        self.state, self.credit, self.inserted = "IDLE", 0, {}

    def insert(self, coin):
        if coin not in self.coins:
            raise ValueError("coin rejected")
        self.state = "HAS_CREDIT"
        self.credit += coin
        self.inserted[coin] = self.inserted.get(coin, 0) + 1

    def select(self, slot):
        if self.state != "HAS_CREDIT":
            return ("insert money first", None)
        if self.items.get(slot, 0) == 0:
            return ("sold out", None)
        price = self.prices[slot]
        if self.credit < price:
            return ("insert more", price - self.credit)
        pool = {c: self.coins[c] + self.inserted.get(c, 0) for c in self.coins}
        change = make_change(self.credit - price, pool)
        if change is None:
            return ("exact change only", None)   # keep credit; user may cancel
        for c, n in self.inserted.items():
            self.coins[c] += n
        for c, n in change.items():
            self.coins[c] -= n
        self.items[slot] -= 1
        self.state, self.credit, self.inserted = "IDLE", 0, {}
        return ("vend", change)

    def cancel(self):
        refund, self.inserted = self.inserted, {}
        self.state, self.credit = "IDLE", 0
        return refund
Bounded change making and a minimal machine. The change function was checked against brute force on random coin sets and supplies.
  • Inserted coins count toward change. The pool includes coins the customer just put in, which matches how real coin mechanisms recycle coins.
  • Refund returns the same coins. Cancel gives back exactly what was inserted, which is always possible and avoids a second change calculation.
  • Check before you act. Stock, credit and change are all verified before the machine commits; only then do counts change. In a real machine the dispense step comes next and can still fail (see section 8).
  • Cost. The change table is amount x total coins, tiny for amounts of a few dollars, so the dynamic program runs instantly on a machine's controller.

6. The architecture for a fleet

  1. Hardware
    • Coin and note mechanisms
    • Card reader
    • Keypad and display
    • Motors and drop sensor
  2. Machine
    • Controller (state machine)
    • Local event log
    • Config cache
  3. Connectivity
    • Cellular or Wi-Fi modem
    • Batched upload with retry
  4. Backend
    • Telemetry ingestion
    • Fleet state store
    • Restock planner
    • Fault alerts
    • Payment settlement
Machine controller, connectivity and the fleet backend. Inside each machine, a controller runs the state machine and talks to the coin mechanism, note reader, card reader, keypad, display and dispenser motors with drop sensors. It stores sales, stock and fault events locally. A cellular or Wi-Fi modem sends batched telemetry to a fleet ingestion service when connected and fetches price and product configuration. The backend stores machine state, plans restocking routes from stock levels, alerts technicians on faults, and settles card payments through a payment provider.

The machine must sell with no connection at all, so every decision a customer waits for happens locally. The backend is for operations: knowing what to restock, which machine is jammed and how much cash to collect.

7. Adding card payments

  1. AuthorizeWhen a card is tapped, the reader asks the payment provider to authorize a maximum amount (for example the highest price in the machine), which needs a connection.
  2. Select and dispenseThe customer chooses; the machine dispenses and waits for the drop sensor to confirm.
  3. Capture or voidOn success, capture the actual price; on a jam or cancel, void the authorization so no money moves.
  4. Offline fallbackSome operators allow small offline card sales that are submitted later, accepting a little risk; others disable cards while offline. It is a business decision to raise, not assume.

8. What breaks, and what you do about it

Failure modes worth naming
FailureEffectMitigation
Product jams in the spiralCustomer paid, got nothingDrop sensor confirms delivery; on failure try once more, then refund (cash) or void (card) and mark the slot faulty
Change tubes run lowSales lost or wrong changeExact-change-only message; telemetry alerts before coins run out
Power cut mid-saleCredit lost from memoryPersist credit and state to non-volatile storage on every change; resume or refund on restart
Counterfeit or foreign coinsLossesCoin validator rejects them; the software never trusts an unvalidated coin
No network for daysBackend view goes staleLocal log keeps everything; upload in order when connected; restock plans use last known stock plus sales estimates
Failure modes worth naming. Scroll sideways on a small screen.

9. Trade-offs to discuss

  • State pattern or transition table. Classes per state are easy to extend with behavior; a table is compact and easy to test exhaustively.
  • Fewest coins or keep small coins. Minimizing coins returned can drain the supply of large coins; some operators prefer to keep certain coins in the machine.
  • Block a sale or risk wrong change. Refusing a sale when exact change is impossible loses revenue but never cheats a customer.
  • Offline cards. Accepting cards offline sells more but risks declined payments later.

10. How to talk through it in the interview

Fictional example

Catching the change-making trap
Interviewer
Price is 70 cents, the customer inserts a dollar, and the machine holds one quarter and three dimes. What happens?
Candidate
Change is 30 cents. A greedy approach would give the quarter and then need a nickel it does not have, and might wrongly refuse the sale. I run a small bounded change-making check over the coins on hand, which finds three dimes. If no combination worked, I would show exact change only and keep the credit so the customer can choose something else or cancel.
Interviewer
And if the product then jams?
Candidate
The drop sensor never fires, so the machine retries once, then returns the customer's coins and marks the slot out of service in its next telemetry report.
  • Draw the state table before any code.
  • Mention integer cents and the change-making trap; both are frequent follow-ups.
  • End with jams and power cuts to show you think about physical failures.

If the interviewer wants a scheduling problem instead of a money one, the elevator system is the usual next step in this family of prompts.

Practicing this design with Natively

This is a prompt where a small coding slip, such as greedy change, costs more than a weak diagram, so rehearse writing the code while explaining it. Natively can sit in on the practice call on your Mac or Windows computer, transcribing both voices and suggesting points for the latest question if you ask, such as power-cut recovery. For the coding part, a screenshot of your function lets it give a code hint in practice. Review the session notes afterwards to see whether you named the state machine before writing code.

Questions people ask

How do you design a vending machine in an object-oriented interview?

Model it as a finite state machine with states such as idle, has credit, dispensing and out of service, and define what each input (coin, selection, cancel) does in each state. Add classes for slots, the coin inventory, payment methods and the dispenser, and keep all money in integer cents.

Why does greedy change making fail in a vending machine?

The machine holds a limited number of each coin. With no nickels left, 30 cents can still be paid as three dimes, but a greedy algorithm takes a quarter first and gets stuck. A small bounded change-making routine over the coins actually held finds the answer or proves none exists.

What should a vending machine do if it cannot make change?

Check before dispensing. If exact change is impossible, show an exact-change message and keep the customer's credit so they can pick another item or cancel and get their own coins back. Telemetry should warn the operator before the coin supply runs that low.

How does a vending machine handle a product that gets stuck?

A drop sensor confirms that the product actually fell. If it does not, the machine retries once, then refunds the coins or voids the card authorization and marks the slot faulty, reporting it in the next telemetry batch so a technician can fix it.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP