Skip to content
Vending Machine System Design: 5 Questions Before Coding, State Machine, Anti-Overselling & Power-Failure Recovery

Vending Machine System Design: 5 Questions Before Coding, State Machine, Anti-Overselling & Power-Failure Recovery

This article provides a comprehensive system design for a vending machine, covering requirement clarification, state machine modeling, concurrency control for overselling prevention, payment idempotency, hardware fault tolerance with MQTT and WAL-based power failure recovery, and engineering best practices for offline sales and reconciliation.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Introduction

The classic interview question "Design a vending machine system" appears simple but is a hidden killer: it tests whether you can anticipate where the system will fail — overselling, lost orders, paid-but-not-dispensed, stuck items, power loss causing account mismatches. This article delivers a complete, battle-tested answer covering requirement clarification, state machine modeling, three-tier concurrency control, payment idempotency, hardware fault tolerance, and power-failure self-healing.

1. Requirement Clarification: Ask 5 Questions First

Before writing any code, clarify:

Standalone embedded or cloud platform for 10k+ devices? Determines local state machine + DB vs distributed + reconciliation.

Payment methods: cash, QR, card, face? Cash needs change module and hardware protocol; QR involves async callbacks and idempotency.

Concurrency level? QPS? Standalone is low-concurrency strong consistency, not flash sale; high volume needs sharding and peak shaving.

Will hardware jam, lose power, or drop packets? Are sensors present? Must assume yes — this decides the compensation loop and is the soul of the problem.

Support offline sales? Biggest pitfall and biggest bonus (detailed later).

Prioritize into P0 (browse, pay, dispense, change, cancel), P1 (restock, inventory, sold-out alert, fault alarm), P2 (remote monitoring, reports, dynamic pricing, loyalty). Non-functional requirements that separate P6/P7: no oversell, money-goods consistency, idempotent payment callbacks, pluggable payment, offline degradation .

2. Overall Architecture: Edge Guarantees "No Wrong Dispense", Cloud Guarantees "Accounts Match"

For "10k devices, mainly QR pay, some cash, weak network", architecture splits into four domains: product/inventory, order/transaction, payment, device fulfillment. Key decision: devices do not call business APIs directly; they go through an IoT gateway with persistent connections because NAT traversal, weak-network reconnect, and guaranteed delivery (QoS) cannot be handled by HTTP short connections. Responsibility split: edge ensures "no wrong dispense" (local state machine + local inventory + power-failure self-healing), cloud ensures "accounts match" (reconciliation, compensation, operations).

3. Core: State Machine Design

A vending machine is a state machine that collects money . Using if (state == IDLE) ... else if ... leads to spaghetti code and illegal transitions like "dispense without payment".

3.1 State Transition Diagram

State transition diagram
State transition diagram

The state machine makes "what can be done in each state" explicit : illegal transitions are rejected immediately, eliminating "Schrödinger states".

3.2 State Pattern Implementation (Interview-Ready)

/** State interface: default methods catch "illegal operations", fail-fast */
public interface VendingState {
    default void insertMoney(VendingMachine m, int amount) {
        throw new IllegalStateException("Current state does not allow coin insertion");
    }
    default void selectProduct(VendingMachine m, String code) {
        throw new IllegalStateException("Please insert money first");
    }
    default void cancel(VendingMachine m) {
        throw new IllegalStateException("Current state does not support refund");
    }
}

/** Context: holds state reference, delegates all behavior to state object */
public class VendingMachine {
    private volatile VendingState state = new IdleState(); // volatile for multi-thread visibility

    public void selectProduct(String code) { state.selectProduct(this, code); }
    public void changeState(VendingState s) { this.state = s; }
}

/** HasMoney state: core business logic */
public class HasMoneyState implements VendingState {
    @Override
    public void selectProduct(VendingMachine m, String code) {
        Slot slot = m.getSlot(code);
        if (slot == null || !slot.hasStock()) { m.alert("Sold out, auto refund"); m.refundAll(); return; }
        if (m.getBalance() < slot.getProduct().getPrice()) { m.alert("Insufficient balance"); return; }

        m.deduct(slot.getProduct().getPrice()); // deduct first
        m.changeState(new DispensingState());
        if (slot.tryDispense()) { // CAS grab inventory
            m.dispense(slot.getProduct()); // trigger hardware dispense
            m.giveChange(); // give change
            m.changeState(slot.hasStock() ? new IdleState() : new SoldOutState());
        } else {
            m.rollback(slot.getProduct().getPrice()); // dispense failed -> rollback refund
            m.changeState(new HasMoneyState());
        }
    }

    @Override
    public void cancel(VendingMachine m) {
        m.refund(m.getBalance());
        m.changeState(new IdleState());
    }
}
Technical highlights: default methods catch illegal operations + volatile state delegation, consolidating transition rules at class level. Adding a "fault state" only requires a new class without modifying old code, perfectly adhering to Open/Closed Principle. Each state's on() method is a natural unit test case.

3.3 Advanced: Table-Driven State Machine

For more states with audit/replay needs, configure transition rules — add a state by adding one line :

public enum VmState {
    IDLE, SELECTED, PAYING, DISPENSING, DISPENSED, REFUNDING, FAULT;

    private static final Map<VmState, Map<VmEvent, VmState>> FSM = new EnumMap<>(VmState.class);

    private static void rule(VmState f, VmEvent e, VmState t) {
        FSM.computeIfAbsent(f, k -> new EnumMap<>(VmEvent.class)).put(e, t);
    }
    static {
        rule(IDLE, SELECT, SELECTED);         rule(SELECTED, PAY, PAYING);
        rule(SELECTED, CANCEL, IDLE);         rule(PAYING, PAY_SUCCESS, DISPENSING);
        rule(PAYING, PAY_TIMEOUT, REFUNDING); rule(DISPENSING, DISPATCH_ACK, DISPENSED);
        rule(DISPENSING, DISPATCH_FAIL, REFUNDING);
        for (VmState s : values()) rule(s, HARDWARE_ERROR, FAULT); // any state can fuse
    }
    public VmState transit(VmEvent e) {
        VmState n = FSM.getOrDefault(this, Map.of()).get(e);
        if (n == null) throw new IllegalTransitionException(this + "-" + e + "->?");
        return n;
    }
}

For extremely complex states, use a state machine engine (Spring StateMachine / Cola) instead of building your own.

4. Concurrency Anti-Oversell: Two Users Buy the Last Coke

Three solutions by deployment mode:

AtomicInteger + CAS spin — Standalone in-memory inventory. Lock-free, non-blocking, best performance under low contention. Fails in distributed.

DB conditional update / optimistic lock — Standalone DB, small-medium concurrency. Simple, naturally atomic. Hot row contention requires retries.

Redis Lua atomic pre-deduct + DB fallback — Distributed, high concurrency. Handles traffic spikes. Must handle cache-DB consistency.

4.1 Standalone: CAS Lock-Free Deduction

public class Slot {
    private final AtomicInteger stock; // inventory uses atomic class

    public boolean tryDispense() {
        while (true) {
            int cur = stock.get();
            if (cur <= 0) return false; // sold out
            if (stock.compareAndSet(cur, cur - 1)) { // two people grab last bottle, only one succeeds
                return true;
            }
        }
    }
}
Why not synchronized ? Both work for standalone, but CAS doesn't block threads under low contention; more importantly — JVM locks fail completely in distributed deployment , so cultivating CAS/conditional-update thinking is the correct approach.

4.2 Database: Single SQL Prevents Oversell

Do not query-then-deduct (check and deduct not atomic, guaranteed oversell). Put condition directly in SQL, using InnoDB row lock + affected rows judgment:

@Update("UPDATE slot SET stock = stock - 1, version = version + 1, gmt_modified = now() " +
        "WHERE id = #{slotId} AND stock > 0 AND version = #{version} AND machine_id = #{machineId}")
int deduct(@Param("slotId") Long slotId,
           @Param("version") Integer version,
           @Param("machineId") Long machineId);
@Transactional(rollbackFor = Exception.class)
public void deductWithRetry(Long slotId, int qty) {
    for (int i = 0; i < 3; i++) { // spin retry, throughput better than pessimistic lock
        Slot slot = slotMapper.selectById(slotId);
        int rows = slotMapper.deduct(slotId, qty, slot.getVersion());
        if (rows > 0) return; // deduction succeeded
        log.warn("Inventory contention conflict, retry #{}", i + 1);
    }
    throw new BizException("Too fast, inventory sold out");
}
Pitfall alert: Do not use select ... for update pessimistic lock for this scenario — long transactions + deadlocks await. Also, the real inventory carrier is the slot (货道), not SKU — one machine may have 6 slots for the same Coke; wrong granularity breaks dispense logic.

4.3 High Concurrency: Pre-allocate + Redis Lua

E-commerce-style vending machines (mobile order, in-store pickup) suit "freeze/confirm" two-phase:

// Pre-allocate: atomic SQL, stock - locked_stock > 0 allows lock
@Transactional
public boolean lockStock(String slotId, String orderNo) {
    int rows = jdbc.update("""
        UPDATE inventory SET locked_stock = locked_stock + 1
        WHERE slot_id = ? AND stock - locked_stock > 0
        """, slotId);
    if (rows == 0) return false;
    jdbc.update("INSERT INTO stock_lock(slot_id, order_no, status) VALUES (?, ?, 'LOCKED')",
                slotId, orderNo);
    return true;
}

// Payment success confirms deduction; payment timeout releases pre-allocation
@Transactional
public void confirmStock(String slotId, String orderNo) {
    jdbc.update("UPDATE inventory SET stock = stock - 1, locked_stock = locked_stock - 1 WHERE slot_id = ?", slotId);
    jdbc.update("UPDATE stock_lock SET status = 'CONFIRMED' WHERE order_no = ?", orderNo);
}

Traffic spikes hit Redis first; deduction check + execution must use Lua for atomicity:

-- KEYS[1] = inventory key, ARGV[1] = deduct quantity
local stock = redis.call('GET', KEYS[1])
if not stock or tonumber(stock) < tonumber(ARGV[1]) then
    return -1 -- insufficient stock
end
return redis.call('DECRBY', KEYS[1], ARGV[1])

Java side (Spring Data Redis):

private final DefaultRedisScript<Long> preDeductScript = new DefaultRedisScript<>(PRE_DEDUCT_LUA, Long.class);

public boolean preDeduct(String machineId, String skuId) {
    String key = "stock:" + machineId + ":" + skuId;
    Long result = redisTemplate.execute(preDeductScript, Collections.singletonList(key), "1");
    return Long.valueOf(1L).equals(result);
}

Two accompanying pitfalls: Redis and DB inventory may diverge (scheduled reconciliation + restock events rebuild cache); hot single key for popular items (segmented inventory / local cache / Sentinel rate limiting).

5. Payment Flow: Idempotency Trio + Local Message Table

Money is a red line. Payment callbacks may repeat N times, weak network may lose callbacks, users may double-click — every link must be idempotent.

5.1 Core Transaction Sequence

Payment sequence diagram
Payment sequence diagram

In one sentence: Transaction synchronous, fulfillment asynchronous, device commands idempotent.

5.2 Payment Callback Handler (Ready to Recite)

@Transactional(rollbackFor = Exception.class)
public void onPayCallback(PayNotifyDTO notify) {
    // ① Verify signature + amount, prevent "pay 1 cent for iPhone"
    checkAmountAndSign(notify);

    // ② Idempotency: payment serial unique index, duplicate callback returns directly
    int inserted = payNotifyLogMapper.insertIgnore(notify.getTradeNo(), notify.getOrderNo());
    if (inserted == 0) { log.warn("Duplicate callback tradeNo={}", notify.getTradeNo()); return; }

    // ③ Order status CAS advance, prevent duplicate transition
    int updated = orderMapper.casStatus(notify.getOrderNo(),
            OrderStatus.WAIT_PAY.name(), OrderStatus.PAID.name());
    if (updated == 0) return;

    // ④ Same transaction write local message table (Transactional Outbox), guarantee subsequent dispense attempt
    outboxMapper.insert(new OutboxMessage(notify.getOrderNo(), "DISPATCH"));
}

Corresponding order status CAS:

@Update("UPDATE vm_order SET status = #{toStatus}, update_time = NOW() " +
        "WHERE order_no = #{orderNo} AND status = #{fromStatus}")
int casStatus(@Param("orderNo") String orderNo,
              @Param("fromStatus") String fromStatus,
              @Param("toStatus") String toStatus);
Technical highlight: Payment trio — unique index anti-duplicate + state machine CAS + local message table (Transactional Outbox). Payment success never directly calls device service synchronously (network jitter loses orders); instead, write local message table first, then async deliver via MQ, backed by hourly reconciliation job.

Three easily missed details:

Order must store price snapshot price_snapshot to prevent frontend price tampering;

Place order with RocketMQ delay message, 15 min unpaid auto-close releases pre-allocated inventory ;

Illegal state transitions log alarm instead of throwing exception to avoid infinite MQ retries.

6. Dispensing Fulfillment: Dealing with "Unreliable Hardware"

The biggest difference from pure software design: must assume motors jam, sensors time out, network breaks, machine loses power .

6.1 Dispense Command Idempotency — Never Double Dispense

Retries are routine, but retries must not give user two bottles for one payment:

public void dispatch(Order order) {
    String commandId = "DISPATCH_" + order.getOrderNo();
    if (commandMapper.existsById(commandId)) return; // one order generates one command
    commandMapper.insert(new Command(commandId, order.getOrderNo(),
            order.getMachineId(), order.getSkuId(), 1));
    mqttClient.publish("vm/" + order.getMachineId() + "/cmd",
            JsonUtil.toJson(command), MqttQos.AT_LEAST_ONCE); // QoS1 at least once
}

Edge side deduplicates by (orderId, seq); retries for already ACKed commands return success immediately. Dispense result relies on photoelectric/infrared/gravity sensor acknowledgment , not trusting motor "turned means dispensed". Failure path: timeout retry 2 times → still fail enters refund flow + FAULT alarm → ops manual fallback .

Hardware layer uses Strategy pattern to abstract vendor differences, zero intrusion for new vendors:

public interface ActuatorDriver {
    boolean deliver(String machineId, String slot, String cmdNo); // cmdNo = command idempotency key
    MachineHealth health(String machineId);
}

6.2 Killer Bonus: WAL + Reconciler Power-Failure Self-Healing

90% of candidates miss this. Vending machines are unattended; power loss restart is normal — in-memory state vanishes on power loss :

public synchronized void fire(long orderId, VmEvent e) { // single-machine serial, naturally eliminates races
    VmState from = state, to = from.transit(e); // ① validate legal transition
    wal.append(orderId, from, e, to);           // ② persist first (replayable after power loss)
    try { onEnter(orderId, to); state = to; }   // ③ side effects ④ update memory state
    catch (Exception ex) { state = FAULT; throw ex; } // fuse, wait for Reconciler
}

On restart, Reconciler periodically scans unfinished orders, does not guess, actively queries :

@Scheduled(fixedDelay = 30_000)
public void reconcile() {
    for (Order o : repo.findUnfinished(machineId)) {
        switch (o.state()) {
            // Don't just wait for callback, actively query payment order
            case PAYING -> pay.query(o.payNo())
                    .ifPresent(r -> fire(o.id(), r.paid() ? PAY_SUCCESS : PAY_FAIL));
            // Directly ask hardware "did you actually dispense?"
            case DISPENSING -> hw.queryCmd(o.id())
                    .ifPresent(a -> fire(o.id(), a.ok() ? DISPATCH_ACK : DISPATCH_FAIL));
            case REFUNDING -> pay.queryRefund(o.payNo()).ifPresent(r -> fire(o.id(), REFUND_DONE));
        }
    }
}

Interviewer follow-up: "What if dispensed but ACK lost causing wrong refund?" Standard answer: Hardware deduplication + Reconciler active verification is first line of defense; real discrepancies resolved by T+1 reconciliation generating difference tickets for loss recovery — standard fund system safety net.

6.3 Serializing Operations on Same Machine

Multiple terminals operating same machine (user buying, backend restocking): two solutions:

Fine-grained lock : lockKey = "vending:order:" + deviceId, Redisson shards by device, throughput an order of magnitude higher than global lock;

MQ ordered consumption (better) : messages sharded by machineId, same machine events go to same queue consumed single-threaded, naturally serial, no distributed lock needed:

rocketMQTemplate.syncSendOrderly("DELIVER_TOPIC", msg, machineId);

7. Change Algorithm: Greedy Works, But Know Boundaries

Cash scenarios need change. Coin denominations {100, 50, 10, 5, 1} (cents), greedy from largest:

public List<Integer> giveChange(int change, Map<Integer, Integer> cashBox) {
    List<Integer> result = new ArrayList<>();
    int[] denominations = {100, 50, 10, 5, 1};
    for (int d : denominations) {
        while (change >= d && cashBox.getOrDefault(d, 0) > 0) {
            change -= d;
            cashBox.merge(d, -1, Integer::sum);
            result.add(d);
        }
    }
    if (change != 0) throw new IllegalStateException("Insufficient change, need refund or switch machine");
    return result;
}
Two pitfalls: ① Greedy only guarantees optimal for "standard denomination systems"; if denominations are {1,3,4} making 6, need dynamic programming; ② Validate and freeze coin box balance before order placement , if cannot change reject cash payment and guide to QR — don't wait until after payment to discover change shortage.

8. Engineering Bonuses: From "Runs" to "Industrial Grade"

After main flow, mention any 2-3 of these and interviewer knows you've done real work:

Restock alert (Observer pattern) : inventory below safety threshold triggers event, pushes alert to ops; combined with XXL-Job scheduled scan generating restock route tasks. Restock action uses restock order + operation log + audit log to prevent mistakes corrupting inventory.

Offline sales (90% can't answer) :

Online normal: cloud order -> cloud deduct inventory -> dispense
Weak/offline: local terminal order -> local SQLite deduct inventory -> dispense -> network restore outbox async report reconcile

Risk: same membership card offline at machine A spends, then at machine B spends, balance overdrawn. Solution: offline quota : allow offline overdraft e.g. 20 RMB, cloud records granted quota, online later writes off — same as credit card offline transactions, typical credit quota model.

Massive device heartbeat flood : 100k device heartbeats/telemetry cannot hit MySQL directly. IoT gateway aggregates heartbeats, only reports changes; metrics go to time-series DB (TDengine/InfluxDB), MySQL stores only alerts and conclusions.

Fund reconciliation : T+1 pull third-party payment statements vs local orders bidirectional comparison , differences into error table for manual handling; jam rate, dispense timeout rate monitored with alerts.

Observability : every transaction carries full-chain traceId from device edge , all logs for one purchase (payment, inventory deduct, dispense, refund) linkable, troubleshooting efficiency doubles.

Distributed transactions? — No. Order and inventory same DB local transaction; payment relies on callback idempotency + compensation — classic "local transaction + eventual consistency", simpler and more reliable than Seata.

How to stress test? Device simulator sends MQTT packets per real purchase curve, focus on two scenarios: payment callback flood and post-power-restoration补报 flood , watch if compensation queue backs up.

Sharding? By device_id (queries mostly device-centric), cross-device reports go to data warehouse/ES.

9. Technical Difficulty Cheat Sheet

1. State chaos, illegal transitions — State pattern / table-driven state machine, illegal transition fail-fast. Keywords: Open/Closed Principle.

2. Concurrency oversell — CAS / stock>0 conditional update / Redis Lua pre-deduct. Keywords: Atomic operation.

3. Payment callback duplicate — Serial unique index + status CAS + idempotency table. Keywords: Idempotency.

4. Paid but not dispensed — Local message table + MQ + timeout compensation scan + auto refund. Keywords: Eventual consistency.

5. Duplicate dispense — Unique command_id + device (orderId,seq) deduplication + sensor verification. Keywords: Command idempotency.

6. Hardware unreliable (jam/no ack) — MQTT QoS1 + timeout retry + FAULT fuse + alert manual fallback. Keywords: Software-hardware collaboration.

7. Power loss restart loses state — WAL persist first + Reconciler active query self-heal. Keywords: Replayable.

8. Single machine concurrency conflict — Fine-grained lock by deviceId / MQ ordered consumption. Keywords: Serialization.

9. Insufficient change — Greedy algorithm + pre-validate freeze coin balance before order. Keywords: Pre-validation.

10. Weak network/offline sales — Local inventory + offline quota + online reconcile. Keywords: Edge autonomy.

11. Heartbeat flood — IoT gateway aggregation + time-series DB. Keywords: Read-write separation.

12. Fund discrepancies — T+1 three-party reconciliation + error table. Keywords: Reconciliation fallback.

10. Interview Closing: Script & Scoring Ladder

Memorize this closing script:

"To summarize, I grasped three cores: State — state machine governs vending machine lifecycle, eliminating illegal transitions; Money & Goods — payment idempotency + atomic inventory deduction + local message table + reconciliation, ensuring fund and physical eventual consistency; Hardware Fault Tolerance — command idempotency + sensor confirmation + WAL power-failure self-heal, turning 'failure' into observable, compensatable, refundable closed loop. If scale grows another order of magnitude, I'd separate device access into IoT gateway, business side unitized deployment."

If interviewer asks "Manage 100k machines?": each machine as IoT terminal reports inventory/fault via MQTT, cloud Kafka peak-shaving + Flink real-time hot item stats, hot items Redis pre-deduct prevents cloud oversell.

Final scoring ladder for self-test:

🥉 Pass — Draw class diagram, flow runs.

🥈 Good — Proactively use state pattern, articulate open/closed principle, anti-oversell.

🥇 Excellent — Explain payment idempotency, dispense compensation, MQ ordered consumption, hardware defense.

🏆 Perfect — Discuss offline quota, WAL power-failure self-heal, reconciliation system, and explain "why not distributed transactions".

Scene design questions test not "can you write this machine" but can you anticipate where the system will break . Oversell, lost orders, state corruption, power-loss account loss — those who articulate the exception flows are who interviewers want to hire. Save the cheat sheet above, review before interview; for hands-on practice, prioritize coding "state machine + inventory deduction + payment callback idempotency" — highest ROI.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

system designstate machineconcurrency controlIdempotencyinterview preparationIoTvending machinepower failure recovery
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.