Functional Requirements

A parking lot system must handle:

  • Vehicle entry and exit: Cars, motorcycles, trucks, and possibly electric vehicles.
  • Slot allocation: Assign available slots efficiently to incoming vehicles.
  • Ticketing: Generate a ticket with entry time, vehicle ID, and slot details.
  • Payment processing: Calculate fees based on time parked or flat rates.
  • Slot availability tracking: Update real-time status as vehicles enter or exit.
  • Validation: Ensure only valid tickets allow exit.

Non-Functional Requirements

Beyond basic functionality, the system should also ensure:

  • Scalability: Support anything from a 50-slot local lot to a 10,000-slot multi-level garage.
  • Fault tolerance: Work smoothly even if a kiosk or server goes down.
  • Reliability: Ensure no double-booking of slots and no loss of payment records.
  • Low latency: Entry and exit flows should be fast to avoid congestion.
  • Usability: Easy for drivers and operators to interact with (self-service kiosks, apps, etc.).

Assumptions

To simplify, let’s assume:

  • Each slot can only fit one vehicle at a time.
  • Vehicles fall into broad categories (motorcycles, cars, trucks).
  • Payment is calculated on duration unless otherwise stated.
  • Parking can be tracked via tickets or license plate recognition.


API Design



### **Parking Lot System API Design**


This design separates concerns into three main services: **Entry**, **Exit/Payment**, and **Account/Admin**.


#### **1. Entry Gate Service**

Handles vehicle arrivals, slot allocation, and ticket issuance.


* **`POST /api/v1/parking/entry`**

* **Description:** Triggered when a vehicle reaches the entry gate. Allocates a spot and issues a ticket.

* **Request Body:**

```json

{

"entry_gate_id": "GATE_01",

"vehicle_number": "ABC-1234",

"vehicle_type": "CAR" // Enum: CAR, MOTORCYCLE, TRUCK, EV

}

```

* **Response (200 OK):**

```json

{

"ticket_id": "TKT_998877",

"vehicle_number": "ABC-1234",

"slot_id": "L1_R3_S10",

"entry_time": "2025-10-27T10:00:00Z",

"bar_code": "binary_data_or_url"

}

```

* **Error (409 Conflict):** `{"message": "Parking Lot Full"}`


#### **2. Exit & Payment Service**

Handles ticket validation, fee calculation, and transaction processing.


* **`POST /api/v1/parking/fee`**

* **Description:** Triggered when a user scans their ticket at the exit or payment kiosk to see the amount due.

* **Request Body:**

```json

{

"ticket_id": "TKT_998877",

"exit_time": "2025-10-27T12:00:00Z" // Optional, defaults to now

}

```

* **Response (200 OK):**

```json

{

"ticket_id": "TKT_998877",

"duration_hours": 2.0,

"amount_due": 15.00,

"currency": "USD",

"status": "UNPAID"

}

```


* **`POST /api/v1/parking/payment`**

* **Description:** Processes the payment for a specific ticket.

* **Request Body:**

```json

{

"ticket_id": "TKT_998877",

"amount": 15.00,

"payment_method": "CREDIT_CARD", // CASH, APPLE_PAY

"payment_reference": "TXN_554433"

}

```

* **Response (200 OK):**

```json

{

"payment_id": "PAY_001",

"status": "SUCCESS",

"receipt_url": "https://api.parking.com/receipts/PAY_001"

}

```


* **`POST /api/v1/parking/exit`**

* **Description:** Final validation at the exit gate barrier. Checks if the ticket is paid/valid before opening the barrier.

* **Request Body:**

```json

{

"ticket_id": "TKT_998877",

"exit_gate_id": "EXIT_02"

}

```

* **Response (200 OK):**

```json

{

"authorized": true,

"gate_action": "OPEN",

"message": "Have a nice day"

}

```


#### **3. Slot & Monitoring Service (Admin/Dashboard)**

Used by internal systems and operator dashboards.


* **`GET /api/v1/slots/availability`**

* **Description:** Returns the count of available spots per type/level.

* **Response:**

```json

{

"total_capacity": 500,

"available_count": 42,

"breakdown": {

"CAR": 30,

"MOTORCYCLE": 10,

"EV": 2

}

}

```


---




High-Level Design

Core Components of Design a Parking Lot System Design

  1. Entry/Exit Gates
    • Equipped with kiosks, sensors, or license plate recognition.
    • Trigger slot allocation and ticket generation at entry.
    • Validate ticket and payment at exit.
  2. Ticketing System
    • Issues tickets (paper, QR code, or digital).
    • Associates tickets with vehicles, slots, and timestamps.
    • Prevents fraudulent exits by linking tickets to actual usage.
  3. Slot Management Module
    • Tracks real-time slot availability.
    • Allocates slots based on rules (nearest to exit, vehicle type, or first available).
    • Updates availability when vehicles enter or leave.
  4. Payment Processor
    • Calculates parking fees based on duration or flat rates.
    • Integrates with cash, cards, or digital payment options.
    • Ensures secure, auditable transactions.
  5. Database and Backend Services
    • Store vehicle records, ticket history, payment logs, and slot data.
    • Provide APIs for mobile apps or operator dashboards.
    • Use replication and backups to prevent data loss.
  6. Admin/Monitoring Dashboard
    • Lets operators monitor occupancy in real time.
    • Provides analytics on usage patterns, revenue, and peak hours.


Data Flow Example

  1. A car approaches the entry gate.
  2. The system checks for available slots.
  3. A ticket is issued, and the slot is reserved.
  4. The car parks in the assigned slot.
  5. Upon exit, the ticket is validated, payment is processed, and the slot is released.




Detailed Component Design

Representing the Lot

  • Levels: Parking structures are often multi-story. Each level may have its own entrance and exit.
  • Rows and slots: Within each level, slots are organized into rows for easy navigation.
  • Categories of slots:
    • Motorcycle slots (smaller footprint).
    • Car slots (standard).
    • Truck/bus slots (oversized).
    • Electric Vehicle (EV) slots with charging stations.

Slot Allocation Strategies

  • First-available: Assign the nearest available slot. Simple but may not be optimal.
  • Nearest-to-exit: Useful in high-traffic lots where quick exits are important.
  • Priority-based: Allocate based on vehicle type, reservations, or VIP access.
  • Dynamic allocation: Adjust assignments based on real-time occupancy trends.

Real-Time Tracking

  • Use sensors or cameras to detect slot occupancy.
  • The system updates the slot management database whenever a vehicle enters or exits.
  • A mobile app can show users the number of available slots in real time.

Data Model (simplified)

  • ParkingSlot (slotID, levelID, type, isAvailable, vehicleID)
  • Level (levelID, totalSlots, availableSlots)

In interviews, highlighting slot categorization, allocation algorithms, and real-time updates shows you can think beyond the basics of designing a parking lot System Design and optimize for usability.

Entry and Exit Flow Design

Smooth entry and exit flows are essential to prevent congestion. When figuring out how to design a parking lot System Design, this flow integrates physical infrastructure with backend logic.

Entry Flow

  1. Vehicle approaches the gate.
  2. System checks if slots are available.
  3. Ticket is generated (paper, digital, or license plate-based).
  4. A slot is assigned and reserved.
  5. Gate opens, and the car proceeds to park.

Exit Flow

  1. Driver approaches the exit gate.
  2. Ticket is scanned or license plate is recognized.
  3. Fee is calculated based on entry time and rate structure.
  4. Payment is processed (cash, card, or mobile).
  5. Slot is released and marked available.
  6. Gate opens for exit.

Handling Congestion

  • Multiple gates: Large lots often use several entry/exit points.
  • Load balancing: Assign vehicles across gates or levels to spread traffic.
  • Express lanes: For prepaid or digital-ticket users.

License Plate Recognition (LPR)

  • Replaces manual ticketing with automatic identification.
  • Reduces fraud and speeds up entry/exit.
  • Works best with high-quality cameras and OCR algorithms.


Ticketing and Validation System

Tickets are the backbone of accountability in how to design a parking lot System Design. They link a vehicle to a slot, a time, and ultimately, a payment.

Types of Tickets

  • Paper tickets: Generated at kiosks, contain barcodes or QR codes.
  • Digital tickets: Sent via SMS, app, or email.
  • License-plate tickets: Vehicle registration serves as the ticket.

Ticket Lifecycle

  1. Creation: Issued at entry with timestamp, vehicle ID, and slot assignment.
  2. Association: Stored in the database and linked to a slot.
  3. Validation: Checked at exit to ensure the ticket matches the vehicle and slot usage.
  4. Closure: Closed once payment is processed, and the slot is released.

Preventing Fraud

  • Ensure tickets cannot be reused at multiple exits.
  • Match vehicle details (plate number) with ticket data.
  • Store cryptographically signed ticket IDs for security.

Data Model (simplified)

  • Ticket (ticketID, vehicleID, slotID, entryTime, exitTime, status, fee)

In interviews, focusing on ticket lifecycle and fraud prevention demonstrates awareness of real-world issues in your answer for “design a parking lot System Design”, which goes beyond just “assigning slots.”

Payment System Integration

A parking lot isn’t just about allocating spaces—it’s also about revenue collection. When figuring out how to design a parking lot System Design, the payment system ensures accurate fee calculation, secure transactions, and a smooth user experience.

Payment Models

  • Flat rate: A fixed charge regardless of duration.
  • Hourly rate: Charge based on total time parked.
  • Tiered pricing: Different rates for short-term vs. long-term parking.
  • Subscription-based: Monthly passes for frequent users.

Payment Methods

  • Cash: Traditional but less convenient.
  • Card payments: Credit/debit card kiosks integrated with secure payment gateways.
  • Mobile/digital wallets: Apps like Google Pay, Apple Pay, or in-app payments.
  • Prepaid passes: Linked to user accounts, enabling fast exits.

Fee Calculation

  • At exit, the system checks the ticket’s entry time and current time.
  • Pricing rules are applied to compute the fee.
  • Any discounts or validations (e.g., hotel guests, employees) are factored in.

Security Considerations

  • Encryption: Protect sensitive card and transaction data.
  • Audit trails: Store payment logs for accountability.
  • Failover systems: If payment processors are down, allow offline validation and collect fees later.


Database Schema and Data Modeling

Behind every smooth entry, slot allocation, or payment is a well-structured database. When answering how to design a parking lot System Design, the schema must capture entities, relationships, and ensure real-time accuracy.

Core Entities

  1. Vehicle
    • vehicleID, licensePlate, type, ownerInfo.
  2. ParkingSlot
    • slotID, levelID, type (car, motorcycle, EV), isAvailable, currentVehicleID.
  3. Ticket
    • ticketID, vehicleID, slotID, entryTime, exitTime, status, fee.
  4. Payment
    • paymentID, ticketID, amount, method, timestamp, status.
  5. Level
    • levelID, totalSlots, availableSlots.

Relationships

  • vehicle is linked to a ticket.
  • ticket is linked to a slot and a payment.
  • slot belongs to a level.

SQL vs. NoSQL Considerations

  • SQL databases are useful for relational consistency (tickets, payments).
  • NoSQL databases can handle real-time availability tracking with fast updates.
  • In practice, a hybrid approach often works best.

Data Indexing

  • Index by license plate for fast lookups.
  • Index by slot availability to quickly allocate slots.
  • Index by ticket status for exit validation.


Concurrency and Synchronization

One of the biggest challenges in problems like design a parking lot System Design is handling concurrency. Multiple cars may enter or exit at the same time, and the system must ensure slot allocation and payments remain consistent.

Concurrency Scenarios

  • Two cars approach at once, both requesting the last available slot.
  • A vehicle exits while another is entering, releasing a slot at the same time it’s being requested.
  • Simultaneous payment transactions happening across multiple kiosks.

Techniques to Handle Concurrency

  1. Database Locks
    • Use row-level locks on slots to ensure only one vehicle can claim a space at a time.
    • Trade-off: can reduce throughput under heavy load.
  2. Optimistic Concurrency Control (OCC)
    • Allow multiple processes to attempt updates but validate before committing.
    • If a conflict occurs, retry with updated data.
  3. Distributed Queues
    • Route slot allocation requests through a queue.
    • Ensures sequential processing and avoids collisions.
  4. Atomic Transactions
    • Wrap ticket issuance and slot reservation in a single atomic transaction.
    • Prevents inconsistent states (like ticket issued but no slot reserved).

Synchronization Across Gates

  • Use a centralized slot manager service to coordinate across multiple entry/exit points.
  • Replicate data across nodes while ensuring consistency with consensus algorithms (e.g., Paxos, Raft).


Fault Tolerance and Reliability

A real parking lot system cannot afford to go down during rush hour. If gates stop working, payments fail, or tickets can’t be validated, it leads to chaos and lost revenue. That’s why fault tolerance is a cornerstone of your answer to “design a parking lot System Design”.

Common Failure Scenarios

  • Hardware failures: Kiosk screen malfunctions, gate sensor errors.
  • Software crashes: Ticketing service or slot manager goes offline.
  • Network outages: Cloud database or payment processor unavailable.
  • Power outages: Entire parking facility goes offline.

Fault Tolerance Strategies

  • Redundancy:
    • Multiple kiosks at busy gates.
    • Backup servers replicating ticketing and payment systems.
  • Graceful degradation:
    • Switch to manual ticketing if kiosks fail.
    • Allow exit with “flat fee” fallback if payment system is down.
  • Data replication:
    • Maintain multiple database replicas to prevent data loss.
    • Write-ahead logs (WALs) ensure ticket/payment info can be restored.
  • Monitoring and alerts:
    • Real-time dashboards track availability of gates, kiosks, and servers.
    • Automatic alerts notify staff when anomalies occur.

Reliability Considerations

  • High availability (HA): Aim for minimal downtime with load balancing and clustering.
  • Failover: If a primary service fails, a backup instance automatically takes over.
  • Self-healing systems: Automated scripts restart failed services without human intervention.


Scalability in Design a Parking Lot System Design

What works for a 50-car lot doesn’t necessarily work for a multi-level airport parking garage or a chain of lots across a city. Scalability ensures the system can grow without breaking.

Scaling Horizontally

  • Add more kiosks, entry/exit gates, and sensors.
  • Deploy additional backend servers for ticketing and slot management.
  • Use load balancers to distribute traffic evenly.

Scaling Across Multiple Lots

  • Treat each lot as a node connected to a centralized cloud service.
  • Centralized dashboards aggregate data from all locations.
  • Each lot operates independently but syncs with headquarters in real time.

Cloud and Edge Integration

  • Cloud services: Manage global reservations, payments, and analytics.
  • Edge computing: Handle real-time entry/exit decisions locally at each lot to reduce latency.

Bottlenecks and Solutions

  • Database overload: Use partitioning or sharding to spread load.
  • Payment processor limits: Integrate with multiple gateways.
  • Gate congestion: Add express lanes for prepaid users.

Trade-Offs in Scaling

  • Freshness vs. performance: Real-time slot tracking across thousands of lots may be expensive; periodic sync may be more practical.
  • Centralized vs. distributed control: Centralization simplifies management but may increase latency; distributed systems improve responsiveness but add complexity.