Level Level Design: Vending Machine System

May 23, 2026

Design a vending machine system that allows users to select a product from a list of available items and purchase it by inserting cash.

Products
Qty0
Qty0
Qty0
Qty0
Qty0
Qty0
Screen
Select a product
ItemsEmpty
ChangeEmpty

Functional Requirements

The vendoring machine should support for the following operations:

  1. Display all available products along with important details like name, price and the quantity available in stock.

  2. Allow users to select a product and insert coins or notes as payment. Once the inserted amount is sufficient, the machine should dispense the product and return the change.

  3. Manage product inventory by updating the available stock after every successful purchase to ensure accurate inventory tracking.


Sequence Flow

The primary use case for the vending machine system is to allow users to select a product and purchase it by inserting coins or banknotes as payment. Here's how its workflow looks like:

  1. Select a product: The user selects a product from the available options.

  2. Insert payment: The user inserts coins or banknotes as payment.

  3. Validate payment: The vending machine compares the inserted amount with the product price.

    • If the amount is insufficient, the machine requests additional payment.
    • If the amount is sufficient, the purchase proceeds.
    • If the amount exceeds the price, the machine calculates the change to return.
  4. Dispense the product and change: The vending machine dispenses the selected product and returns any applicable change.

  5. Update Inventory: The vending machine updates the inventory to reflect the reduced stock.

Loading diagram…

Design Rationale

Let's try to identify the key components of the vending machine system through the following design discussions.

Q1. How can a user interact with the vending machine to fulfill a purchase request?

A user interacts with the vending machine through a set of public methods that allow them to select a product, insert coins or banknotes, and complete a purchase.

We introduce a VendingMachine class that acts as the central controller, coordinating product selection, payment validation, product dispensing, change calculation, and inventory updates.

To follow the Single Responsibility Principle (SRP), we delegate inventory management, payment processing, and product dispensing to specialized components such as InventoryManager, PaymentProcessor, ProductDispenser, and ChangeDispenser.

Loading diagram…

The VendingMachine also acts as a Facade, providing a unified and simplified interface to these subsystems while hiding their internal implementation details.

Q2. How would you model the inventory to support efficient product lookups, availability checks, and stock updates?

We can model the inventory using a Map<Product, Integer>. This provides average-case O(1) lookup and update operations, assuming good hash distribution.

We'll keep the map private inside InventoryManager and expose inventory operations through methods such as getProductQuantity(), isAvailable(), decreaseStock(), and restockProduct().

This encapsulates inventory management within InventoryManager, following the Single Responsibility Principle (SRP) and preventing other components from directly modifying stock quantities.

Loading diagram…
Q3. How do we maintain a good hash distribution?

Since Product is used as a key in the HashMap, it must implement equals() and hashCode() consistently. Equal products must return the same hash code, and the fields used for equality and hashing should remain stable while the product is stored in the map.

To maintain a good hash distribution, hashCode() should minimize collisions by distributing distinct products across the available hash buckets. We can use an immutable, unique productId for equality and hash-code calculations, ensuring consistent lookup behavior even if other product attributes, such as name or price, change.

Loading diagram…
Q4. How should the vending machine validate the inserted amount and determine the change due?

We'll introduce a PaymentProcessor class to validate the payment by comparing the total inserted amount with the product price. If the amount is insufficient, the machine requests additional payment. If the amount is sufficient, the purchase can proceed, and any excess amount is calculated as change due.

Loading diagram…
Q5. How should the vending machine represent and track coins and banknotes inserted by the user?

We can represent the inserted cash using a Map<Denomination, Integer>, where Denomination represents a coin or banknote value and the integer represents its quantity.

We can encapsulate this map inside a Payment class, which is responsible for tracking the inserted denominations and calculating the total amount received. The PaymentProcessor uses this total to validate the payment and determine the change due.

Loading diagram…
Note

getInsertedCash() should ideally return an unmodifiable view or a defensive copy so callers cannot bypass the Payment class and modify its internal state directly.

Q6. How should we model different coin and banknote denominations to ensure type safety and support cash handling and change dispensing?

We can model Denomination as an enum representing the coins and banknotes accepted by the vending machine. Using an enum provides type safety and immutability, ensuring that only predefined denominations are used.

Loading diagram…

Each denomination has an associated monetary value, allowing the system to calculate the total inserted amount and determine the change due. For example, COIN_5(5) represents a ₹5 coin, while NOTE_5(5) represents a ₹5 banknote, if both are supported. This distinction allows the machine to handle different physical cash types even when their monetary values are equal.

Q7. How should the vending machine dispense the required change while ensuring sufficient cash is available?

We introduce a ChangeDispenser class responsible for selecting the appropriate coins and banknotes to return the required change. It interacts with CashInventory to check the availability of denominations and determine whether the requested amount can be dispensed.

The ChangeDispenser selects a combination of available denominations that adds up to the change due. If the required amount cannot be formed using the available cash, the machine must handle the failure without completing the purchase incorrectly.

Once a valid combination is selected, the dispenser returns the change and updates the cash inventory to reflect the dispensed denominations.

Loading diagram…
Q8. How should the vending machine track available coins and banknotes to ensure it can return the correct change to users?

We can represent the cash inventory using a Map<Denomination, Integer>, where Denomination represents a coin or banknote value and the integer represents its available quantity.

We can encapsulate it inside a CashInventory class, making it responsible for checking denomination availability, updating quantities when cash is added or dispensed, and ensuring that sufficient cash is available to return the required change.

The ChangeDispenser can use CashInventory to determine whether the required change can be provided and dispense the appropriate denominations.

Loading diagram…
Q9. How should the vending machine dispense the selected product?

We introduce a Dispenser class responsible for physically dispensing the selected product after payment has been validated and sufficient inventory has been confirmed.

Loading diagram…

Implementation

java

public final class VendingMachine {
    private final InventoryManager inventoryManager;
    private final PaymentProcessor paymentProcessor;
    private final Dispenser dispenser;
    private final ChangeDispenser changeDispenser;
    private final CashInventory cashInventory;

    public VendingMachine(
            InventoryManager inventoryManager,
            PaymentProcessor paymentProcessor,
            Dispenser dispenser,
            ChangeDispenser changeDispenser,
            CashInventory cashInventory) {
        if (inventoryManager == null || paymentProcessor == null || dispenser == null
                || changeDispenser == null || cashInventory == null) {
            throw new IllegalArgumentException("Dependencies cannot be null");
        }
        this.inventoryManager = inventoryManager;
        this.paymentProcessor = paymentProcessor;
        this.dispenser = dispenser;
        this.changeDispenser = changeDispenser;
        this.cashInventory = cashInventory;
    }

    public Product selectProduct(String productId) {
        Product product = inventoryManager.getProduct(productId);
        if (product == null) {
            throw new IllegalArgumentException("Unknown product: " + productId);
        }
        if (!inventoryManager.isAvailable(product)) {
            throw new IllegalStateException("Product is out of stock: " + product.getName());
        }
        return product;
    }

    public PurchaseResult purchaseProduct(String productId, Payment payment) {
        if (payment == null) throw new IllegalArgumentException("payment cannot be null");

        int inserted = payment.getTotalAmount();
        Product product = inventoryManager.getProduct(productId);
        if (product == null) {
            return result(PurchaseResult.Status.PRODUCT_NOT_FOUND, inserted, 0, Map.of(),
                    "Product not found");
        }
        if (!inventoryManager.isAvailable(product)) {
            return result(PurchaseResult.Status.OUT_OF_STOCK, inserted, 0, Map.of(),
                    "Product is out of stock");
        }
        if (!paymentProcessor.isSufficient(payment, product.getPrice())) {
            return result(PurchaseResult.Status.INSUFFICIENT_PAYMENT, inserted, 0, Map.of(),
                    "Please insert more cash");
        }

        int changeDue = paymentProcessor.calculateChangeDue(payment, product.getPrice());

        // Plan change before dispensing, so we don't dispense a product if change is unavailable.
        Map<Denomination, Integer> plannedChange = cashInventory.findChange(changeDue);
        if (plannedChange == null) {
            return result(PurchaseResult.Status.EXACT_CHANGE_UNAVAILABLE, inserted, changeDue,
                    Map.of(), "Unable to provide exact change; purchase not completed");
        }

        DispenseResult dispenseResult = dispenser.dispenseProduct(product);
        if (dispenseResult != DispenseResult.SUCCESS) {
            return result(PurchaseResult.Status.DISPENSING_FAILED, inserted, changeDue,
                    Map.of(), "Dispensing failed; refund/recovery is required");
        }

        // Commit product stock only after dispensing succeeds.
        inventoryManager.decreaseStock(product);

        /*
         * Cash inserted by the user enters the machine's cash inventory.
         * Then return change. In production, physical cash operations require
         * a transactional/reservation protocol and hardware-failure recovery.
         */
        payment.getInsertedCash().forEach(cashInventory::addCash);

        Map<Denomination, Integer> dispensedChange;
        try {
            dispensedChange = changeDispenser.dispenseChange(changeDue);
        } catch (RuntimeException e) {
            // Product has already been dispensed; production systems need compensation/manual recovery.
            return result(PurchaseResult.Status.EXACT_CHANGE_UNAVAILABLE, inserted, changeDue,
                    Map.of(), "Product dispensed but change delivery failed; recovery is required");
        }

        return result(PurchaseResult.Status.SUCCESS, inserted, changeDue, dispensedChange,
                "Purchase completed");
    }

    private PurchaseResult result(
            PurchaseResult.Status status,
            int inserted,
            int changeDue,
            Map<Denomination, Integer> change,
            String message) {
        return new PurchaseResult(status, inserted, changeDue, change, message);
    }
}

Final Design

Loading diagram…

Follow-Up Questions

Q1. How to extend the system to support other payment methods such as card or UPI?