Design a vending machine
medium 90 minBuild a vending machine around its money: coins in escrow, change from a limited box, stock by place, a slow motor that can jam, and several events that arrive at once.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
A vending machine is a shop without a person. It takes money, checks, gives a product, gives change, and must be right when nobody is there to say sorry.
Underneath it is a small transaction over two things that cannot be rolled back easily: coins that have fallen and cans that have fallen. The trick is to do everything that can fail before either of them moves.
It is also the standard example for state machines. That half is on the State pattern page. This page owns money, change, stock and races.
Why it exists
The domain is known to everyone, so the interview reaches design within a minute.
It hides a real algorithm (change from a limited stock), a real protocol (hold, act, take) and a real race (the three seconds of the motor) behind a toy.
Every checkout, cash machine and ticket counter has the same order of steps. Whoever understands the hatch understands them.
A short history
1st century
Hero of Alexandria describes a machine that gives holy water or wine for a coin: the coin falls on a pan, a lever opens a valve.
1883
Percival Everitt invents a machine that sells postcards. Such machines soon stand in railway stations and post offices in London.
1895
The first automat, Quisisana, opens in Berlin: a restaurant with coin operated hatches.
1902
On 12 June Horn and Hardart open the first automat in the United States, in Philadelphia.
1994
The book Design Patterns describes State, the pattern most people name first for this machine.
Words to know
- Escrow
- Coins inserted but not taken yet. They belong to the customer.
- Coin box
- The machine's own coins, counted by kind.
- Float
- Coins left in the box on purpose, for change.
- Change making
- Finding coins that add up to an amount.
- Greedy
- Always the largest coin that fits. Fast, not always possible.
- Claim
- Look and take one piece in one step.
- Settle
- Move coins between owners after the product is out.
- Authorise and capture
- Reserve money on a card, take it later.
- Idempotent
- Doing it twice has the result of doing it once.
- Journal
- A record written before the act, used after a crash.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Coins in. Each coin lies in escrow and still belongs to the customer
Understand it
Start here
The deckchair hatch
At the seaside, Asha rents deckchairs from a wooden hatch. A chair costs 70 cents. There is a tray for the customer's coins and a box with Asha's own. Watch when a coin moves from the tray to the box: that moment is the whole problem.
Tray before box. Ask for change before the chair. Then every refusal is cheap.
What an interviewer looks for here
Money as coins
Whole cents, and a count of each coin. A sum cannot be paid out.
Whose is it?
Escrow is the customer's, the box is the owner's. One method moves coins between them.
The order of steps
Check, plan change, claim, drop, settle. Each refusal costs nothing.
The slow motor
Three seconds in which a second press, a coin or a cancel may arrive.
Questions
Six questions, and what each answer changes
| Ask | If the answer is | Then |
|---|---|---|
| Coins only, or notes and cards? | Coins and notes | Notes are values of the same enum that the box cannot pay out |
| Must it give change? | Yes | The box is counted by coin, and the search uses the stock |
| What if it cannot? | Refuse | NoChange before the motor runs. A lamp says exact money only |
| Choose first or pay first? | Either | buy looks at what is inserted when it is called |
| Can the product fail to fall? | Yes | The motor may report a jam. The claim is put back |
| Who else touches it? | A technician, an app | A lock, a busy flag, and later reservations |
One purchase
Design, first try
The design most people draw first
The design to avoid: beautiful states around a bare number
1/4Money is a number
insertMoney(100) adds 100 to a balance. Which coins came in is forgotten. So nobody can say whether 30 cents can be given back.
usesimplementshas (lives on)owns (dies together)
class Machine: def __init__(self): self.balance, self.quantity, self.price = 0, 1, 70 def insert(self, cents): self.balance += cents def select(self): if self.balance < self.price: return "more money" self.quantity -= 1 # it has not even fallen yet change = self.balance - self.price self.balance = 0 return f"here is your juice and {change} cents" # from where?m = Machine()m.insert(100)print(m.select())m.insert(100)print(m.select(), "| left:", m.quantity)left: -1.Design, better
The design to reach
The design to reach: whose coins are these?
1/5Coins, not a number
The customer's coins lie in escrow, as a list. They are not ours until something falls. cancel gives back the very same coins.
owns (dies together)useshas (lives on)depends on
What each class owns
| Class | Knows | Does | Does not know |
|---|---|---|---|
VendingMachine | Escrow, busy, the order of steps | insert, cancel, buy | How change is found |
CoinBox | How many of each coin | Plans and settles | Prices, products |
make_change | Nothing | Fewest coins from a stock | Whose coins they are |
Inventory | Products, counts, broken places | Claims one, puts it back | Money |
Motor | The hardware | Drops, or reports a jam | Everything else |
Change
Why greedy is not enough
For many real coin systems, the greedy rule (largest coin first) gives the fewest coins if you have enough of each. A machine has not. Take 30 cents, one quarter and four dimes: greedy takes the quarter, needs 5, and gives up. Three dimes were there.
| Amount | Stock | Greedy | Best |
|---|---|---|---|
| 30 | 25 x 1, 10 x 4 | 25, then stuck | 10 + 10 + 10 |
| 40 | 25 x 1, 10 x 4, 5 x 1 | 25 + 10 + 5 | The same |
| 30 | 25 x 1, 10 x 1 | 25, then stuck | Impossible: refuse |
| 6 | coins 1, 3, 4 without limit | 4 + 1 + 1 | 3 + 3 |
| 0 | Anything | Nothing | Nothing: a plan with no coins |
Building sums, coin by coin: stock 25 x 1 and 10 x 4, amount 30
Work
How do you find the change?
BreaksPrint the difference
- How
change = balance - price- Limit
- A number is not a coin. The machine may not have it.
- Choose when
- Never.
WorksGreedy over the stock
- How
- Largest first, at most what is there.
- Limit
- Refuses sales it could make, as with 25 and four 10s.
- Choose when
- If you say so, and the box is always well filled.
StrongSearch with the stock
- How
- Dynamic programming: for each sum, the shortest list of coins.
- Limit
- Ten more lines. Needs an upper bound for the amount.
- Choose when
- Here. Amounts are small.
States
The moods, derived
The same four moods, without a state field
What each action does in each mood
| Action | Idle | HasMoney | Dispensing |
|---|---|---|---|
insert | Coin into escrow | Coin into escrow | Busy: coin falls through |
buy | NotEnough(price) | Sale, or a refusal | Busy |
cancel | Empty list | All coins back | Busy |
ifs. The State pattern page shows the version with a class for each column and says when it pays: many moods, different answers.The hard part
Three seconds
The motor turns for about three seconds. In this time a child presses the button again, somebody throws another coin, and the customer presses cancel. All three look at the same escrow.
Press twice without a busy flag
How do you protect the three seconds?
BreaksHold the lock while the motor turns
- How
- One big
with lockaroundbuy. - Limit
- Every other thread waits for three seconds: no refusal, no display, no technician. And the second press is queued, then sells again if there is money.
- Choose when
- Never around hardware.
WorksEmpty the escrow first
- How
- Take the coins, drop, give back on a jam.
- Limit
- A crash in between eats the money in silence.
- Choose when
- With a journal.
StrongA busy flag under a short lock
- How
- Lock: check and claim, set busy. Unlock: drop. Lock: settle.
- Limit
- Two short critical sections, and the flag must be cleared on every known result.
- Choose when
- Here.
Summary
The whole topic in one minute.
Coins are a list in escrow until something has fallen. Change is planned from the box and the escrow with a search, before the product. The order is check, plan, claim, drop, settle, and each refusal moves nothing.
A short lock covers the decisions, a busy flag covers the motor. A known jam puts everything back, an unknown result stops the machine. Cards fit the same shape: hold, take, release.
- Whole cents, and coins by kind: a sum cannot be paid out.
- Escrow belongs to the customer until something has fallen.
- Plan the change before the product, with the stock you have.
- Order: check, plan, claim, drop, settle.
- No lock while the motor turns: a busy flag says no at once.
- An unknown result stops the machine. A known jam gives everything back.
Sources
- Wikipedia: Vending machine
- Wikipedia: Automat
- Wikipedia: Change-making problem
- Wikipedia: Multidrop bus (MDB/ICP)
- Stripe: place a hold on a payment method
- Stripe: idempotent requests
- Square: delayed capture
- Square: working with monetary amounts
- Odoo: cash rounding
- SQLite: atomic commit
- PostgreSQL: SELECT, the locking clause
- Python: decimal, why binary floats are inexact
- Java SE 21 API: ReentrantReadWriteLock