Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 57 ยท Low-Level Design Projects

Project: Parking Lot

Design a parking lot system step by step: vehicles, spots, tickets, a pricing strategy, a vehicle factory and concurrency, with a complete runnable Node.js model.

The parking lot is the classic low-level design problem, and for good reason. It is small enough to finish in one sitting, yet it touches every skill: finding entities, modeling rules that change (prices), handling lifecycles (a ticket is issued, then paid) and thinking about two cars racing for the last spot. In this project you will follow the process from How to Approach a Low-Level Design Problem and end with a runnable model.

What the lot must do

Park A vehicle enters and gets a spot and a ticket.
Ticket It records the spot and entry time.
Pay on exit The fee depends on time and spot size.
Free the spot Exit makes the spot available again.
1 / 2

Step 1: requirements

Assumptions, stated up front:

  • One building with several spots of three sizes: small, medium and large.
  • Vehicle types: motorcycle, car and truck. A vehicle may use a spot at least as big as it needs: motorcycles fit anywhere, cars need medium or large, trucks need large.
  • On entry the lot picks the smallest suitable free spot and issues a ticket.
  • On exit the driver presents the ticket, the lot calculates a fee, frees the spot and invalidates the ticket.
  • Pricing is per started hour, with a different hourly rate per spot size. Pricing rules are expected to change.
  • Out of scope: payment processing, cameras, reservations, user interface, persistence.

Step 2: entities and relationships

From the nouns: Vehicle, Spot, Ticket, ParkingLot. From the rule that pricing changes: a PricingStrategy. From the idea that time matters: a Clock.

classDiagram
    class ParkingLot {
      +enter(vehicle) Ticket
      +exit(ticketId) Receipt
      +available() object
    }
    class Spot {
      +id
      +size
      +vehicle
    }
    class Ticket {
      +id
      +plate
      +spotId
      +enteredAt
    }
    class PricingStrategy {
      <<interface>>
      +fee(ticket, spot, exitTime)
    }
    ParkingLot "1" o-- "many" Spot
    ParkingLot ..> Ticket : issues
    ParkingLot --> PricingStrategy
    PricingStrategy <|.. HourlyPricing
    PricingStrategy <|.. DailyCapPricing

The lot owns its spots, issues tickets and asks a pricing strategy for the fee. Strategies implement one shared interface.

The lot owns the spots (aggregation), creates tickets and uses a pricing strategy that is handed to it from outside (dependency injection, see Dependency Inversion and Dependency Injection).

Step 3: the public API

Three operations are enough:

  • enter(vehicle) returns a ticket or throws if no suitable spot is free.
  • exit(ticketId) returns a receipt with the fee, or throws for an unknown or already-used ticket.
  • available() returns how many free spots each size has.

Step 4: patterns, and why

Factory. Callers say "car" and a plate, and a small factory validates the type and builds the vehicle. When a new vehicle type appears (a bus), only the factory and the fit table change. See Factory Method.

Strategy. The price is the most likely thing to change: weekend rates, daily caps, a free first hour. Each rule becomes a class with the same fee() method, so the lot never needs an if on the pricing mode. See Strategy.

Injected clock. The lot never calls Date.now() itself. It receives a clock object. In production that is the real time, and in a test it is a fake you can move forward by exactly 90 minutes. Anything that reads the current time, a random number or the network directly is hard to test, so pass it in.

Step 5: the code

The complete model is below. Read it top to bottom: vehicle fit rules and the factory, then spots and tickets, then the two pricing strategies, then the lot itself. The demo at the end parks four vehicles, fills the lot, exits one vehicle and compares two pricing strategies on the same ticket.

Node.js A complete parking lot model

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 carefully. The motorcycle took the small spot and the car took the medium one, because the lot picks the smallest suitable free spot. The truck had only the large spot to choose from. The second car is rejected because no medium or large spot is free. The 90-minute stay is billed as two started hours at the medium rate of 2, and the 30-hour truck stay costs 120 at the hourly rate but only 40 with the daily cap of 20 per started day.

Design notes and trade-offs

  • Best fit versus first fit. Picking the smallest suitable spot saves large spots for trucks. A real lot might also prefer spots near the entrance. That is a second strategy (SpotAllocator) you can extract when the requirement appears.
  • Ticket in a map. Looking up by id is constant time, and deleting on exit makes a second exit fail naturally.
  • Money. The model uses whole numbers. A production system would use a money type, as in Anti-Patterns and Code Smells.
  • Where the state lives. Everything is in memory. To persist, put a repository behind the lot (see Repository and Unit of Work).
  • Extensions. Electric-vehicle spots are another size or a flag plus a pricing strategy. Multiple floors are a Floor class that owns spots, with the lot delegating to floors. Reservations add a state to the spot.

Concurrency

In a real lot, several entrance gates call enter at about the same time. The danger is a check-then-act race: gate A sees that spot L1 is free, gate B sees the same, and both assign it. Our enter is safe in plain JavaScript because it runs from start to finish without pausing. The risk appears when the real work includes something asynchronous between the check and the assignment, such as a database lookup. The next example reproduces the race and fixes it with a tiny mutex. The mutex makes callers take turns.

Node.js Two gates, one spot: a race and its fix

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.

In the unsafe version both cars were told they got the spot, and the second one silently overwrote the first. In the safe version the second call waits its turn, then sees the spot taken and gets "lot full". In Java you would use synchronized or a ReentrantLock around the same check-and-take, or an atomic compare-and-set on the spot. In C++, a std::mutex with std::lock_guard does the same job. The principle is identical: make check and take one indivisible step. With several lots or servers you need the database to enforce it (a unique constraint or a conditional update), because an in-process lock covers only one process.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does ParkingLot receive a PricingStrategy instead of calculating fees itself?

    Isolating the part that changes behind a small interface is the point of Strategy, and it follows the Open/Closed Principle.
  2. 2. Why is the clock passed into the lot instead of calling Date.now() inside it?

    Time is an input. Injecting it makes behavior deterministic in tests.
  3. 3. What is a check-then-act race in this design?

    The check (is the spot free?) and the action (assign it) must be one atomic step, or two callers can both pass the check.
  4. 4. How do you add a bus that needs two large spots with the least change?

    The fit table and factory handle the new type, and a spot-allocation strategy isolates the new rule, so existing classes stay untouched.

Summary

  • Start from requirements and scope, then list entities: vehicle, spot, ticket, lot, plus a pricing strategy and a clock.
  • A factory creates vehicles, a strategy computes fees, and injecting the clock makes time testable.
  • The lot picks the smallest suitable free spot, issues a ticket and frees the spot when the ticket is used.
  • Check-then-act races happen whenever something asynchronous sits between the check and the assignment; fix them with a lock or an atomic operation.
  • In production, move state behind a repository and let the database enforce uniqueness.

Next lesson: Project: Elevator System.