Object-Oriented Design for a Multi-Story Parking Facility
System DesignModel answerLast updated
Design an object-oriented domain model for managing multi-story parking structures, handling real-time spot assignment, pricing strategies, and concurrency control.
Design an object-oriented domain model and core architecture for managing a multi-story automated parking facility.
The system must handle:
- Structures with multiple floors, each containing various parking spot configurations.
- A variety of vehicle classifications (e.g., motorbikes, sedans, oversized delivery vans, and electric vehicles).
- Distinct spot types (e.g., motorbike, compact, oversized, accessible/handicapped, and EV charging stations).
- Full life-cycle tracking: vehicle arrival, ticket generation, automated spot assignment, vehicle departure, dynamic fee evaluation, and spot release.
- Immediate query capability for current available capacity grouped by spot type.
Detail the core domain objects, their structural relationships, chosen data structures, and operational algorithms. Address how your design handles spot matching strategies, extensible fee calculations, and thread safety across concurrent entry/exit gates.
Hints
Hint 1
Decouple immutable vehicle attributes and transient parking spot allocations from ticket lifecycle tracking.
Hint 2
Consider indexing available spots per type using a priority queue (min-heap) ordered by floor level to optimize entry throughput while guaranteeing optimal spot placement.
Hint 3
Use strategy patterns for pricing rules and vehicle-to-spot matching to allow changes without altering core garage logic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
A robust parking facility system cleanly separates static structural layout (Garage, Floors, Spots), dynamic state tracking (Occupancy, Active Tickets), and business logic policies (Matching Rules, Pricing Engine).
+-------------------+
| ParkingGarage | (Facade / Synchronizer)
+---------+---------+
|
+-------------------------+-------------------------+
| | |
v v v
+-----------+ +---------------+ +------------------+
| Floor | | Ticket | | PricingStrategy |
+-----+-----+ +---------------+ +------------------+
|
v
+-----------+
| Spot |
+-----------+
Core Data Modeling & Responsibilities
| Class / Entity | Primary Responsibility | Key Attributes / Relationships |
|---|---|---|
Vehicle | Represents an incoming vehicle. Immutable. | license_plate: str, category: VehicleCategory, has_disability_permit: bool |
ParkingSpot | Models an individual physical space. | spot_id: str, floor_level: int, spot_type: SpotType, current_vehicle: Optional[Vehicle] |
Floor | Manages physical layout for a single story. | level: int, spots: List[ParkingSpot] |
Ticket | Tracks an active parking session. | ticket_id: str, vehicle: Vehicle, assigned_spot: ParkingSpot, entry_time: float |
PricingStrategy | Interface for computing total charges. | calculate_fee(ticket: Ticket, departure_time: float) -> float |
ParkingGarage | Primary API Facade & state coordinator. | Owns structural entities, heap-based spot availability indices, active ticket lookup tables, and concurrency locks. |
Data Structure Selection for Hot Paths
To maintain low latency during peak traffic (hundreds of vehicles entering/exiting simultaneously), critical operations avoid linear scanning across all garage spots:
-
Available Spots Index (
dict[SpotType, MinHeap]):
For everySpotType, we maintain a Min-Heap of available spots, ordered primary byfloor_levelascending and secondary byspot_id.- Entry Query: Finding and taking the closest free spot costs $O(\log N)$ time where $N$ is total spots of that type.
- Spot Release: Pushing a freed spot back into its respective heap costs $O(\log N)$.
-
Active Sessions (
dict[str, Ticket]):
A hash map keyed byticket_idgrants $O(1)$ lookup upon departure. -
Plate Registry (
dict[str, str]):
A secondary hash map mappinglicense_plate -> ticket_idprevents duplicate vehicle entries (tailgating protection) and handles lost ticket workflows in $O(1)$ time. -
Availability Metric:
Capacity perSpotTypeis derived directly vialen(heap)in $O(1)$ time.
Allocation Logic & Flexibility
Vehicle categories match to compatible spot types based on size and feature needs. Allocation operates using a strictly prioritized fallback chain:
- Motorcycle: Motorcycle $\rightarrow$ Compact $\rightarrow$ Oversized
- Sedan / Standard Car: Compact $\rightarrow$ Oversized
- Oversized Van: Oversized
- Electric Vehicle: EV Charging $\rightarrow$ Compact $\rightarrow$ Oversized
Accessible Permit Override: If vehicle.has_disability_permit is True, the ACCESSIBLE spot type is prefixed to the vehicle's fallback chain. Accessible spots are never offered to non-permitted vehicles.
COMPATIBILITY_MAP = {
VehicleCategory.MOTORCYCLE: [SpotType.MOTORCYCLE, SpotType.COMPACT, SpotType.OVERSIZED],
VehicleCategory.SEDAN: [SpotType.COMPACT, SpotType.OVERSIZED],
VehicleCategory.VAN: [SpotType.OVERSIZED],
VehicleCategory.EV: [SpotType.EV_CHARGING, SpotType.COMPACT, SpotType.OVERSIZED],
}
Concurrency & Thread Safety
In multi-gate environments, concurrent entry/exit events can introduce race conditions where two gates claim the same free spot.
-
In-Memory Lock Architecture:
A reentrant lock (threading.RLock) wraps critical state modifications insideissue_entry_ticketandprocess_departure. Because the critical section executes strictly in $O(\log N)$ time (heap operations and dictionary mutations), lock contention remains minimal even under thousands of requests per minute. -
Decoupled Payment Processing:
To avoid blocking gates during external credit card processing, execution is split into two phases:- Phase 1 (Quote): Compute fee under read-only access ($O(1)$).
- External Payment: Gate hardware performs network transaction outside the lock.
- Phase 2 (Release): Acquire lock, pop ticket from registry, and return spot to the availability min-heap ($O(\log N)$).
-
Distributed System Scaling (Database-backed):
If running multiple stateless API nodes behind entry gates:- Replace in-memory heaps with a transactional SQL database.
- Execute spot selection using row-level locks:
SELECT id FROM spots WHERE spot_type = :type AND occupied = FALSE ORDER BY floor_level ASC LIMIT 1 FOR UPDATE SKIP LOCKED;
Complete Python Implementation
from __future__ import annotations
import heapq
import math
import threading
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Protocol
class VehicleCategory(Enum):
MOTORCYCLE = "MOTORCYCLE"
SEDAN = "SEDAN"
VAN = "VAN"
EV = "EV"
class SpotType(Enum):
MOTORCYCLE = "MOTORCYCLE"
COMPACT = "COMPACT"
OVERSIZED = "OVERSIZED"
ACCESSIBLE = "ACCESSIBLE"
EV_CHARGING = "EV_CHARGING"
@dataclass(frozen=True)
class Vehicle:
license_plate: str
category: VehicleCategory
has_disability_permit: bool = False
@dataclass
class ParkingSpot:
spot_id: str
floor_level: int
spot_type: SpotType
occupied_by: Optional[Vehicle] = None
def __lt__(self, other: ParkingSpot) -> bool:
# Heap priority: Lower floor level first, then lexicographical spot_id
if self.floor_level != other.floor_level:
return self.floor_level < other.floor_level
return self.spot_id < other.spot_id
@dataclass
class Ticket:
ticket_id: str
vehicle: Vehicle
assigned_spot: ParkingSpot
entry_timestamp: float
exit_timestamp: Optional[float] = None
calculated_fee: Optional[float] = None
class PricingStrategy(Protocol):
def compute_fee(self, ticket: Ticket, departure_time: float) -> float:
...
class HourlyRatePricingStrategy:
def __init__(self, hourly_rates: Dict[SpotType, float], grace_period_minutes: float = 15.0):
self.hourly_rates = hourly_rates
self.grace_period_minutes = grace_period_minutes
def compute_fee(self, ticket: Ticket, departure_time: float) -> float:
duration_seconds = max(0.0, departure_time - ticket.entry_timestamp)
duration_minutes = duration_seconds / 60.0
if duration_minutes <= self.grace_period_minutes:
return 0.0
billable_hours = math.ceil(duration_minutes / 60.0)
rate = self.hourly_rates.get(ticket.assigned_spot.spot_type, 10.0)
return billable_hours * rate
class ParkingGarageManager:
def __init__(self, pricing_strategy: PricingStrategy):
self._pricing_strategy = pricing_strategy
self._lock = threading.RLock()
# Min-heaps keyed by SpotType -> List[ParkingSpot]
self._available_spots: Dict[SpotType, List[ParkingSpot]] = {
st: [] for st in SpotType
}
self._active_tickets: Dict[str, Ticket] = {}
self._plate_to_ticket: Dict[str, str] = {}
self._ticket_counter = 0
def register_spot(self, spot: ParkingSpot) -> None:
"""Initializes a spot into the management pool."""
with self._lock:
if spot.occupied_by is None:
heapq.heappush(self._available_spots[spot.spot_type], spot)
def get_available_count(self, spot_type: SpotType) -> int:
with self._lock:
return len(self._available_spots[spot_type])
def _determine_search_order(self, vehicle: Vehicle) -> List[SpotType]:
search_order = []
if vehicle.has_disability_permit:
search_order.append(SpotType.ACCESSIBLE)
fallback_chain = {
VehicleCategory.MOTORCYCLE: [SpotType.MOTORCYCLE, SpotType.COMPACT, SpotType.OVERSIZED],
VehicleCategory.SEDAN: [SpotType.COMPACT, SpotType.OVERSIZED],
VehicleCategory.VAN: [SpotType.OVERSIZED],
VehicleCategory.EV: [SpotType.EV_CHARGING, SpotType.COMPACT, SpotType.OVERSIZED],
}
for st in fallback_chain.get(vehicle.category, [SpotType.OVERSIZED]):
if st not in search_order:
search_order.append(st)
return search_order
def issue_entry_ticket(self, vehicle: Vehicle, current_time: Optional[float] = None) -> Ticket:
entry_time = current_time if current_time is not None else time.time()
with self._lock:
if vehicle.license_plate in self._plate_to_ticket:
raise ValueError(f"Vehicle {vehicle.license_plate} is already inside the garage.")
candidate_types = self._determine_search_order(vehicle)
assigned_spot: Optional[ParkingSpot] = None
for spot_type in candidate_types:
heap = self._available_spots[spot_type]
if heap:
assigned_spot = heapq.heappop(heap)
break
if not assigned_spot:
raise RuntimeError("Facility Full: No compatible spot available.")
assigned_spot.occupied_by = vehicle
self._ticket_counter += 1
ticket_id = f"TICK-{self._ticket_counter:06d}"
ticket = Ticket(
ticket_id=ticket_id,
vehicle=vehicle,
assigned_spot=assigned_spot,
entry_timestamp=entry_time
)
self._active_tickets[ticket_id] = ticket
self._plate_to_ticket[vehicle.license_plate] = ticket_id
return ticket
def process_departure(self, ticket_id: str, departure_time: Optional[float] = None) -> Ticket:
exit_time = departure_time if departure_time is not None else time.time()
with self._lock:
if ticket_id not in self._active_tickets:
raise KeyError(f"Invalid ticket identifier: {ticket_id}")
ticket = self._active_tickets.pop(ticket_id)
del self._plate_to_ticket[ticket.vehicle.license_plate]
ticket.exit_timestamp = exit_time
ticket.calculated_fee = self._pricing_strategy.compute_fee(ticket, exit_time)
# Release spot and return to availability min-heap
spot = ticket.assigned_spot
spot.occupied_by = None
heapq.heappush(self._available_spots[spot.spot_type], spot)
return ticket
Complexity Analysis
- Entry Request (
issue_entry_ticket): $O(K \log N)$ where $K$ is the number of compatible spot types checked ($K \le 4$) and $N$ is the number of spots of that type. - Departure Processing (
process_departure): $O(\log N)$ to restore the spot to its corresponding heap. - Capacity Queries (
get_available_count): $O(1)$ runtime complexity. - Space Complexity: $O(S + T)$ where $S$ is the physical spot count and $T$ is the number of concurrent active tickets.
Critical Edge Cases Handled
- Garage Overcapacity: If no compatible spot heap contains an item,
RuntimeErroris raised, preventing gate clearance. - Duplicate Registration Prevention: Re-entry of an active license plate throws an explicit error to prevent license sharing fraud or gate sensor misfires.
- Grace Period Exemption: Departures within the grace window (e.g., driver unable to find space) evaluate to a $0.0 fee.
- Accessible Spot Protection: Vehicles lacking a disability permit bypass the
ACCESSIBLEheap during allocation searches.