Vehicle Rental Relational Schema and Booking APIs

Hard · System Design · Software Engineer · Technical Screen

Prompt

Design the relational database schema, transactional backend workflows, and REST API surface for a multi-branch vehicle rental platform.

Core domain & schema scope:

  • Model the core domain entities and their relationships: renters/customers, physical fleet units, vehicle categories/classes, rental branches, branch inventory pools and temporary holds, bookings/reservations, active rental contracts, branch employees/staff, outbound/inbound inspections and damage reports, rate schedules, promotional codes, optional protection/equipment add-ons, and payment records.
  • Write concrete SQL table definitions specifying primary keys, foreign keys, uniqueness invariants, check constraints, and targeted indexes (especially for fast branch-and-window availability lookups and active-contract invariants).

Workflows & consistency guarantees:

  • Availability search: Query open vehicle categories for a chosen branch and pickup/return window, returning itemized pricing.
  • Booking lifecycle: Create, modify, and cancel reservations using short-lived checkout holds so concurrent shoppers never double-book fleet capacity.
  • Counter pick-up & lot return: Assign a ready physical vehicle at check-out, capture pre-trip inspection details, and generate a signed rental contract; at return, record odometer mileage, fuel level, and any new damage, computing late fees, overage charges, and final settlement.
  • Pricing & payments: Calculate base daily tariffs, mileage allowances/overages, insurance and equipment add-ons, promotional discounts, and local taxes/fees; manage card pre-authorizations, final captures, partial releases, and refunds safely across network retries.

API & system engineering concerns:

  • Specify 3–5 representative REST endpoints with concrete request and response payloads covering availability search, reservation creation, reservation modification, counter pick-up, and return settlement.
  • Address idempotency keys, list pagination, authentication and role-based authorization, concurrency control (pessimistic row locking vs. optimistic version checks), and horizontal scaling (caching hot availability lookups, read replicas, and partitioning by branch or geographic region).

Scope & Expectations

  • Propose a normalized relational schema with primary/foreign keys, integrity constraints, and indexes tailored for overlap queries and active-rental safety.
  • Define 3–5 clean REST endpoints with request/response shapes, idempotency semantics, cursor pagination, and role-based access control.
  • Walk through concurrency-safe transactions for inventory holds, reservation edits, counter pick-up, lot return, cent-accurate pricing, and fault-tolerant payment settlement.
  • Outline a practical scaling architecture combining in-memory availability caching, read replicas, and regional/branch partitioning.

Step-by-step walkthrough

  1. Clarify requirements and core domain choice

    Car rental system design lives or dies on one foundational modeling question you should ask in the first two minutes: does a customer book a specific license plate, or a vehicle category ("Midsize — Toyota Camry or similar")?

    Just like real-world fleets (Enterprise, Hertz, Avis), we separate booking a vehicle type (reservation against a branch's fleet_pool) from driving away in a physical car (rental bound to a specific vehicle_id at the counter). That single split keeps cars interchangeable when flights are delayed or a tire goes flat, and lets us prevent double-booking by checking pool capacity rather than packing individual car calendars months in advance.

    Functional requirements

    • Search: Given pick-up branch, pick-up/return timestamps, optional promo code, and driver age, return available vehicle types with exact itemized pricing.
    • Reservations with temporary holds: Place a 15-minute inventory hold during checkout so a car does not vanish while the customer enters payment details, then confirm, modify (dates, type, add-ons), or cancel.
    • Pick-up workflow (counter): Verify driver license and age, authorize card (estimated total + security deposit), assign a ready physical car (or free upgrade), record outbound inspection (odometer, fuel, photos, prior damage), and generate a signed contract.
    • Return workflow (lot): Record return time, odometer, fuel level, and any new damage; compute final charges (extra days after grace period, overage miles, refuel fee, taxes); capture final payment and release unused deposit.
    • Pricing, promotions, and payments: Versioned daily rates, mileage allowances, insurance/equipment add-ons, promo caps, jurisdiction taxes/fees, plus safe payment authorization, capture, and refunds.

    Non-functional requirements and explicit scope assumptions

    • Zero double-booking (strong consistency on writes): Confirmed + active holds at any instant in [pickup_at, return_at + turnaround) never exceed the branch pool's rentable units.
    • Fast search (< 300 ms p99): Search may tolerate 1–2 seconds of cache staleness, because the reservation transaction re-verifies exact availability under a lock.
    • Exact, auditable money: Store all amounts in integer cents (bigint) + ISO currency (USD), freeze quoted unit rates at booking time, and make invoice charges append-only.
    • Core scope: Round-trip rentals (return to pick-up branch) in North America and Europe; one-way rentals and intentional overbooking are covered in follow-ups.
  2. Back-of-the-envelope numbers

    Let us size a large multi-region rental company so we know whether write throughput or read/search throughput is our real bottleneck:

    1. Physical scale
       1,000 branches (300 airports) * ~10 vehicle types/branch = ~10,000 fleet pools
       100,000 physical vehicles total; 75% utilization -> ~75,000 cars on the road at once
       Average rental length = 4 days -> 75,000 / 4 ≈ 19,000 pick-ups/day & 19,000 returns/day
    
    2. Transactional write load
       ~50,000 checkout holds/day -> ~25,000 confirmed bookings/day (~25% cancel/no-show -> 19k pick-ups)
       Total DB write transactions/day (holds + confirms + edits + pick-ups + returns + payments):
         ~180,000 txns/day ≈ 2 writes/s average, ~20 writes/s at 10x holiday peak!
    
    3. Search read load (look-to-book ratio = searches per confirmed booking)
       Direct + travel-aggregator traffic at 100:1 look-to-book = 2.5M searches/day (~30/s avg)
       Design target for partner bursts (1,000:1)              = ~1,500 searches/s
    
    4. Active working-set & storage sizes
       Live reservations (14-day avg lead time * 25k/day + 75k active) ≈ 425,000 live rows total
         Average pool: ~42 live rows; busiest airport pool (e.g. SEA Midsize): ~2,000 live rows
         Entire fleet's live availability timelines in RAM: 425,000 * ~40 bytes ≈ 17 MB!
       Relational history (reservations, quotes, charges, events): ~4 KB * 50k/day ≈ 75 GB/year
       Inspection photos (8 photos * 1 MB * 2 inspections * 19k/day): ~300 GB/day ≈ 110 TB/year
    

    Three design conclusions jump straight out of these numbers:

    1. Database write rate (~2–20 txns/s) is tiny. A single PostgreSQL primary (with a synchronous standby) handles 100x this write rate effortlessly—so we should lean heavily on ACID transactions, row locks, and relational constraints rather than premature NoSQL sharding.
    2. Search outnumbers writes by ~100:1. Serving 1,500 searches/s off a 17 MB Redis/in-memory cache of per-pool timelines keeps read load off the primary database completely.
    3. Photos (~110 TB/year) belong in object storage (S3), uploaded directly from branch tablets via pre-signed URLs so our API servers only handle metadata keys.
  3. REST API design, idempotency, pagination, and auth

    All monetary fields use integer *_cents + currency. Every state-changing POST requires Idempotency-Key (a client-generated UUID per logical attempt so network retries never create two holds or charge twice); every PATCH requires If-Match: "<version>" (optimistic concurrency control so two editors cannot overwrite each other's changes).

    1. Search availability & generate frozen price quotes
    POST /v1/search
    Body: { "pickup_branch_id": "SEA01",
            "pickup_at": "2026-12-04T10:00:00-08:00",
            "return_at": "2026-12-07T10:00:00-08:00",
            "promo_code": "AUTUMN10", "driver_age": 30 }
    200 OK:
      { "as_of": "2026-12-01T18:00:02Z",
        "offers": [
          { "vehicle_type": { "code": "MIDSIZE", "name": "Toyota Camry or similar", "seats": 5 },
            "available": true,
            "quote_id": "q_8f2c", "quote_expires_at": "2026-12-01T18:15:02Z",
            "price": { "days": 3, "base_cents": 15600, "discount_cents": -1560,
                       "taxes_fees_cents": 4334, "total_cents": 18374, "currency": "USD" } } ] }
    
    2. Place a 15-minute checkout hold, then confirm
    POST /v1/reservations                       Headers: Idempotency-Key: 5d3b9f0e-...
    Body: { "quote_id": "q_8f2c",
            "addons": [ { "code": "CDW" }, { "code": "CHILD_SEAT", "quantity": 1 } ],
            "driver": { "first_name": "Maya", "last_name": "Lin", "license_no": "...",
                        "license_country": "US", "date_of_birth": "1994-05-02" },
            "payment_mode": "PAY_LATER" }
    201 Created: { "reservation_id": "r_19ab", "confirmation_code": "K7Q-4M2",
                   "status": "HELD", "hold_expires_at": "2026-12-01T18:15:30Z", "version": 1,
                   "price": { "total_cents": 30528, "currency": "USD", "lines": [...] } }
    409 SOLD_OUT | 410 QUOTE_EXPIRED | 422 IDEMPOTENCY_KEY_REUSED
    
    POST /v1/reservations/r_19ab/confirm        Headers: Idempotency-Key: 0c41...
    Body: { "payment_method_token": "pm_tok_..." }
    200 OK: { "reservation_id": "r_19ab", "status": "CONFIRMED", "version": 2 }
    
    3. Modify dates or add-ons (optimistic version check)
    PATCH /v1/reservations/r_19ab               Headers: If-Match: "2", Idempotency-Key: 77aa...
    Body: { "return_at": "2026-12-08T10:00:00-08:00", "quote_id": "q_91d0" }
    200 OK (version: 3) | 409 SOLD_OUT (original booking kept intact!) | 412 VERSION_MISMATCH
    
    4. Counter pick-up (staff role at branch)
    POST /v1/reservations/r_19ab/pickup         Headers: Idempotency-Key: 9e02...
    Body: { "vehicle_id": "veh_8410", "odometer_miles": 12043, "fuel_eighths": 8,
            "inspection": { "photo_keys": [...], "existing_damage": [] },
            "payment_method_token": "pm_tok_...", "signature_id": "sig_88" }
    201 Created: { "rental_id": "rt_7c1", "vehicle": { "plate": "7TRK490", "type": "MIDSIZE" },
                   "authorization": { "amount_cents": 50528, "status": "AUTHORIZED" },
                   "contract_url": "https://..." }
    
    5. Lot return & final settlement
    POST /v1/rentals/rt_7c1/return              Headers: Idempotency-Key: 4b6d...
    Body: { "returned_at": "2026-12-07T13:10:00-08:00", "branch_id": "SEA01",
            "odometer_miles": 12993, "fuel_eighths": 6,
            "inspection": { "photo_keys": [...], "new_damage": [] } }
    200 OK: { "status": "RETURNED",
              "invoice": { "total_cents": 47658, "currency": "USD", "lines": [...] },
              "payment": { "capture_cents": 47658, "release_cents": 2870, "status": "PENDING" } }
    

    Pagination, authentication, and authorization

    • Cursor (keyset) pagination on list endpoints (GET /v1/customers/me/reservations?limit=20&cursor=..., GET /v1/branches/SEA01/pickups?date=2026-12-04&limit=50&cursor=...): the opaque cursor encodes the last item's (pickup_at, reservation_id) and queries WHERE (pickup_at, reservation_id) > (:t, :id) via a B-tree index. Unlike OFFSET 5000, cursor pagination stays O(limit) fast and never skips or duplicates rows when new bookings arrive mid-scroll.
    • AuthN & AuthZ: Customers authenticate via OAuth 2.0 JWTs (scoped strictly to customer_id == token.sub); partners use mTLS/API keys with per-partner rate limits; staff sign in via corporate SSO with branch-scoped RBAC (AGENT can execute pick-up/return at assigned branches; MANAGER can waive fees; FINANCE approves large refunds). Card numbers never touch our servers—only tokenized pm_tok_... strings from the payment provider's client SDK.
  4. Relational database schema, constraints, and indexes

      customers (1) ----< (N) reservations (N) >---- (1) fleet_pools (branch_id, vehicle_type_id)
                                  |    |                        |
                       (1:1)      |    | (1:0..1)               | (1:N)
                   price_quotes <-+    +-> rentals (N) >--- (1) vehicles
                    + addons / promos         |
                                              +--< inspections (PICKUP, RETURN) & damage_reports
                                              +--< charges (append-only invoice lines) & payments
    
    CREATE TABLE branches (
      branch_id      bigserial PRIMARY KEY,
      code           text NOT NULL UNIQUE,            -- e.g. 'SEA01'
      region_id      int  NOT NULL,
      time_zone      text NOT NULL,                   -- IANA zone, e.g. 'America/Los_Angeles'
      currency       char(3) NOT NULL,
      opening_hours  jsonb NOT NULL
    );
    
    CREATE TABLE vehicle_types (
      vehicle_type_id int  PRIMARY KEY,
      code            text NOT NULL UNIQUE,           -- e.g. 'MIDSIZE'
      name            text NOT NULL,                  -- 'Toyota Camry or similar'
      seats           int  NOT NULL,
      upgrade_rank    int  NOT NULL                   -- monotonic tier order for free counter upgrades
    );
    
    -- Unit of inventory capacity AND row-level concurrency locking:
    CREATE TABLE fleet_pools (
      branch_id       bigint NOT NULL REFERENCES branches,
      vehicle_type_id int    NOT NULL REFERENCES vehicle_types,
      units           int    NOT NULL CHECK (units >= 0),
      turnaround_min  int    NOT NULL DEFAULT 60,     -- cleaning/prep buffer added after return_at
      version         bigint NOT NULL DEFAULT 0,      -- incremented on every pool mutation for cache sync
      PRIMARY KEY (branch_id, vehicle_type_id)
    );
    
    CREATE TABLE vehicles (
      vehicle_id        bigserial PRIMARY KEY,
      vin               text   NOT NULL UNIQUE,
      plate_region      text   NOT NULL,
      plate             text   NOT NULL,
      vehicle_type_id   int    NOT NULL REFERENCES vehicle_types,
      current_branch_id bigint NOT NULL REFERENCES branches,
      status            text   NOT NULL,              -- AVAILABLE | RENTED | CLEANING | MAINTENANCE | RETIRED
      odometer_miles    int    NOT NULL,
      fuel_eighths      int    NOT NULL CHECK (fuel_eighths BETWEEN 0 AND 8),
      tank_gallons      numeric(4,1) NOT NULL,
      version           bigint NOT NULL DEFAULT 1,
      UNIQUE (plate_region, plate)
    );
    -- Partial index so counter car lookup scans only ready cars at that branch:
    CREATE INDEX vehicles_ready_idx ON vehicles (current_branch_id, vehicle_type_id)
      WHERE status = 'AVAILABLE';
    
    CREATE TABLE reservations (
      reservation_id         bigserial PRIMARY KEY,
      confirmation_code      text        NOT NULL UNIQUE,
      customer_id            bigint      NOT NULL,    -- FK -> customers
      pickup_branch_id       bigint      NOT NULL,
      return_branch_id       bigint      NOT NULL REFERENCES branches,
      booked_vehicle_type_id int         NOT NULL REFERENCES vehicle_types, -- rate customer pays
      vehicle_type_id        int         NOT NULL,                          -- pool occupied (changes on upgrade)
      pickup_at              timestamptz NOT NULL,
      return_at              timestamptz NOT NULL CHECK (return_at > pickup_at),
      occupied_until         timestamptz NOT NULL,    -- precomputed return_at + turnaround_min
      status                 text        NOT NULL,    -- HELD | CONFIRMED | CHECKED_OUT | COMPLETED
                                                      -- | CANCELLED | EXPIRED | NO_SHOW
      hold_expires_at        timestamptz,
      quote_id               uuid        NOT NULL,    -- FK -> price_quotes (frozen pricing snapshot)
      payment_mode           text        NOT NULL,    -- PAY_LATER | PREPAID
      version                bigint      NOT NULL DEFAULT 1,
      created_at             timestamptz NOT NULL DEFAULT now(),
      -- Composite FK ensures you can only book a vehicle_type actually offered at that branch:
      FOREIGN KEY (pickup_branch_id, vehicle_type_id) REFERENCES fleet_pools,
      CHECK ((status = 'HELD') = (hold_expires_at IS NOT NULL))
    );
    -- Partial covering index: stays ~425k rows forever regardless of 10-year historical table growth!
    CREATE INDEX reservations_live_idx ON reservations (pickup_branch_id, vehicle_type_id, pickup_at)
      INCLUDE (occupied_until, status, hold_expires_at)
      WHERE status IN ('HELD', 'CONFIRMED', 'CHECKED_OUT');
    CREATE INDEX reservations_customer_idx ON reservations (customer_id, pickup_at DESC, reservation_id);
    
    CREATE TABLE rentals (
      rental_id        bigserial PRIMARY KEY,
      reservation_id   bigint      NOT NULL UNIQUE REFERENCES reservations, -- 1 contract per booking
      vehicle_id       bigint      NOT NULL REFERENCES vehicles,
      pickup_staff_id  bigint      NOT NULL,          -- FK -> staff
      picked_up_at     timestamptz NOT NULL,
      due_at           timestamptz NOT NULL,
      odometer_out     int         NOT NULL,
      fuel_out_eighths int         NOT NULL,
      returned_at      timestamptz,
      return_branch_id bigint      REFERENCES branches,
      odometer_in      int,
      fuel_in_eighths  int,
      status           text        NOT NULL,          -- ACTIVE | RETURNED | CLOSED
      contract_key     text        NOT NULL,          -- S3 key of signed PDF contract
      contract_sha256  text        NOT NULL,
      version          bigint      NOT NULL DEFAULT 1,
      CHECK (odometer_in IS NULL OR odometer_in >= odometer_out)
    );
    -- Partial unique index: database guarantees a physical car cannot be on 2 open contracts!
    CREATE UNIQUE INDEX rentals_one_active_per_car_idx ON rentals (vehicle_id)
      WHERE status = 'ACTIVE';
    CREATE INDEX rentals_overdue_idx ON rentals (due_at) WHERE status = 'ACTIVE';
    
    CREATE TABLE payments (
      payment_id        uuid        PRIMARY KEY,      -- passed directly to Stripe/Adyen as idempotency key
      reservation_id    bigint      NOT NULL REFERENCES reservations,
      rental_id         bigint      REFERENCES rentals,
      kind              text        NOT NULL,         -- AUTHORIZE | CAPTURE | CHARGE | REFUND | VOID
      parent_payment_id uuid        REFERENCES payments,
      purpose           text        NOT NULL,         -- 'prepay', 'pickup_auth', 'return_capture', ...
      amount_cents      bigint      NOT NULL CHECK (amount_cents > 0),
      refunded_cents    bigint      NOT NULL DEFAULT 0,
      currency          char(3)     NOT NULL,
      status            text        NOT NULL,         -- PENDING | SUCCEEDED | FAILED | UNKNOWN
      provider_ref      text        UNIQUE,
      UNIQUE (reservation_id, purpose),
      CHECK (refunded_cents BETWEEN 0 AND amount_cents)
    );
    
    CREATE TABLE idempotency_keys (
      principal      text        NOT NULL,            -- e.g. 'customer:42', 'staff:310', 'partner:7'
      key            text        NOT NULL,
      request_hash   text        NOT NULL,
      status         text        NOT NULL,            -- IN_PROGRESS | DONE
      response_code  int,
      response_body  jsonb,
      locked_until   timestamptz NOT NULL,
      PRIMARY KEY (principal, key)
    );
    

    Supporting tables (summary): customers (license_no_enc encrypted at rest), staff + staff_branches (M:N branch permissions), capacity_blocks (scheduled maintenance / cleaning / fleet-transfer deductions against fleet_pools), rate_plans (daily rate + included miles + per-mile cents by branch/region/season), addon_products (CDW, LIABILITY, CHILD_SEAT, GPS) + reservation_addons, promotions + promotion_redemptions, tax_rules, price_quotes (immutable JSON line-item snapshot + expires_at), inspections (UNIQUE (rental_id, phase) for PICKUP/RETURN), damage_reports, charges (append-only invoice lines), and outbox (transactional outbox table for reliable async event publishing).

  5. High-level architecture

      Web / Mobile App             Travel Aggregators            Branch Counter Tablets
             \                             |                             /
              v                            v                            v
      [ API Gateway: TLS, OAuth JWT / SSO / Partner Keys, Per-Client Rate Limits ]
              |                            |                            |
              v                            v                            v
      [ Search Service ]         [ Reservation Service ]       [ Counter Service ]
        (Read-only, stateless)     (Hold, Confirm, Patch,        (Pick-up, Return, Upgrades,
              |        |            Cancel)                       Inspections, Contracts)
              |        +---------> [ Pricing Library ] <---------+      |
              v                            |                            v
      [ Redis Pool Cache ]       [ PostgreSQL Primary  ]       [ Object Storage (S3) ]
        (~17 MB timelines)         + Sync AZ Standby             (Photos, Signed PDFs)
              ^        |                   |         \
              |   miss +--------> [ Read Replicas ]   +--> [ Payment Worker ] <--> Stripe / Adyen
              |                                                   ^
      [ Outbox Relay ] ---> [ Event Bus ] ------------------------+ (cache invalidation, captures,
                                                                     refunds, receipts)
    

    Notice how cleanly read and write paths separate:

    • Search path (read-only): Reads the ~10 pool timelines for the requested branch from Redis (falling back to a read replica on a miss), computes peak overlap in memory, prices available types via the pure Pricing Library, writes a price_quotes snapshot, and returns in < 20 ms.
    • Reservation & counter paths (strongly consistent): Execute short, lock-ordered ACID transactions on the PostgreSQL primary. External payment calls never happen inside a database transaction.
  6. Deep dive 1: Preventing double-booking with holds and sweep-line locking

    Why counting overlapping rows is wrong—we need peak simultaneous overlap! Suppose SEA has 2 MIDSIZE cars (units = 2) and a customer searches Mon–Fri. Imagine three 1-day bookings already exist: Mon–Tue, Tue–Wed, and Wed–Thu (all on the same car sequentially!). A naive SELECT COUNT(*) WHERE overlap sees 3 >= 2 and falsely says SOLD OUT, even though at most 1 car is ever in use at once!

    SEA MIDSIZE Pool (units = 2):
      Mon       Tue       Wed       Thu       Fri
      |[Car A]--|                             |     <- Booking 1 (Mon-Tue)
                |[Car A]--|                   |     <- Booking 2 (Tue-Wed)
                          |[Car A]--|         |     <- Booking 3 (Wed-Thu)
      |[========= New Mon-Fri Request =======]|     <- Uses Car B! Peak simultaneous usage = 2 <= 2 (FITS!)
    

    By the classic interval-partitioning theorem, interchangeable cars can fulfill all bookings if and only if at every instant t, active_bookings(t) + capacity_blocks(t) <= units. We compute the exact peak inside [window_start, window_end) in O(K log K) time over the pool's K overlapping intervals using a sweep-line algorithm:

    def peak_usage(intervals: list, window_start, window_end) -> int:
        """Return maximum simultaneous units in use inside [window_start, window_end).
        Each entry in `intervals` is (start_time, end_time, unit_count)."""
        events = []
        for start, end, count in intervals:
            if start < window_end and end > window_start:
                events.append((max(start, window_start), +count))
                events.append((min(end, window_end), -count))
        # Sorting tuples puts (t, -count) BEFORE (t, +count) at identical timestamps, so a car whose
        # cleaning finishes at 11:00 is freed before a 11:00 pick-up is counted!
        events.sort()
        current_used = 0
        max_used = 0
        for _, delta in events:
            current_used += delta
            if current_used > max_used:
                max_used = current_used
        return max_used
    

    Preventing write skew with row-level pool locking. Even with exact peak_usage, if two customers click "Book" on the last MIDSIZE car at the exact same millisecond, both transactions could read peak = 19 < 20 and both insert—creating a 21st booking! That concurrency bug is called write skew (two transactions read overlapping data and make separate inserts that together break an invariant; no UNIQUE index can prevent it).

    We serialize writers of the same (branch_id, vehicle_type_id) using a pessimistic row lock (SELECT ... FOR UPDATE) on fleet_pools under PostgreSQL READ COMMITTED isolation:

    BEGIN;  -- Isolation level: READ COMMITTED
    
    -- Step 1: Lock ONLY this (branch, vehicle_type) pool row (~2-5 ms hold time).
    -- Concurrent bookings at other branches or other car types do NOT wait!
    SELECT units, turnaround_min
      FROM fleet_pools
     WHERE branch_id = :branch AND vehicle_type_id = :type
       FOR UPDATE;
    
    -- Step 2: Under PostgreSQL READ COMMITTED, this SELECT takes a fresh snapshot AFTER Step 1's
    -- lock is granted, so it is guaranteed to see any reservation just committed by a prior holder!
    -- Notice expired holds (hold_expires_at <= clock_timestamp()) vanish automatically with zero cron lag!
    SELECT pickup_at, occupied_until
      FROM reservations
     WHERE pickup_branch_id = :branch
       AND vehicle_type_id = :type
       AND status IN ('HELD', 'CONFIRMED', 'CHECKED_OUT')
       AND (status <> 'HELD' OR hold_expires_at > clock_timestamp())
       AND pickup_at < :occupied_until
       AND occupied_until > :pickup_at;
    
    -- (Also fetch overlapping rows from capacity_blocks for the same pool.)
    -- Step 3: Application checks peak_usage(...) + 1 <= units. If false -> ROLLBACK & return 409 SOLD_OUT.
    
    -- Step 4: Insert 15-minute hold, bump pool version, and enqueue cache invalidation in outbox:
    INSERT INTO reservations (..., status, hold_expires_at, occupied_until)
    VALUES (..., 'HELD', clock_timestamp() + interval '15 minutes', :return_at + :turnaround);
    
    UPDATE fleet_pools SET version = version + 1
     WHERE branch_id = :branch AND vehicle_type_id = :type;
    
    INSERT INTO outbox (topic, aggregate_id, payload) VALUES ('pool_changed', :pool_key, ...);
    COMMIT;
    

    Watch out for the now() vs clock_timestamp() confirmation trap! In PostgreSQL, now() returns the timestamp when the transaction started, whereas clock_timestamp() returns actual wall-clock time right now. If Customer A's confirm request starts at 18:14:59 (1 second before 18:15:00 expiry) and blocks for 3 seconds behind Customer B who grabs the last car at 18:15:01, checking hold_expires_at > now() would still see 18:15:00 > 18:14:59 and double-book the car! Using clock_timestamp() under the same fleet_pools lock ensures Customer A detects that the hold expired while waiting, re-runs peak_usage, and cleanly refunds if sold out:

      Prepaid Confirm Flow (NEVER call Stripe inside BEGIN...COMMIT!):
      [1. DB Txn: Hold row] ---> [2. Stripe CHARGE (outside DB lock!)] ---> [3. DB Txn: Lock pool & Confirm]
                                        (idempotency_key = payment_id)            |
                                                                                  +-- If hold expired & sold out:
                                                                                      enqueue automatic REFUND in outbox!
    

    When modifying a reservation across two vehicle types (PATCH), always lock both fleet_pools rows sorted by (branch_id, vehicle_type_id) so two opposite swaps can never deadlock.

  7. Deep dive 2: Pick-up, upgrades, return, and late-car reality

    Counter pick-up workflow:

    1. Pre-authorize card outside the DB transaction: Insert a payments row (status = 'PENDING', purpose = 'pickup_auth', amount = $305.28 quote + $200.00 deposit = $505.28), then call the payment gateway using payment_id as the idempotency key. UNIQUE (reservation_id, purpose) prevents double holds if the counter tablet retries.
    2. Assign a physical car atomically: If the agent scans key tag veh_8410, run UPDATE vehicles SET status = 'RENTED' WHERE vehicle_id = :id AND status = 'AVAILABLE' ... RETURNING vehicle_id. If auto-assigning, use SELECT vehicle_id FROM vehicles WHERE ... AND status = 'AVAILABLE' ORDER BY odometer_miles LIMIT 1 FOR UPDATE SKIP LOCKED so parallel agents at a busy airport counter never block each other.
    3. Free upgrade when the booked pool is temporarily short: If a late return left 0 MIDSIZE cars washed and ready, lock (branch, MIDSIZE) and (branch, FULLSIZE) in sorted order, verify FULLSIZE has both a ready AVAILABLE car and peak_usage + 1 <= units for this rental's window, and update reservations.vehicle_type_id = FULLSIZE while keeping booked_vehicle_type_id = MIDSIZE so the customer keeps their original $52/day rate!
    4. Commit rental + outbound inspection: Insert rentals (status = 'ACTIVE', guarded by rentals_one_active_per_car_idx), inspections (phase = 'PICKUP'), flip reservation to CHECKED_OUT, and store the signed PDF contract hash.

    Lot return and late-return handling:

    • Idempotent return transaction (WHERE status = 'ACTIVE'): Marks rentals.status = 'RETURNED', sets vehicles.status = 'CLEANING' with updated odometer and fuel, flips reservations.status = 'COMPLETED', and inserts a 1-unit capacity_blocks (CLEANING) row from returned_at to returned_at + turnaround_min under the pool lock so cleaning time stays protected even on an early return.
    • Overdue rentals: What if a car due at 10:00 still hasn't returned by 11:00? An hourly job locks the pool, extends that active reservation's occupied_until forward by 24 hours so search stops selling the missing car, and alerts branch staff on a shortage report if tomorrow's bookings now exceed units—giving staff hours to prep an upgrade or transfer a car from a nearby branch.
  8. Deep dive 3: Deterministic pricing and fault-tolerant payments

    Pure, integer-cent pricing engine. Search, checkout quotes, and final return invoices all call the exact same pure function using basis points (1 basis point = 0.01%, so 950 bp = 9.50% tax and 1000 bp = 10.00% discount) and half-up integer rounding—eliminating floating-point drift (0.1 + 0.2 != 0.3):

    import math
    from datetime import timedelta
    
    GRACE_PERIOD = timedelta(minutes=29)
    
    
    def billable_days(pickup_at, return_at) -> int:
        """Count started 24-hour periods with a 29-minute return grace period (minimum 1 day)."""
        effective_duration = return_at - pickup_at - GRACE_PERIOD
        days = math.ceil(effective_duration / timedelta(hours=24))
        return max(1, days)
    
    
    def percent_half_up(amount_cents: int, basis_points: int) -> int:
        """Compute amount_cents * (basis_points / 10,000) using integer half-up rounding."""
        return (amount_cents * basis_points + 5000) // 10000
    
    
    def compute_invoice_lines(days: int, daily_cents: int, addons: list, usage_lines: list,
                              promo_bp: int, tax_bp: int, untaxed_daily_fees: list) -> tuple:
        """Pure pricing function used by Search, Hold Quotes, and Final Return Invoices."""
        base_cents = days * daily_cents
        lines = [("BASE", days, daily_cents, base_cents)]
        if promo_bp > 0:
            lines.append(("PROMO", 1, 0, -percent_half_up(base_cents, promo_bp)))
        for code, rate_cents in addons:
            lines.append((code, days, rate_cents, days * rate_cents))
        lines.extend(usage_lines)                       # Extra miles & refuel charges added at return
        taxable_subtotal = sum(item[3] for item in lines)
        lines.append(("TAX", 1, 0, percent_half_up(taxable_subtotal, tax_bp)))
        for code, fee_cents in untaxed_daily_fees:
            lines.append((code, days, fee_cents, days * fee_cents))
        total_cents = sum(item[3] for item in lines)
        return lines, total_cents
    

    Let us trace our concrete reservation from Search -> Quote -> Return using compute_invoice_lines ($52/day base, 10% promo, 9.5% tax, $10/day untaxed airport facility fee):

    Stage 1 — Search (3 days, no add-ons):
      BASE $156.00 - PROMO $15.60 = $140.40 taxable -> TAX $13.34 + FEE $30.00 = $183.74 (18,374 cents)
    
    Stage 2 — Checkout Hold Quote (+ CDW $25/day, + CHILD_SEAT $12/day for 3 days):
      Taxable $251.40 -> TAX $23.88 + FEE $30.00 = $305.28 (+ $200 deposit = $505.28 authorized at pick-up)
    
    Stage 3 — Return 3h 10m late (past 29m grace -> 4 billable days; 950 mi vs 800 incl = 150 extra mi @ $0.25;
              6/8 fuel on 16-gal tank = 4 gal @ $6.50):
      BASE $208.00 - PROMO $20.80 + CDW $100.00 + SEAT $48.00 + MILES $37.50 + FUEL $26.00 = $398.70 taxable
      + TAX $37.88 + FEE $40.00 = $476.58 captured from $505.28 auth ($28.70 released back to customer!)
    

    Safe payment state machine: Every gateway call records a PENDING row in payments first, sends payment_id as the provider's idempotency key, and marks HTTP timeouts as UNKNOWN (never FAILED!). A background reconciler queries/retries UNKNOWN rows using the same payment_id, and nightly settlement reconciliation diffs provider payout files against payments.

  9. Scaling plan, failure handling, and trade-offs

    How we scale reads, writes, and regions

    1. Cache pool timelines, not search query URLs: Caching raw (branch, pickup_at, return_at) queries gets a terrible hit rate because timestamps vary by minute. Instead, cache pool:{branch_id}:{vehicle_type_id} containing that pool's live (pickup_at, occupied_until, hold_expires_at) intervals (~17 MB for all 100,000 cars!). Any search window is answered in memory in < 2 ms. Outbox events invalidate changed pools within ~1 second (backed by a 60-second safety TTL), and bookings never trust the cache—they always re-verify on the primary under FOR UPDATE.
    2. Read replicas + read-your-writes: Staff dashboards, customer trip history, and Redis cache misses hit read replicas; after a customer mutates a reservation, route their reads for that reservation to the primary for 5 seconds so replication lag never hides their edit.
    3. Cell-based regional partitioning (and branch_id sharding if ever needed): Deploy independent database cells per region (North America, Europe) for low latency and GDPR data residency. Because every pool lock and counter workflow is scoped to one branch, branch_id is also a zero-cross-shard partition key if volume ever grows 100x.
    4. Monthly table partitioning for history: reservations_live_idx indexes only active statuses (~425k rows), while completed/cancelled rows partition by month and roll off to cold storage.

    Key failure modes at a glance

    Failure Scenario Risk Mitigation
    Client/tablet retries after network timeout Duplicate hold, return, or charge idempotency_keys (principal, key) replays original response; payments.payment_id dedupes at Stripe
    Two users race for last car Double-booking (write skew) SELECT ... FOR UPDATE on fleet_pools + READ COMMITTED fresh snapshot + peak_usage check
    Hold expires while user completes prepay Charged with no car Confirm re-checks under pool lock with clock_timestamp(); triggers outbox refund on 409
    Payment gateway slow / timeout Locked DB rows or double charge Gateway called outside DB transactions; timeouts marked UNKNOWN and reconciled with same key
    Primary DB crash Lost confirmed reservations Synchronous standby in a second AZ promoted automatically (RPO = 0)

    Summary of trade-offs: Booking by vehicle type (fleet_pool) maximizes fleet utilization and simplifies counter operations in exchange for handling late-return shortages via upgrades; exact interval sweep-line under a per-pool lock avoids the wasted turnover days of daily-bucket counters while requiring a lightweight 17 MB timeline cache for high-QPS search; and keeping payment calls outside ACID locks adds PENDING/UNKNOWN reconciliation states in exchange for keeping database locks under 5 ms even during payment-provider slowdowns.

Intuition & how it works

Think of a car rental branch like a restaurant that takes reservations by table size ("party of 4") rather than promising Booth #7 months in advance. Because any clean 4-top table can seat any party of 4 when they walk through the door, the restaurant never has to reshuffle guests if Table #7 lingers over dessert—as long as the number of overlapping reservations at any moment stays at or below the total number of 4-top tables. Car rentals work the exact same way: customers book a vehicle type at a branch (fleet_pool, such as 20 MIDSIZE cars at SEA01), and a specific license plate (vehicle_id) is only bound when signing the rental contract at the counter.

Why do naive database designs fail here? First, putting a UNIQUE (vehicle_type_id, date) constraint cannot express "allow up to 20 overlapping intervals, then reject the 21st," and checking SELECT COUNT(*) without a lock suffers from write skew—a concurrency bug where two customers simultaneously see "19 of 20 booked" and both insert a booking, creating 21 bookings for 20 cars! Second, counting total overlapping rows instead of peak simultaneous overlap rejects valid bookings (three sequential 1-day rentals Mon–Tue, Tue–Wed, and Wed–Thu all overlap Mon–Fri, yet they only use 1 physical car!). Third, calling an external payment API like Stripe inside the database transaction holds row locks across 500 ms network calls, freezing bookings for everyone else whenever the payment gateway slows down.

Let us walk through a concrete 4-step trace on a small branch pool with units = 2 MIDSIZE cars, where Booking 1 (Fri 10:00–Sat 10:00) and Booking 2 (Sat 11:00–Sun 10:00) already exist, and Maya books Fri 09:00–Sun 12:00:

  1. Fast cached search (POST /v1/search): Search reads the branch's cached pool timeline from Redis (~17 MB covers a 100,000-car fleet), adds 60 minutes of cleaning turnaround (occupied_until), and runs a sweep-line overlap check: Booking 1 occupies [Fri 10:00, Sat 11:00) and Booking 2 occupies [Sat 11:00, Sun 11:00). Because Booking 1 frees its car at Sat 11:00 right as Booking 2 starts, peak simultaneous usage is 1, leaving 2 - 1 = 1 car free! Search freezes unit rates into an immutable price_quotes snapshot ($183.74).
  2. Locked 15-minute hold (POST /v1/reservations): Under READ COMMITTED, the database locks the (SEA01, MIDSIZE) row in fleet_pools (SELECT ... FOR UPDATE), re-reads live rows via a partial index (an index storing only active rows where status IN ('HELD', 'CONFIRMED', 'CHECKED_OUT')), verifies peak_usage + 1 <= 2 (ignoring any HELD rows whose hold_expires_at <= clock_timestamp()), inserts Maya's row as HELD for 15 minutes, and writes a cache-invalidation event to a transactional outbox (a table written in the same transaction so background events are never lost on crash).
  3. Confirm & counter pick-up: Maya confirms (status = 'CONFIRMED'). On Friday at the counter, staff pre-authorize $505.28 (quote + $200 deposit) at the payment provider outside any DB transaction using payment_id as an idempotency key (a unique token ensuring retries never double-charge), then atomically claim ready car veh_8410 (status = 'RENTED') and create the rental contract (status = 'ACTIVE', protected by a partial unique index allowing at most 1 active rental per car).
  4. Return & capture: When Maya returns the car on Sunday (recording odometer, fuel, and photos), one transaction marks the rental RETURNED, puts veh_8410 into CLEANING with a 60-minute capacity block, computes exact integer-cent invoice lines from her frozen quote rates, and triggers async payment capture (claiming the final $476.58 from the $505.28 authorization and releasing the remaining $28.70).

Key trade-offs

  • Reserve a vehicle type (fleet_pool) vs. assign a specific vehicle_id at booking. Booking by category maximizes fleet utilization and absorbs minor maintenance swaps without touching customer reservations; the trade-off is that if several drivers return cars hours late, the counter must resolve physical shortages using free upgrades (upgrade_rank). Assigning specific cars at booking (using a PostgreSQL GiST exclusion constraint—a database rule forbidding overlapping (vehicle_id, time_range) pairs) fits peer-to-peer marketplaces like Turo where every car is unique, but fragments calendars for interchangeable fleets.
  • Exact interval sweep-line under a per-pool lock vs. daily inventory counters. Daily bucket tables ((pool, date, booked_count)) make reads trivial, but a 4-day rental from Friday 10:00 to Tuesday 10:00 touches 5 calendar dates—blocking Tuesday afternoon even though the car is washed and ready by Tuesday 11:00! Hourly buckets fix turnover waste but require ~88M rows/year and ~100 row updates per booking. Checking exact intervals under SELECT ... FOR UPDATE on fleet_pools (~3 ms lock on one row) wastes zero turnover hours and lets holds expire passively by timestamp, at the small cost of maintaining a 17 MB Redis timeline cache for high-QPS search.
  • Pessimistic row locking (FOR UPDATE) for capacity vs. optimistic concurrency (If-Match: version) for human edits. Capacity holds take ~3 ms on the server, so queueing concurrent writers on one fleet_pools row avoids retry storms cleanly. Conversely, you can never hold a database lock for 2 minutes while a user edits dates on screen—so PATCH /v1/reservations/{id} checks version optimistically and returns 412 Precondition Failed on conflicting edits.
  • Immutable price_quotes snapshot vs. recalculating from live rates at return. Copying daily, mileage, add-on, promo, and tax rates into price_quotes at search/booking guarantees customers pay the exact rates they agreed to even if headquarters raises summer prices tomorrow, trading modest JSON storage (~75 GB/year across all tables) for complete financial auditability.
  • Calling payment providers outside DB transactions vs. inside BEGIN ... COMMIT. External HTTP calls take 200–2,000 ms; keeping them outside transactions keeps fleet_pools lock hold times under 5 ms, at the cost of explicit PENDING / UNKNOWN payment states, compensating outbox refunds (if a hold expires during payment), and orphan-authorization sweepers.
  • Single regional primary + read replicas vs. early sharding. At ~2 writes/s average (~20/s peak), one PostgreSQL primary + synchronous standby per region (US, EU) preserves full ACID constraints and zero distributed transactions, while branch_id remains a clean future shard key because all pool and counter operations happen within one branch.

Common mistakes

  • Check-then-insert without locking the pool row. Running SELECT to check capacity and then INSERT without FOR UPDATE (or SERIALIZABLE retries) allows concurrent requests to pass the check simultaneously and double-book the last car.
  • Counting total overlapping bookings instead of peak simultaneous overlap. Using COUNT(*) over [pickup_at, return_at) treats sequential non-overlapping rentals inside a longer window as concurrent, falsely rejecting valid reservations.
  • Using PostgreSQL now() instead of clock_timestamp() after waiting on a lock. Because now() freezes at BEGIN, a confirm transaction that waited behind another writer can misjudge an expired hold as still valid unless it checks clock_timestamp().
  • Relying on a cron job to free expired holds. If the cleanup worker crashes or lags by 10 minutes, abandoned checkouts lock up fleet inventory unless queries filter hold_expires_at > clock_timestamp() directly on read.
  • Forgetting cleaning/turnaround buffer (occupied_until = return_at + turnaround_min). Allowing Car A's 10:00 return to immediately satisfy Car B's 10:00 pick-up fails at the counter because washing, vacuuming, and refueling take 30–60 minutes.
  • Holding database locks across Stripe/Adyen network calls, or retrying payment timeouts with a new idempotency key. Calling the payment gateway inside BEGIN ... COMMIT stalls the whole branch pool during gateway hiccups, and treating an HTTP timeout as FAILED with a brand-new key risks charging or holding the customer's card twice.
  • Using float for money or OFFSET for live reservation feeds. Floating-point math accumulates cent rounding bugs (always use integer cents and basis points), and OFFSET pagination skips or duplicates rows when new bookings arrive.

Follow-up questions

  • How would you adapt the schema and locking model to support one-way trips where a customer picks up at one branch and drops off at another? A one-way trip permanently removes 1 unit from the pick-up branch starting at pickup_at and adds 1 unit to the drop-off branch starting at return_at + turnaround_min! Model the pick-up side as an open-ended deduction (until a scheduled fleet-rebalancing transfer brings a vehicle back) and record the incoming car at return_branch_id in a capacity_additions table (which peak_usage subtracts from usage after return_at + turnaround_min). During the hold transaction, lock both (pickup_branch_id, type) and (return_branch_id, type) in fleet_pools in deterministic sorted order to prevent deadlocks, and add a dynamic one-way drop fee in the pricing engine based on the destination branch's surplus or deficit.
  • Because roughly 20% of pay-later reservations cancel or fail to show up, how would you add controlled overbooking without stranding arriving drivers? Add an overbook_bps column per (branch_id, vehicle_type_id) calibrated from historical no-show rates by day-of-week and booking lead time, and apply it only to PAY_LATER reservations (since prepaid no-shows already collect revenue). The hold check becomes peak_usage + 1 <= floor(units * (1 + overbook_bps / 10000)) bounded by a strict safety cap tied to spare capacity in higher upgrade_rank tiers at that same branch. Track the "walked customer" rate (arrivals where both upgrades and nearby-branch transfers ran out) and automatically dial overbook_bps down whenever predicted shortages approach that ceiling.
  • What happens in both the database and branch operations if a renter keeps a car two days past its due time when tomorrow's pool is fully booked? One hour past rentals.due_at, an overdue-monitor job locks the fleet_pool, extends that active reservation's occupied_until forward in rolling 24-hour increments so search stops selling the unreturned unit, and evaluates peak_usage across the next 48 hours. Any upcoming reservation pushed above units immediately appears on the branch manager's shortage worklist the day before the next driver arrives—giving staff lead time to pre-assign a free upgrade (upgrade_rank + 1), transfer an idle car from a nearby city branch, or contact the overdue renter while billing extra days at the contracted daily rate.

Follow-up questions

Similar questions

More Retool interview questions

All 2 Retool questions →