List the key functional requirements for the system (Ask the AI for hints if stuck)
User account: user should be able to signup/signin/signout their own account, add/delete/update their name, phone, email, payment method, and other personal setting. When user add/delete/update their phone and email, they should receive a link to verify by phone/email, and a 2-factor verification when add/delete/update their payment method.
Entry/exit gate: application generate a QR code or barcode for user to scan at the gate to record arrival and leave timestamp, which support application to calculate the fine or refund, and release the spot when user scan the code to leave.
Payment processing: user should be able to add/delete/update payment methods to their account, pay for the spot or parkin lot service by using their payment methods, cancel the spot and/or get refund, get recipt of successful payment.
Car spot assignment: user should be able to be assigned one or more spots from application, user should be able to select time, location of pakring lot, different tier of spot or parking lot service, and so on. The assigned spot should only be users and the spot should be unique.
Spot duration checking: application should be able to record the duration of each assigned spot, check when will the assigned spot is expried. If a assigned spot is expired, notify the assigned user, still keep the spot for assigned user until user empty the spot, set the spot as empty, no colck on it.
Timeout processing: if a assigned spot is expired, notify the assigned user by phone or email, add fine or addition fee to user if available. Mark the spot as expired but not empty, still map it to current user.
Notification service: application should be able to notify users by their phone or email for anything new, a retry phone or email will be sent if the user didn't check the phone/email or they didn't solve the issues in the notification.
Direction to spot: application should be able to show user direction from the user's location to the spot, no matter the user is to go to get their car or drive to that location.
List the key non-functional requirements (performance, scalability, reliability, etc.)
Scalability: it should be horizontal scaling, this application should be able to handle ten millions to billions of data and millions to ten millions requests per day from national or global, a single server with bigger setup would not handle the server crash issue, which is same as DB, so server and DB replicas are needed.
High availablity: user account, payment processing, Spot duration checking, Timeout processing, Entry/exit gate, and car spot assignment service must be abailable all the time, since they are all relates to essential functionalities of this application and all relates to user's fund, if any of them breaks it will cause damage to user's fund and lose their trust. Notification and direction to spot can tolerate a short outages.
Latency: Payment processing, Timeout processing, and Spot duration checking must be proceed under 1 minute (we will use third party service), user should pay for spot/services or get refund as quick as possible, car spot assignment should under 30 seconds, user should get their spot ~30s once they finish their spot fliter. For rest of services, they can tolerate higher latency since the user do not use them too much and their focus are on payment and spot.
Consistency: Once the user create their account, the data should always stay the same unless they update it by themselves. Once their spot is assigned, the spot should always assigned until user finished leaving. The user's personal data should never lost or they will not be able to login the application, the user's assigned spot data should never lost as well since the lost will cause user not be able to leave.
Estimate the scale of the system. Consider daily active users, read/write ratio, storage requirements, bandwidth, and any relevant QPS calculations.
Assuming this application is mid-sized, which is popular among some states instead of national wide, ~5000 parking lots are available on it.
Traffic: start with write side: assuming 1M books/day, it will be 365M books/year, with peak period, assume x5 times, write will be 5M books/day, ~1.9B books/year. Applying 1:10 write:read ratio, user will check their spot, service, direction to spot, service for ~10 times totally once they book spot or service on this application, the read side will be 10M reads/day, 3.65B/year, with peak, the read will be 50M reads/day, ~19B reads/year.
Storage: user ID (~8 bytes), QR / barcode (store the encoded payload string ~3 bytes), entry timestamp (~8 bytes), exipre timestamp (~8 bytes), spot location (~3 bytes), status (~4 bytes), payment method (~50 bytes). So for every books, there are roughly ~84 bytes, round up to 128 bytes for account metadata, indexing overhead, and padding.
Daily storage growth: 1M/day * 128 bytes * 365 = ~47 GB/year, over 5 years: 47 GB/year * 5 = 0.24 TB
Bandwidth: 1M books/day = ~11 books/sec * 128 bytes = ~1.5 KB/sec, with peak it is 7.5 KB/sec, acceptable
10M reads/day = ~110 reads/sec * 128 bytes = ~15KB, with peak it is 150KB/sec, acceptable.
Both write and read path are acceptable and will not be bottleneck.
Cache: assuming 50% of books count for 80% of traffic, we will need to cache at least top 50% of books (such as the books will expire in a specific date), 20% of total DB (0.24 TB over 5 years) will roughly ask for 48 GB of cache memory, if application cache the books which already activative for 80% of time interval per day with a ~60 GB cache memory can provides 80%-90% hit rate.
Define the APIs expected from the system. This is your chance to analyze and define the read and write paths so that you can come up with the high-level design.
Using HTTP RESTFul API
Payment APIs:
POST api/v1/pay : pay for spot or service
{spot_id (num), spot_tier (num), timestamp_start (date format), timestamp_start (date format), status (num), payment (text)}
success message: 201: spot_location (num), QR/barcode (string), start_time (date_format), end_time (date_format), timeout_rate (num).
error message: 406: payment not acceptable.
POST api/v1/refund : get refund if leave eariler
{spot_id (num), status (num), payment (text), timestamp_start (date format), timestamp_leave (date_format)}
success message: 200: payment_method (text, where refund should be returned to), refund (num)
error message: 404: refund are unavailable.
Spot APIs:
Get api/v1/spot : find the assigned spot
{spot_id (num), user_id (uuid/string)}
success message: 200: spot_location (num), rest_time (num), time_start (date_format), time_end (date_format), status (int)
error message: 404: not found spot_id
Get api/v1/spot_details: get spot's detail
{spot_id (num)}
success message: 200: spot_location (num), spot_tier (num), price (num), duration (date_format), availablity (bool)
error message: 404: not found spot_id
Post api/v1/spot: select a spot
{spot_id (num), start_time (date_format), end_time (date_format), spot_tier (num), spot_location (text)}
success message: 200: spot_location, price, availablity
error message: 406: the spot is unavailable
Post api/v1/spot/{spot_id}: reverse a spot
{spot_id, spot_location, spot_tier, time_start, time_end, payment}
success message: 200: QR/barcode, spot_location, duration, time_leave}
error message: 400: spot unavailable
Other APIs:
Post /checkin: time when user start using spot
{spot_id, spot_location, timestamp_start}
success message: 200
error message: 400
Post /checkout: time when user leave the spot
{spot_id, spot_location, timestamp_leave}
success message: 200
error message: 400
Get /capacity/{parking_lot_id}: get the total available spot in a parking lot
{parking_lot_id, time_interval}
success message: 200: total number of spot in a parking lot
error message: 404: no such parking lot.
Rate limiting: using an API gateway to avoid request from some IP to abuse the API services (we can use a bucket and counter to check which IP access the API too many times in a specific period, such as 100 times in one minute). Also add 429 error to API services to suggest user wait a sec and retry.
Describe the overall system architecture. Identify the main components needed to solve the problem end-to-end. Use the diagramming tool to create a block diagram.
Client: user who access this application from mobile or website and use the service.
CDN: since this application is popular among some states, so CDN are necessary to store the static assets, such as parking lot pictures, user pictures, and spot pictures, etc.
API Gateway/DNS: which can be used to protect application be abused from the same IP, enforce rate limits, handle auth.
Load balancer: distribute the load across server replicas to avoid single server overloaded, terminate TLS.
Server: the "backend" where application logic stays, which covers all services. It will has server replicas to avoid single server crashed. The load will be distributed by load balancer.
checkout/in service: user use the generated code to entry and leave the parking lot, this service will connect to DB and cache, so when user open the code it will get from cache instead of DB to avoid read latency.
spot service: it will provides find spot, get spot's detail, and reverse a spot. It will connect to DB and cache to avoid write and read latency.
noticification service: the application will use a third service and this service will not connects to DB or cache.
payment service: the application will use a third service to handle the payment process, the payment method will be store into DB and cache for refund process and avoid latency.
capacity service: this service is use to check if the parking lot has available spot and their spot's detail, the data will store in DB and cache to avoid latency.
Code generate service: this service is used to generate the checkin/out code, it will be stored in DB and cache to avoid read and write latency.
Reverse spot service: this service is used to reverse a user selected spot, it is write only, we can only store the reverse spot into DB and then update to cache to save latency.
The process of the relationship between services:
client->get parking lot capacity -> get spot details -> select spot -> reverse spot -> payment service -> PSP comfirm -> code issued -> gate validate when check in -> release spot when check out
To avoid 2 users looks on same spot, we will use read committed in a SQL DB, and we will not choose serializable to avoid process lock.
message queue: this application will not using any message queue or event bus since all service need to be done to move to next step, such as get a spot, user should check if the spot is available, user need to wait for payment finish to get the code, and so on.
Define the data model. Identify the main entities, their attributes, and relationships. Consider the choice of database type (SQL vs NoSQL) and justify your decision based on access patterns
DB selection: SQL and DB cache, to be more specific, we will use PostgreSQL and redis.
PostgreSQL Data schema:
User:
user_id PK snowflake bigint
name varchar
phone varchar unique
email varchar unique
create_at timestamp
Spot:
spot_id PK bigint
parking_lot_id FK bigint index->fetch all spots for a parking lot
spot_location bigint
price decimal
status/available boolean
spot_tier varchar
Parking_lot:
parking_lot_id PK bigint
name varchar
address text
location POINT(PostGIS)
rating DECIAML
is_open boolean
operating_hour JSONB
reversation:
reversation_id PK snowflake bigint
spot_id FK snowflake bigint
parking_lot_id FK bigint index
user_id FK bigint index
status enum: incoming, valid, end, timeout, canceled
price decimal
tax decimal
payment_id varchar reference to external payment service
duration timestamp
start_at timestamp
end_at timestamp
code JSONB
vehicle:
user_id snowflake bigint
spot_id bigint
car_plate JSONB
reversation_id FK bigint index
reversation_history:
user_id PK snowflask bigint
reversation_id FK bigint index
status enum
change_at timestamp
change_by bigint (user_id who make this change)
cache:
key: spot_id, value: gate code, parking_lot_id
user use the spot_id to get the code and parking_lot_id instead of loading from DB.
indexes:
spot: parking_lot_id -> fetch all spots in this parking_lot
reversation: user_id -> reversation history, parking_lot_id -> parking_lot spot status and available number
reversation_history: reversation_id -> history for a reversation.
DB sharding: instead of sharding by parking_lot_id, we use reversation_id and user_id instead to avoid double booking.
Deep dive into 2-3 key components. Explain how they work, how they scale, discuss tradeoffs, capacity, and any relevant algorithms or data structures.
Spot assignment / reversation commit:
Hold expiry / now-show sweeper:
Payment + PSP webhook: