Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 57 ยท Low-Level Design Projects

Project: Ride Sharing and Vending Machine

Two classic low-level design projects: a ride-sharing dispatcher with matching and pricing strategies, and a vending machine built with State and Command.

This lesson solves two problems that look very different but share a skeleton. A ride-sharing dispatcher has to pick a driver for a rider, price the trip and move the ride through a life cycle. A vending machine has to react to coins and button presses differently depending on what has already happened, and it has to give money back when a customer changes their mind.

We follow the framework from How to Approach a Low-Level Design Problem: requirements, entities, API, patterns, failure paths, extensions. The code is plain in-memory JavaScript that runs on the site, so you can change a rule and watch the result. A real ride-sharing app also needs maps, payments, push notifications and a database; none of that is simulated here. Only the design of the core domain is.

Two problems, four patterns

Strategy Matching and pricing rules can be swapped.
State Rides and machines react by status.
Command Every coin is an undoable action.
Decorator Surge pricing wraps normal pricing.
1 / 2

Part 1: the ride-sharing dispatcher

Requirements

  • A rider requests a ride with a pickup point and a drop-off point.
  • The system finds an available driver. How it chooses may change: nearest driver today, best-rated driver within a radius tomorrow.
  • The fare depends on distance. Rules change often (base fee, per-kilometer rate, minimum fare, surge multiplier).
  • A ride moves through REQUESTED, MATCHED, ONGOING and COMPLETED. It can be cancelled before it starts.
  • A driver can carry only one ride at a time.

Out of scope: maps and real routes (we use straight-line distance on a flat grid), payments, ratings after the trip, and persistence.

Entities and relationships

Underline the nouns: rider, driver, ride, location, fare. A Location is a value object. A Driver is an entity with a position, a rating and an availability flag. A Ride is an entity that links one rider to at most one driver and owns its status. A RideService is the facade that the outside world calls: requestRide, startRide, completeRide, cancelRide.

classDiagram
  class RideService {
    +requestRide(rider, pickup, dropoff) Ride
    +startRide(rideId)
    +completeRide(rideId)
    +cancelRide(rideId)
  }
  class MatchingStrategy {
    <<interface>>
    +choose(drivers, pickup) Driver
  }
  class PricingStrategy {
    <<interface>>
    +fare(distance) number
  }
  class Ride
  class Driver
  RideService --> MatchingStrategy
  RideService --> PricingStrategy
  RideService o-- Driver
  RideService *-- Ride
  Ride --> Driver

The service depends on two small strategy interfaces. Rides and drivers are plain entities.

Patterns and why

  • Strategy for matching: NearestDriver and BestRatedNearby implement the same choose method. See Strategy.
  • Strategy plus Decorator for pricing: StandardPricing calculates a fare; SurgePricing wraps any pricing object and multiplies the result. See Decorator.
  • State machine for the ride: a table of allowed transitions. A full state-object version appears in the vending machine below, and the idea is explained in State.

A runnable dispatcher

The code uses a table of legal transitions, so an illegal move such as completing a ride that never started is rejected in one place. Notice also that a driver is marked busy in the same synchronous step in which it is chosen. In Node this makes "check and take" atomic, as discussed in the framework lesson. If you added await between choosing and marking, two riders could receive the same driver.

Node.js Ride-sharing dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at what changed between runs. The service class never changed; we passed different strategy objects. That is the design paying off. Adding a "women-preferred" or "electric-car" matching rule is one new class.

Failure paths and concurrency

The code already answers three questions an interviewer will ask. No drivers free? The ride is cancelled and returned, so the caller learns immediately. Illegal call order? The transition table throws. Two riders at once? In a single-threaded runtime the choose and available = false steps run without interruption. In Java or C++ you would guard the pair with a lock, or use an atomic compare-and-set on the driver's status, so that only one thread can claim the driver.

Extensions

  • Ride pooling: a new matching strategy that may return a driver who already has a ride, plus a ride that can hold several riders.
  • Driver acceptance: add a OFFERED state between REQUESTED and MATCHED, and fall back to the next candidate on decline.
  • Notifications: the service publishes events ("matched", "completed") and notification classes subscribe. See Observer.

Part 2: the vending machine

Requirements

  • The machine stocks products in coded slots such as A1, each with a price (in cents) and a quantity.
  • A customer inserts coins (5, 10, 25 or 100 cents), selects a slot, and receives the product and any change.
  • A customer can ask for a refund before buying, and gets back exactly the coins inserted.
  • The machine has a limited stock of coins for change. If it cannot make exact change, the sale must not happen.

Why State

Count how many ways a single button press can behave. Pressing "select" with no money should say "insert coins". Pressing it with enough money should dispense. Pressing it with too little money should show the missing amount. A naive implementation puts all of that into one method full of if (credit === 0) checks. With the State pattern, each situation is an object that answers every event in its own way, and the machine just forwards the event. Study State for the general shape.

stateDiagram-v2
  [*] --> Idle
  Idle --> HasMoney: insert coin
  HasMoney --> HasMoney: insert coin
  HasMoney --> Idle: refund
  HasMoney --> Idle: purchase with no credit left
  HasMoney --> HasMoney: purchase fails (price, stock or change)

Two states are enough. Dispensing happens inside the transition, in one synchronous step.

Why Command for refunds

A refund must return exactly what the customer put in. The cleanest way is to treat each coin insertion as a command object that knows how to execute itself and how to undo itself. The machine keeps a list of commands for the current transaction. A refund undoes them in reverse order and collects the coins. When a purchase completes, the transaction list is cleared because the coins now belong to the machine. This is the same undo-stack idea you meet in Command.

A runnable vending machine

The change-maker uses a greedy algorithm, taking the largest coin first, limited by the coins the machine holds. Greedy is correct for these denominations when the float is unlimited. With a limited float it can fail even when a solution exists (for example change of 30 from coins of 25, 10, 10, 10 where greedy takes 25 first and gets stuck). A real machine would use a small search or dynamic programming; the sketch here says plainly when it gives up.

Node.js Vending machine with State and Command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output from top to bottom and watch the bracketed state. The same call, select("A1"), gives three different answers because the state changed, not because of any condition inside the machine. And the refund returns exactly the coins that were inserted since the last sale, in reverse order.

Concurrency and extensions

A vending machine has one customer at a time, so concurrency is mostly about hardware events: the coin sensor and the button panel may fire from different threads. A simple fix is to put all events on one queue and process them one by one. For the extensions:

  • New product kinds: nothing in the machine cares what a slot holds, so a Slot subclass or a factory per product line is enough. See Factory Method.
  • Out-of-service state: add an OutOfOrderState that rejects everything, and let the machine switch to it when the float is empty. No existing state changes.
  • Refund to a card: the InsertCoin command has a cousin, AuthorizeCard, whose undo voids the authorization. The machine's refund code stays the same.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is SurgePricing written as a decorator around another pricing object instead of a subclass of StandardPricing?

    A wrapper takes any object with a fare method. With subclassing you would need one surge class per base rule.
  2. 2. In the dispatcher, why is the driver marked unavailable in the same synchronous step as choosing it?

    Check-then-take must be atomic. In Node a synchronous step is atomic, but an await between the two lines would let another request in.
  3. 3. What does the table of transitions in the Ride class provide?

    All rules about legal moves live in one data structure, so every caller is protected and new states are easy to add.
  4. 4. How does the vending machine refund exactly the coins that were inserted?

    Command objects remember what they did and know how to reverse it, so the transaction list is also the refund list.
  5. 5. Which choice best describes the role of the State pattern in the vending machine?

    The machine forwards each event to the current state, and the state may switch the machine to another state.

Summary

  • Start from requirements and entities, then pick patterns only for the rules that are likely to change.
  • The dispatcher uses Strategy for matching, Strategy plus Decorator for pricing, and a transition table for the ride life cycle.
  • Claiming a shared resource must be one atomic step: no await between the check and the update.
  • The vending machine uses State objects for behavior by situation and Command objects to make every coin undoable.
  • Limited change shows why a design needs explicit failure paths: refusing a sale is better than losing money.
  • Show extensions at the end: pooling, offer-and-accept, notifications, out-of-service and card payments all plug in without rewriting what exists.

Next lesson: Project: Text Editor with Undo and a Chess Engine Core.