Design a Time-Interval Vehicle Booking System
System DesignModel answerLast updated
Design a booking service for rental vehicles: availability search, temporary holds, confirmation, cancellation, concurrency control, and double-booking prevention.
Design a Time-Interval Vehicle Booking System
Background
A vehicle rental platform lets customers find and reserve cars at various locations. A customer picks a location, specifies a pickup and return window, browses available vehicles, places a hold, and then either confirms or abandons it. Because the fleet is finite, multiple customers may race to claim the same car or the last car in a given class.
What to Design
Describe the system end to end:
- APIs — what endpoints exist, what they accept, and what they return
- Data model — how vehicles, availability, holds, and confirmed reservations are stored
- Availability search — how the system finds vehicles free during a requested interval
- Hold and confirmation flow — the lifecycle from search result to confirmed booking
- Concurrency control — how the system guarantees no vehicle is double-booked
- Degraded inventory handling — what happens when the item a customer holds is no longer available by the time they confirm
Key Question
Search results are inherently advisory — they reflect a snapshot that may already be stale. At exactly which step must the system enforce that the vehicle is still free, and what mechanism makes that enforcement safe?
Constraints and Assumptions to Address
- A single vehicle cannot be committed to two overlapping bookings.
- Holds that are never confirmed must expire automatically and release inventory.
- Clients and background workers may retry any request; the system must behave correctly under retries.
- Availability search may return slightly stale data, but a confirmation must never produce a double-booking.
- State whether a customer books a specific vehicle or a vehicle class, and justify the choice.
Clarifying Questions Worth Raising
- Are customers booking an exact car (by plate or ID) or any car within an equivalent class?
- Can pickup and return happen at different locations, and how does that affect fleet availability modeling?
- How long is a hold valid, and can a customer extend it?
- When the last vehicle in a class is taken, does the system offer a waitlist, an upgrade, or simply a rejection?
Hints
Hint 1
Start with the reservation state machine: sketch every state a booking can be in (e.g., SEARCHING, HELD, CONFIRMED, CANCELLED, EXPIRED) and every valid transition before touching APIs or storage.
Hint 2
The hardest constraint is atomic inventory claim. Think about how a relational database row-level lock or an optimistic-concurrency version check lets you detect a conflict at the exact moment of hold creation — not at search time.
Hint 3
Hold expiry is an inventory leak if not handled. Consider a background sweeper versus a lazy expiry check on read, and think about what happens to in-flight confirmation requests when a hold expires mid-flight.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifying Assumptions
Before designing anything, nail down scope. A reasonable baseline: customers book a vehicle class (e.g., compact, SUV) rather than a specific car. This decouples fleet assignment from the booking flow — you assign an actual vehicle at pickup — and makes availability math simpler. One-way rentals (different pickup/return locations) are supported but treated as a stretch goal. Holds last 15 minutes and are not extendable by default.
Reservation State Machine
Every booking moves through a fixed set of states:
HELD → CONFIRMED → COMPLETED
↓
CANCELLED
HELD → EXPIRED (background worker or lazy check)
No transition is allowed out of sequence. This state machine drives both the API design and the concurrency rules: you can only confirm a HELD booking, and a HELD booking that has passed its expiry timestamp is treated as EXPIRED regardless of what the row says.
Data Model
Three core tables (relational storage fits well here because you need transactions):
vehicles_class — class ID, location, total fleet count
reservations — reservation ID, class ID, location, customer ID, pickup time, return time, state, hold expiry, version (for optimistic locking), created/updated timestamps
inventory_holds — a denormalized count or a lock row used during atomic claims (see below)
For interval conflict detection, the standard overlap predicate is:
existing.pickup < requested.return AND existing.return > requested.pickup
Index on (class_id, location, state, pickup, return) to make this query fast.
APIs
| Method | Path | Purpose |
|---|---|---|
| GET | /availability?class=&location=&from=&to= | Search available vehicles |
| POST | /holds | Claim a hold on an inventory unit |
| POST | /reservations | Confirm a held booking |
| DELETE | /holds/{holdId} | Cancel a hold early |
| DELETE | /reservations/{reservationId} | Cancel a confirmed booking |
| GET | /reservations/{reservationId} | Fetch current status |
All mutating endpoints are idempotent via a client-supplied idempotency-key header. The server stores the key and returns the cached response on a duplicate request. This makes retries safe without double-creating holds or double-charging.
Availability Search
Search reads from a replica or a cache. It counts confirmed reservations and unexpired holds that overlap the requested interval and subtracts from total fleet count. Because it runs against a replica, results may be a few seconds stale. That is acceptable: search is advisory. The contract the system must guarantee is not "search is always accurate" but "you can never confirm a booking that conflicts with an existing one."
Hold Creation — The Critical Atomic Step
This is the core of the design. When a customer requests a hold, the system must:
- Re-check availability inside a transaction on the primary database.
- If slots remain, insert a new
reservationsrow in stateHELDwith an expiry timestamp. - Commit atomically. If a concurrent transaction snuck in first and consumed the last slot, this transaction sees the conflict and returns
409 Conflict.
With a relational DB, the conflict check and insert are a single serializable transaction or a SELECT ... FOR UPDATE on the inventory count row. With optimistic locking, you read a version number, do the math, and write back with a WHERE version = ? — a zero-row update means someone else moved first, and you retry or reject.
Common mistake: doing the availability check at search time and trusting it at confirmation time. Those two moments are separate; only the atomic write is authoritative.
Hold Expiry
Two approaches, usually combined:
- Background sweeper: a worker runs every minute, finds HELD rows past their expiry timestamp, and transitions them to EXPIRED. Simple and reliable for cleanup.
- Lazy check on read: before honoring any operation on a hold, the API checks whether
now > hold_expiry. If so, it rejects the request and marks the row EXPIRED. This catches the edge case where the sweeper is behind.
If a confirmation request arrives for an already-expired hold, the system returns a clear error (hold_expired) and the client must start over with a new hold.
Handling Inventory Exhaustion
When POST /holds fails because no slots remain:
- Return
409with a structured body indicating the reason (no_inventory). - Optionally include available substitute classes (e.g., same location, overlapping interval, adjacent class tier).
- For high-demand scenarios, offer a waitlist entry: a lightweight record that gets promoted to a hold if a cancellation frees up a slot.
Scaling and Partitioning
Partition reservations by (location, class_id). Hot inventory (a specific class at a busy airport) contends on a narrow set of rows, which is fine for a relational lock. For very high write throughput, move the inventory counter into Redis with a Lua script for atomic decrement-if-positive, using the database as the durable record of truth and syncing asynchronously.
Observability
Key metrics: hold-to-confirmation rate (low rate signals UX friction or inventory exhaustion), conflict rate at hold creation (high rate signals undersupply), hold expiry rate, and p99 latency on the availability search endpoint. Alert on double-booking incidents at the database level — they should never occur, so even one is a severity-1 event.
Common Mistakes to Avoid
- Trusting search results at confirmation: search is advisory; enforcement happens at the atomic write.
- Not handling retries: without an idempotency key, a network timeout leads to duplicate holds.
- Forgetting hold expiry inventory release: expired holds that are never cleaned up silently reduce apparent availability.
- Over-engineering specific-car assignment: assigning a plate at booking time rather than pickup time complicates fleet logistics with no customer benefit.