Low-Level Design: Parking Lot
A complete object-oriented design: requirements, entities and relationships, strategy pattern for spot assignment and pricing, the open-closed principle and thread-safe spot allocation.
Low-level design (LLD), also called object-oriented design, is about the structure of the code inside one application: which classes exist, what each is responsible for, how they relate, and how the design accommodates change. The parking lot is the most common LLD question.
High-level design asks which services and databases to use. Low-level design asks which classes and interfaces to write. Writing code immediately skips the part that is being assessed. The approach in these notes is: requirements, entities, relationships, design patterns, then code for the core flows.
1. Requirements and assumptions
As with high-level design, the first step is to fix the scope. The following is a reasonable set of requirements; each one should be confirmed, since they affect the class design.
- The parking lot has multiple floors, and each floor has many spots.
- Spot types: motorcycle, compact (car) and large (truck). Vehicle types: motorcycle, car and truck. A vehicle parks in a spot of a suitable type.
- There are multiple entry and exit gates.
- On entry, a spot is assigned and a ticket is issued. On exit, the fee is calculated from the duration and vehicle type, payment is taken, and the spot is freed.
- If no suitable spot is available, entry is refused.
- The design should allow new vehicle types, pricing rules and payment methods to be added easily.
- Out of scope unless asked: reservations in advance, electric charging, monthly passes.
2. Identify the entities
Read the requirements and pick out the nouns; they become candidate classes. The verbs become methods. Each class should have one clear responsibility.
- Vehicle: licence number and type. Subtypes or an enum for Motorcycle, Car, Truck.
- ParkingSpot: identifier, type, floor, and whether it is occupied and by which vehicle.
- ParkingFloor: a collection of spots; can report free spots by type.
- Ticket: identifier, vehicle, spot, entry time, exit time, status.
- ParkingLot: the facade that owns the floors and offers the park and unpark operations.
- EntryGate and ExitGate: where vehicles interact with the system.
- SpotAssignmentStrategy: decides which free spot a vehicle receives.
- PricingStrategy: calculates the fee for a ticket.
- Payment: amount, method and status.
3. Relationships
State how the classes are connected, because the type of relationship determines ownership and lifetime. Composition means the part cannot exist without the whole. Association means one object refers to another that exists independently.
ParkingLot 1 ----<> * ParkingFloor 1 ----<> * ParkingSpot (composition) ParkingLot ----------> SpotAssignmentStrategy <<interface>> (uses) ParkingLot ----------> PricingStrategy <<interface>> (uses) Ticket ---> Vehicle (association: which vehicle) Ticket ---> ParkingSpot (association: which spot) Ticket ---> Payment (0..1, created at exit) Vehicle <|-- Motorcycle | Car | Truck (inheritance) SpotAssignmentStrategy <|.. NearestSpotStrategy | LowestFloorStrategy PricingStrategy <|.. HourlyPricing | FlatRatePricing | WeekendPricing PaymentMethod <|.. CashPayment | CardPayment | UpiPayment
4. Enums and core entities
The basic types come first. Which spot types can hold which vehicle types is kept as data in one place, so that the rule can change without editing the classes that use it.
enum VehicleType { MOTORCYCLE, CAR, TRUCK }
enum SpotType { MOTORCYCLE, COMPACT, LARGE }
enum TicketStatus { ACTIVE, PAID }
// Which spot types can hold which vehicle, in order of preference
const ALLOWED_SPOTS: Record<VehicleType, SpotType[]> = {
[VehicleType.MOTORCYCLE]: [SpotType.MOTORCYCLE, SpotType.COMPACT],
[VehicleType.CAR]: [SpotType.COMPACT, SpotType.LARGE],
[VehicleType.TRUCK]: [SpotType.LARGE],
};
class Vehicle {
constructor(readonly licenceNumber: string, readonly type: VehicleType) {}
}
class ParkingSpot {
private vehicle: Vehicle | null = null;
constructor(readonly id: string, readonly floor: number, readonly type: SpotType) {}
isFree(): boolean { return this.vehicle === null; }
// Returns false if another vehicle took the spot first
tryOccupy(vehicle: Vehicle): boolean {
if (this.vehicle !== null) return false;
this.vehicle = vehicle;
return true;
}
release(): void { this.vehicle = null; }
}
class Ticket {
exitTime: Date | null = null;
status = TicketStatus.ACTIVE;
constructor(
readonly id: string,
readonly vehicle: Vehicle,
readonly spot: ParkingSpot,
readonly entryTime: Date,
) {}
}5. The strategy pattern
Two parts of the system are certain to change: how a spot is chosen and how the fee is calculated. One operator wants the spot nearest to the entrance; another wants to fill the lowest floors first. Pricing may be hourly today, with a weekend rate or a daily cap tomorrow.
If these rules were written as if-else blocks inside ParkingLot, every new rule would require modifying and retesting that class. The strategy pattern avoids this. Each family of algorithms is defined behind an interface, each variant is a separate class implementing that interface, and ParkingLot holds a reference to the interface without knowing which variant it has. Changing the behaviour means supplying a different object.
interface SpotAssignmentStrategy {
findSpot(floors: ParkingFloor[], vehicle: Vehicle): ParkingSpot | null;
}
class LowestFloorStrategy implements SpotAssignmentStrategy {
findSpot(floors: ParkingFloor[], vehicle: Vehicle): ParkingSpot | null {
for (const type of ALLOWED_SPOTS[vehicle.type]) {
for (const floor of floors) {
const spot = floor.firstFreeSpot(type);
if (spot) return spot;
}
}
return null;
}
}
interface PricingStrategy {
calculate(ticket: Ticket, exitTime: Date): number;
}
class HourlyPricing implements PricingStrategy {
constructor(private ratePerHour: Record<VehicleType, number>) {}
calculate(ticket: Ticket, exitTime: Date): number {
const ms = exitTime.getTime() - ticket.entryTime.getTime();
const hours = Math.max(1, Math.ceil(ms / 3_600_000)); // minimum one hour
return hours * this.ratePerHour[ticket.vehicle.type];
}
}
// A new rule is a new class. Existing classes are not modified.
class FlatRatePricing implements PricingStrategy {
constructor(private flatFee: number) {}
calculate(): number { return this.flatFee; }
}6. The open-closed principle
The benefit of the strategy pattern is described by the open-closed principle, the O in SOLID: software entities should be open for extension and closed for modification. A new pricing rule or a new assignment policy is added by writing a new class. The ParkingLot class, which is already tested and working, is not touched.
The same reasoning applies to vehicle types. Because the compatibility between vehicles and spots is a table, supporting an electric vehicle or a bus means adding entries, not rewriting conditionals spread across the code. The other SOLID principles are visible too: each class has a single responsibility, and ParkingLot depends on interfaces, not on concrete implementations (dependency inversion).
7. The core flows
ParkingLot is a facade: gates call two simple methods and do not need to know about floors, strategies or tickets. Parking finds a spot, occupies it and issues a ticket. Unparking calculates the fee, takes payment, frees the spot and closes the ticket.
class ParkingFloor {
constructor(readonly level: number, private spots: ParkingSpot[]) {}
firstFreeSpot(type: SpotType): ParkingSpot | null {
return this.spots.find((s) => s.type === type && s.isFree()) ?? null;
}
}
class ParkingLot {
private activeTickets = new Map<string, Ticket>();
constructor(
private floors: ParkingFloor[],
private assignment: SpotAssignmentStrategy,
private pricing: PricingStrategy,
) {}
park(vehicle: Vehicle): Ticket {
// Retry: another gate may take the chosen spot between find and occupy
for (let attempt = 0; attempt < 3; attempt++) {
const spot = this.assignment.findSpot(this.floors, vehicle);
if (!spot) throw new Error("Parking lot is full for this vehicle type");
if (spot.tryOccupy(vehicle)) {
const ticket = new Ticket(crypto.randomUUID(), vehicle, spot, new Date());
this.activeTickets.set(ticket.id, ticket);
return ticket;
}
}
throw new Error("Could not assign a spot, please retry");
}
unpark(ticketId: string, payment: PaymentMethod): number {
const ticket = this.activeTickets.get(ticketId);
if (!ticket) throw new Error("Invalid or already used ticket");
const exitTime = new Date();
const fee = this.pricing.calculate(ticket, exitTime);
payment.pay(fee); // throws if the payment fails
ticket.exitTime = exitTime;
ticket.status = TicketStatus.PAID;
ticket.spot.release();
this.activeTickets.delete(ticketId);
return fee;
}
}
interface PaymentMethod { pay(amount: number): void; }8. Concurrency: two gates, one spot
With several entry gates, two vehicles can arrive at the same moment. Both gates ask for a free spot, both find spot A-12 free, and both assign it. Two tickets now point to one spot. This is the same check-then-act race condition seen in the flash sale and cab booking designs.
The check and the update must be atomic. In the code above, tryOccupy does both in one step and reports whether it succeeded, and park retries with another spot if it lost the race. In a multithreaded language, tryOccupy must be protected with a lock on the spot or implemented with an atomic compare-and-set, so that exactly one thread succeeds. Locking a single spot is preferable to locking the entire parking lot, which would force all gates to wait for each other.
If the system runs on several servers with a shared database, the same guarantee is obtained with a conditional update that occupies the spot only if it is still free, or with a row lock inside a transaction.
// In-process (Java-style): per-spot lock or compare-and-set
class ParkingSpot {
private final AtomicReference<Vehicle> vehicle = new AtomicReference<>(null);
boolean tryOccupy(Vehicle v) {
return vehicle.compareAndSet(null, v); // only one thread can succeed
}
}
-- Shared database: conditional update, then check affected rows
UPDATE parking_spots
SET occupied_by = :licence
WHERE id = :spotId AND occupied_by IS NULL;
-- 1 row -> the spot is yours 0 rows -> someone else took it, pick another9. Singleton versus dependency injection
There is one parking lot, so it is common to implement ParkingLot as a singleton: a class with a private constructor and a static method that returns the only instance. This guarantees one shared state for all gates.
The singleton has drawbacks. It is global state, its dependencies are hidden inside it, and it is difficult to replace in a unit test. The alternative is dependency injection: create one ParkingLot object when the application starts and pass it to the gates through their constructors. There is still exactly one instance, but it is created and supplied explicitly, and tests can construct a small parking lot with fake strategies. Mentioning the singleton and then explaining why injection is preferable demonstrates judgement about patterns, not just knowledge of them.
10. Extending the design
- New vehicle type: add an enum value and a row in the compatibility table.
- New pricing rule: a new PricingStrategy implementation, chosen through configuration.
- New payment method: a new PaymentMethod implementation.
- Display boards showing free spots per floor: the observer pattern, where floors notify displays when a spot changes state.
- Faster spot lookup: keep a set or min-heap of free spots per type per floor, so finding a spot does not scan all spots.
- Persistence: repository interfaces for tickets and spots, so the storage can be swapped without changing the domain classes.
Interview summary
- Start with requirements and assumptions, not code.
- Identify entities: ParkingLot, ParkingFloor, ParkingSpot, Vehicle, Ticket, Payment, and their relationships.
- Use the strategy pattern for spot assignment and pricing.
- Follow the open-closed principle: new behaviour is a new class.
- Make spot allocation atomic for concurrent gates, and prefer dependency injection to a singleton.
Summary
A low-level design is judged on structure. Fix the requirements, derive the entities and their relationships, isolate the parts that will change behind interfaces with the strategy pattern, and make spot allocation atomic so that concurrent gates cannot assign the same spot. The resulting design accepts new vehicle types, pricing rules and payment methods without changes to the classes that already work.
Puneet Tiwari
Full Stack Developer
