My Solution for Design an Efficient Parking Lot System with Score: 8/10
by quest_celestial19
System requirements
Functional:
I'd like to focus on implementing the below functional requirements for the driver/user of the system.
- Check Availability: Users should be able to view real-time availability of parking spaces.
- Find Parking Space: Implement a feature that helps users locate available spaces, possibly using GPS for guidance.
- Reservation: Allow users to reserve a parking spot in advance.
- Payment Processing: Integrate payment options for users to pay for parking seamlessly.
- Notifications: Provide updates or alerts regarding parking status or payment confirmations.
Non-Functional:
- Availability: The system should be available for 99.99% of time, which means that the system can be down for 8 seconds in a day assuming there are 8x10^5 seconds.
- Low latency:
- For checking availability and payment, we need low latency. It should be able to finish instantly, e.g. within 200ms.
- Consistency: the system should have consistency
Capacity estimation
- Parking Capacity: With 500 parking spots and a turnover rate of 12 vehicles per spot per day, you expect to handle around 6,000 vehicle entries daily.
- Data Storage:
- Each vehicle's information, including entrance time, make, and license plate, totals approximately 10KB.
- Thus, daily data generation will be about 60MB, which is manageable for most database systems.
- Traffic Estimates:
- With one entrance and one exit, you're estimating peak traffic at one request every 5 seconds. This translates to approximately 12 requests per minute (720 requests per hour), which is still quite reasonable for a well-designed system.
API design
There will be those apis:
- Vehicle APIs:
- vehicleEnter: Handles when a vehicle enters, logging the license plate and entrance time.
- vehicleExit: Manages the exit process, checking for payment, and logging the exit time.
- Payment APIs:
- checkPayment: Verifies whether payment has been made and if additional payments are required before exit.
- makePayment: Interfaces with a third-party payment service to process payments, returning success or failure.
- Availability APIs:
- displayAvailability: Subscribes to updates for available parking lots and displays this information at the entrance.
- checkAvailability: Allows clients to check for available parking spots directly.
- Reservation:
- makeReservation: Enables users to reserve a parking space for up to an hour. Upon successful payment, it decreases the count of available spaces.
Here is a diagram how apis will be called:
Database design
We will have two database. One is the event database, and the other one will be status database.
Event Database:
- Purpose: To log and track events related to vehicles entering and exiting the parking lot, as well as payment transactions.
- Event Types:
- Entrance: Logs when a vehicle enters the parking, including a timestamp.
- Reserved: when a reservation is made.
- Payment Made: Records the payment amount and timestamp.
- Exit: Logs the timestamp when a vehicle exits.
- Key Design: Using the license plate as the primary key allows for easy retrieval of all events related to a specific vehicle, sorted by timestamp.
- Database Choice: Using Cassandra for this database is a good choice given its high availability and horizontal scalability, which suits my peak traffic requirements.
Status/Inventory Database:
- Purpose: Maintains real-time availability of parking spots.
- Operational Strategy:
- Decrease available spots upon vehicle entry and increase upon exit.
- Keep the current inventory status in service memory for rapid access.
- Save snapshots of the inventory into the database every minute.
- Recovery Strategy: In the event of a crash, you can rebuild the current inventory by combining the latest snapshot with events from the event database, ensuring data integrity.
High-level design
System Components:
- API Gateway: Acts as the entry point for all client requests, delegating them to appropriate services.
- Event Service:
- Handles incoming events (vehicle entry, payment, exit).
- Logs events to the event database.
- Updates the status inventory when necessary.
- Before vehicle exit, checks payment status either on request or conditionally.
- Inventory Service:
- Maintains an in-memory representation of available parking spots.
- Takes snapshots of the inventory every minute and stores this in the status database.
- Restores the inventory status from both the event database and snapshots.
- Broadcasts availability to the display at the parking entrance and other third-party services (e.g., Google Maps).
- Handles requests for checking availability.
- Event Database:
- Consists of one master database for write requests and one replica for read-only requests.
- Ensures strong consistency, and only returns success after all replicas have synced with the master.
- Payment Service:
- Checks if any payment is needed before allowing an exit.
- Interfaces with third-party payment platforms (like credit card services) for processing payments.
Request flows
Explain how the request flows from end to end in your high level design. Also you could draw a sequence diagram using the diagramming tool to enhance your explanation...
Detailed component design
Handling Failure:
- Rebuilding Inventory Status:
- Upon a service crash, the system will initiate a recovery process.
- The Inventory Service will check both the event database and the most recent inventory snapshot to restore the available parking spots.
- Any discrepancies can be resolved by cross-referencing events (entry and exit logs) within the event database.
Managing Reservations:
- Reservation Service:
- Responsible for creating and managing reservations within a one-hour window.
- When a reservation is made, it checks for available spots and reserves one for the user.
- A notification system will alert users before the reservation expires.
- Expiration Management:
- If a reservation is not claimed (i.e., the vehicle has not entered the parking lot) after one hour, the system automatically cancels the reservation.
- If payment was made, the reservation service will reverse the payment (if applicable) and return the parking spot to the inventory.
Event Database Recovery:
- Synchronized Replication:
- The system maintains one master database for handling write requests and one replica for read requests.
- Strong consistency is enforced: the event database acknowledges write success only when all replicas are synchronized with the master.
- If recovery is needed, the system can pull data from the replica to restore any lost writes.
Reservation System Enhancements:
- Reservation Condition:
- Before allowing a reservation, the system should check that there are at least 5 spots available.
- This ensures the inventory stays robust enough to accommodate on-site vehicles that may arrive suddenly.
- Prioritizing Waiting Vehicles:
- When assessing availability for reservations, the system should track vehicles that have been waiting to enter. You can implement a queue for vehicles that are waiting.
- When checking availability for a new reservation, the system should give priority to the queued vehicles. This would mean that if there are still spots available after accommodating waiting vehicles, only then can online reservations take place.
Proposed Workflow for Reservation:
- Check Availability:
- When a user requests to make a reservation, the system first verifies the number of waiting vehicles.
- If the number of available spots is less than or equal to 5 and there are waiting vehicles, the system rejects the reservation request and informs the user.
- Reservation Process:
- If the conditions are met (more than 5 available spots and no waiting vehicles), the system reserves a spot for the online user.
- It logs the reservation and waits for the user to enter the parking lot.
- Handle Waiting Vehicles:
- When a vehicle enters the parking lot, the system first accommodates waiting vehicles, if any, from the queue, ensuring they get priority access to the available spots.
Trade offs/Tech choices
Strong Consistency vs. Asynchronous Replication
- Strong Consistency:
- Advantages:
- Ensures that all reads return the most recent write. This is critical in high-stakes applications like parking reservations where double booking can lead to significant user frustration and operational challenges.
- Improves trust in the system as users can be confident that their reservations are accurately reflected in real time.
- Disadvantages:
- Imposes latency overhead as users must wait during the replication process; however, you’ve indicated that the latency for replication is less than 100ms, which aligns with your latency goals.
- This could lead to longer wait times for certain operations, particularly during peak usage, which can impact user experience.
- Advantages:
- Asynchronous Replication (not implemented in your design):
- Advantages:
- Would allow for faster read responses since writes could be confirmed without waiting for the replicas to catch up.
- Generally enhances system throughput by allowing writes to proceed without waiting for all replicas to be updated.
- Disadvantages:
- Increases the risk of stale reads, which could lead to double bookings or missed reservations as different replicas may not have synced up immediately.
- Would require additional mechanisms to handle reconciliation and potential conflicts, adding complexity.
- Advantages:
Failure scenarios/bottlenecks
System Recovery Mechanism
- Recovery from Replication:
- If the master database experiences a failure, the system will be able to quickly recover from the latest replicated data in the replica databases.
- During recovery, the system can fetch the most recent successful write from the replica and update the master to restore integrity.
- Recovery from Snapshots:
- The system will utilize periodic snapshots of the status/inventory database to recover inventory data in case of a system crash.
- Alongside the event database logs, these snapshots will help reconstruct the current state of the inventory dynamically and accurately.
- This process ensures minimal downtime and data loss.
Administrative Operations
- Admin Functionality:
- Manual Entry and Exit: Admins can manually override normal operations to allow vehicles to enter or exit, which is crucial for handling exceptional circumstances like emergencies or system malfunctions.
- Admins will have a specialized interface in the API Gateway through which they can send requests to:
- Allow a specific vehicle to enter the parking lot.
- Forcefully check out a vehicle in cases where the automated system fails.
- API Design for Admin Operations:
- Consider creating specific APIs tailored for administrative actions:
adminAllowEntry(licensePlate)
: Allows an admin to grant entry to a specified vehicle.adminForceExit(licensePlate)
: Permits an admin to forcefully log a vehicle's exit.adminViewStatus()
: Provides real-time insights into current parking inventory and events.
- Consider creating specific APIs tailored for administrative actions:
Future improvements
- Scalability:
- Adding More Replicas: As the user base grows, simply adding additional replicas can help distribute read traffic and improve overall system performance. This can reduce the load on the master database and provide faster access to data for reporting and queries.
- Partitioning: Implementing database partitioning can allow the system to handle larger volumes of data more efficiently. Partitioning by vehicle license plate or timestamp could help speed up queries and improve write performance.
- Horizontal Scaling: Plans for horizontal scaling would involve the ability to spin up additional servers or database instances as needed without architectural changes.
- Log Cleanup:
- Set up an automated process to periodically clean up old log entries in the event database.
- Implement retention policies that specify how long entries should be kept (e.g., keep logs for 30 days). This will help manage storage requirements and maintain performance, especially in a high-traffic environment.
- Visual Display of Available Spaces:
- Implementing a visual interface in the parking lots to show available spaces across different levels can greatly enhance user experience.
- This could involve digital signage that updates in real-time based on the inventory status. Sensors can track available spots and send updates to the Inventory Service.
- Admin Permissions Check:
- Introduce a permission-checking mechanism for admin actions to enhance security.
- Implement role-based access control (RBAC) where different admin roles are assigned specific permissions. For example, only certain users can allow vehicle entries or access sensitive data.
- This ensures that only authorized personnel can perform critical functions within the system.