Vehicle Trip Reservation API and Inventory Model

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design the REST API and relational persistence layer for a vehicle-rental or travel marketplace where guests search for available listings over a requested trip window, reserve and pay for a booking, inspect or cancel existing reservations, and later extend the return timestamp of an active trip.

Your design should explicitly evaluate two contrasting database representations for calendar availability—storing one availability record per calendar date versus storing continuous [start, end) timestamp intervals—and walk through how both the API and schema accommodate extending an already-confirmed reservation's end time.

Scope & Expectations

  • REST endpoint contracts: Define the URL routes, JSON request/response payloads, concurrency/idempotency headers, and HTTP status codes covering availability search, reservation hold and payment confirmation, trip lookup, cancellation, and trip-end extensions.
  • Relational schema & indexing: Specify the core tables, keys, constraints, and indexes that prevent double-booking and keep guest, host, and background maintenance queries fast.
  • Inventory representation trade-offs: Compare per-date calendar rows against interval/range-based rows across timestamp granularity, storage footprint, multi-unit support, pricing overrides, and concurrency guarantees.
  • Safe trip extensions: Show the API flow and schema additions needed when a guest pushes out a booking's return time, ensuring overlapping trips are rejected and failed extension payments leave the original reservation intact.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Think of a peer-to-peer vehicle-sharing marketplace: each listing represents one unique physical car owned by a host, and a guest reserves it for an exact pickup and return timestamp (a "trip"). Most of this design also applies to vacation home rentals, and we will explicitly call out where multi-unit hotel inventory (such as 20 identical Queen rooms) favors a different table layout.

    Functional requirements

    • Search availability: Find listings near a geographic location that are free across [start_at, end_at) and return a price estimate.
    • View listing calendar: Return one listing's available and unavailable windows over a date range.
    • Book a trip: Place a short temporary hold on the vehicle, quote the exact total price, process payment, and confirm the booking (instant-book flow).
    • Manage bookings: View a single booking, list a guest's upcoming/past trips, and cancel with a policy-based refund.
    • Host calendar blocks: Hosts can block windows for personal use or maintenance.
    • Trip extension: Allow a guest to push out end_at on a confirmed or in-progress reservation safely.

    Non-functional requirements

    • Zero double-booking (strict consistency on writes): Two guests must never confirm overlapping trips on the same car. On the booking write path, correctness beats availability—if we cannot prove the window is free, we reject the write.
    • Fast search with eventual consistency: Search p99 < 500 ms (meaning 99% of searches finish in under 500 ms) and may lag behind bookings by 1–3 seconds because the booking transaction performs the final authoritative check.
    • Safe retries (idempotency): Mobile apps frequently drop connections mid-checkout; retrying create, confirm, cancel, or extend must never create duplicate bookings or double-charge a card.
    • Low checkout latency: Creating a hold finishes in under 300 ms at p99 (external card-network latency happens in the separate confirm step).

    Clarifying assumptions

    • Units per listing: 1 physical car per listing.
    • Time granularity & turnaround buffer: Pickup and return times use 30-minute increments (such as Friday 10:00 to Monday 18:00) with a minimum trip length (for example 24 hours) plus a host-configured turnaround buffer (such as 2 hours for cleaning/inspection after each return).
    • Booking horizon: Up to 365 days in advance.
    • Payments: Handled via an external PCI-compliant card processor (such as Stripe); we never store raw card numbers.
  2. Back-of-the-envelope numbers

    Estimating scale up front tells us immediately whether our database bottleneck is write volume, row count, or read fan-out:

    Inventory & Horizon
      Active listings                      1,000,000 cars
      Booking horizon                      365 days ahead
    
    Traffic estimates
      Search queries                       20M / day  -> ~230 req/s avg, ~1,200 req/s at 5x peak
      Listing / calendar views             10M / day  -> ~115 req/s avg
      Confirmed bookings                   100k / day -> ~1.2/s avg, ~12/s at 10x peak
      Checkout holds (incl. abandoned)     ~3x confirmed -> ~36 writes/s at peak
      Average trip length                  4 days
    
    Inventory row counts (1M listings, 1-year horizon)
      1a) Per-date DENSE (1 row/car/day)   1M x 365 = 365M rows (~30-40 GB + PK index)
          (If split into 30-min slots:     365M x 48 = 17.52 BILLION rows -> painful!)
      1b) Per-date SPARSE (taken days)     100k bookings/day x 4 days x 365 = ~146M rows/year
      2)  Range / interval (1 row/trip)    100k bookings/day x 365 = ~36.5M rows/year (~4-6 GB)
    
    Bookings table growth
      36.5M bookings/year x ~500 B/row     ~18 GB / year
    

    What these numbers tell us:

    1. Write QPS is tiny (~36/s at peak). A single PostgreSQL primary with a synchronous standby handles booking writes with huge headroom.
    2. Search QPS (~1,200/s with geospatial radius + date filtering) is read-heavy. We should offload search to a dedicated search index (such as Elasticsearch/OpenSearch) fed asynchronously from database events.
    3. Granularity drives row count. Range rows stay compact (36.5M/year) regardless of whether trips use whole days or 30-minute timestamps, whereas dense slot rows explode to 17.5B if forced below whole-day resolution.
  3. REST API endpoints, payloads, and status codes

    Endpoint overview

    GET   /v1/listings/search                        Search free cars near lat/lng for [start_at, end_at)
    GET   /v1/listings/{id}/availability?from&to     Fetch one listing's calendar & price overrides
    POST  /v1/bookings                               Create 10-min hold & lock quote   [Idempotency-Key]
    POST  /v1/bookings/{id}/confirm                  Charge card & confirm booking     [Idempotency-Key]
    GET   /v1/bookings/{id}                          View single booking details
    GET   /v1/bookings?role=guest&status=upcoming    List guest's trips (cursor pagination)
    POST  /v1/bookings/{id}/cancel                   Cancel trip & trigger refund      [Idempotency-Key, If-Match]
    POST  /v1/bookings/{id}/extensions               Follow-up: hold trip extension    [Idempotency-Key, If-Match]
    POST  /v1/bookings/{id}/extensions/{ext_id}/confirm  Pay & confirm extension       [Idempotency-Key]
    

    Key REST design choices:

    • Why split checkout into POST /bookings (hold) + POST /confirm (pay)? Database holds take ~5 ms, whereas charging a credit card calls an external network that takes 500–2,000 ms and may trigger a browser 3D-Secure bank challenge. Splitting them avoids holding database locks during a slow external call, displays the authoritative locked-in price before charging, and auto-expires abandoned checkouts after 10 minutes.
    • Why POST /bookings/{id}/cancel instead of DELETE /bookings/{id}? Cancelling is a business transition that records a reason, computes a policy-based refund, and preserves the booking record for receipts, tax reporting, and customer support.
    • Idempotency-Key header: A client-generated UUID per button press so network retries replay the original response instead of double-booking or double-charging.
    • If-Match header: Carries the booking's current version integer (optimistic concurrency control—an update succeeds only if nobody else modified the booking since the client last read it), preventing a guest's extension and a host's cancellation from silently overwriting each other.

    Request and response shapes (money is represented in integer minor units—cents for USD—to avoid floating-point rounding bugs):

    1) Search Availability
    GET /v1/listings/search?lat=37.77&lng=-122.42&radius_km=10
        &start_at=2026-12-18T10:00:00-08:00&end_at=2026-12-21T18:00:00-08:00&limit=20
    
    200 OK
    {
      "results": [
        {
          "listing_id": "lst_123",
          "title": "2023 Sedan",
          "distance_km": 2.4,
          "daily_price": {"amount": 8900, "currency": "USD"},
          "estimated_total": {"amount": 35600, "currency": "USD"}
        }
      ],
      "next_cursor": "eyJpZCI6ImxzdF8xMjMifQ=="
    }
    
    2) Create Booking (10-Minute Hold)
    POST /v1/bookings
    Idempotency-Key: 6f1c2a9e-0d7b-4a51-9a3e-2b8f0c11d7aa
    {
      "listing_id": "lst_123",
      "start_at": "2026-12-18T10:00:00-08:00",
      "end_at": "2026-12-21T18:00:00-08:00"
    }
    
    201 Created   Location: /v1/bookings/bkg_987
    {
      "booking_id": "bkg_987",
      "status": "PENDING_PAYMENT",
      "version": 1,
      "listing_id": "lst_123",
      "start_at": "2026-12-18T18:00:00Z",
      "end_at": "2026-12-22T02:00:00Z",
      "price": {"trip": 35600, "fees": 2900, "taxes": 2400, "total": 40900, "currency": "USD"},
      "hold_expires_at": "2026-11-30T16:40:00Z"
    }
    
    3) Confirm & Pay
    POST /v1/bookings/bkg_987/confirm
    Idempotency-Key: 0b9e81c2-41aa-4d8e-8f12-91ab440192ef
    { "payment_method_id": "pm_card_visa", "expected_total": 40900 }
    
    200 OK       { "booking_id": "bkg_987", "status": "CONFIRMED", "version": 2, ... }
    202 Accepted { "booking_id": "bkg_987", "status": "PAYMENT_IN_PROGRESS" }
    
    4) Cancel Booking
    POST /v1/bookings/bkg_987/cancel
    Idempotency-Key: 4d2f99a1-77bc-41e0-b811-55ca1290ab11
    If-Match: "2"
    { "reason": "plans_changed" }
    
    200 OK { "booking_id": "bkg_987", "status": "CANCELLED", "version": 3,
             "refund": {"amount": 40900, "currency": "USD", "status": "PENDING"} }
    

    Status code contract

    200 OK                  GET, confirm, or cancel completed synchronously
    201 Created             New booking hold or extension hold created
    202 Accepted            Payment processor timed out; outcome pending (client polls GET /bookings/{id})
    400 Bad Request         Malformed JSON or unparsable timestamp
    401 Unauthorized        Missing or expired auth token
    402 Payment Required    Card declined (error.code = "CARD_DECLINED"; hold stays alive to try another card)
    404 Not Found           Unknown ID, or belongs to another user (avoids leaking existence via 403)
    409 Conflict            Dates unavailable, hold expired, illegal state transition, or expected_total mismatch
    412 Precondition Failed Stale If-Match version; client should re-fetch booking and retry
    422 Unprocessable       end_at <= start_at, shorter than min trip, in the past, or Idempotency-Key body mismatch
    429 Too Many Requests   Rate limit or max-active-holds limit exceeded (includes Retry-After)
    503 Service Unavailable Temporary DB unavailability; safe to retry with the same Idempotency-Key
    
  4. Core relational schema and indexes

    We store booking and payment records in PostgreSQL. Timestamps use timestamptz (stored internally as UTC instants), paired with each listing's IANA time zone (a region identifier like America/Los_Angeles that knows Daylight Saving Time rules) for rendering local calendars and computing local day boundaries.

    CREATE TABLE listings (
      id               bigint PRIMARY KEY,
      host_id          bigint           NOT NULL,
      status           text             NOT NULL,   -- ACTIVE | PAUSED | REMOVED
      time_zone        text             NOT NULL,   -- IANA zone, e.g. 'America/Los_Angeles'
      lat              double precision NOT NULL,
      lng              double precision NOT NULL,
      daily_price      integer          NOT NULL,   -- minor units (cents)
      currency         char(3)          NOT NULL,
      min_trip_minutes integer          NOT NULL DEFAULT 1440,
      buffer_minutes   integer          NOT NULL DEFAULT 120
    );
    CREATE INDEX listings_by_host ON listings (host_id);
    
    CREATE TABLE bookings (
      id              bigint PRIMARY KEY,
      listing_id      bigint      NOT NULL REFERENCES listings(id),
      guest_id        bigint      NOT NULL,
      start_at        timestamptz NOT NULL,
      end_at          timestamptz NOT NULL,
      status          text        NOT NULL,   -- PENDING_PAYMENT | PAYMENT_IN_PROGRESS | CONFIRMED
                                              -- | IN_PROGRESS | COMPLETED | CANCELLED | EXPIRED
      total_amount    integer     NOT NULL,
      currency        char(3)     NOT NULL,
      hold_expires_at timestamptz,
      version         integer     NOT NULL DEFAULT 1,
      created_at      timestamptz NOT NULL DEFAULT now(),
      CHECK (end_at > start_at)
    );
    -- Powers GET /v1/bookings?role=guest ("my trips" sorted newest first)
    CREATE INDEX bookings_by_guest ON bookings (guest_id, start_at DESC);
    -- Powers host dashboard calendar queries
    CREATE INDEX bookings_by_listing ON bookings (listing_id, start_at);
    -- Partial index (indexes ONLY unpaid holds) so the expiry sweeper scans tiny data
    CREATE INDEX bookings_active_holds ON bookings (hold_expires_at)
      WHERE status = 'PENDING_PAYMENT';
    
    CREATE TABLE booking_events (             -- append-only audit history
      id         bigserial   PRIMARY KEY,
      booking_id bigint      NOT NULL REFERENCES bookings(id),
      at         timestamptz NOT NULL DEFAULT now(),
      type       text        NOT NULL,        -- CREATED | CONFIRMED | CANCELLED | EXTENDED
      actor      text        NOT NULL,
      data       jsonb
    );
    CREATE INDEX booking_events_by_booking ON booking_events (booking_id, at);
    
    CREATE TABLE payments (                   -- one row per charge or refund attempt
      id              bigint PRIMARY KEY,
      booking_id      bigint      NOT NULL REFERENCES bookings(id),
      kind            text        NOT NULL,   -- CHARGE | REFUND
      amount          integer     NOT NULL,
      currency        char(3)     NOT NULL,
      status          text        NOT NULL,   -- PENDING | SUCCEEDED | FAILED
      provider_ref    text,
      -- Unique per-attempt key sent to card processor: 'booking:{booking_id}:payment:{id}'
      idempotency_key text        NOT NULL UNIQUE,
      created_at      timestamptz NOT NULL DEFAULT now()
    );
    CREATE INDEX payments_by_booking ON payments (booking_id);
    CREATE INDEX payments_stuck_pending ON payments (created_at) WHERE status = 'PENDING';
    
    CREATE TABLE idempotency_keys (
      user_id       bigint NOT NULL,
      key           text   NOT NULL,
      request_hash  text   NOT NULL,
      response_code integer,                  -- NULL while initial request is still running
      response_body jsonb,
      created_at    timestamptz NOT NULL DEFAULT now(),
      PRIMARY KEY (user_id, key)              -- purged after 24 hours
    );
    
    CREATE TABLE outbox (                     -- transactional outbox for reliable event publishing
      id         bigserial PRIMARY KEY,
      topic      text        NOT NULL,
      payload    jsonb       NOT NULL,
      created_at timestamptz NOT NULL DEFAULT now()
    );
    

    Notice that every index maps directly to an API or background access pattern, and partial indexes (WHERE status = 'PENDING_PAYMENT' and WHERE status = 'PENDING') ensure background sweepers only inspect the few hundred in-flight checkouts rather than 36 million historical rows. Next, we design the inventory table—the table that physically prevents double-bookings—in two ways and compare them.

  5. High-level architecture

                               Guest Mobile / Web App
                                         |
                                         v
                         +-------------------------------+
                         | API Gateway (TLS, Auth, Rate) |
                         +-------------------------------+
                            |                         |
             GET /search    |                         |  Bookings & Extensions
                            v                         v
                 +------------------+       +-------------------+      +-----------------+
                 | Search Service   |       | Booking Service   |----->| Payment Service |--> Card Network
                 +------------------+       +-------------------+      +-----------------+
                            |                         |
                            v                         v
                 +------------------+       +-------------------+   sync    +---------------+
                 | Search Index     |       | PostgreSQL Primary|---------->| Sync Standby  |
                 | (Geo + Busy      |       | (bookings, inv.,  |           | (Cross-AZ)    |
                 |  Date Ranges)    |       |  payments, outbox)|           +---------------+
                 +------------------+       +-------------------+
                            ^                         |
                            |                   Outbox Relay
                            |                         v
                            +--- Indexer <--- Event Bus (Kafka) ---> Emails / Push / Analytics
    
                 Background Workers: Hold-Expiry Sweeper (30s) & Stuck-Payment Reconciler
    

    Why use a transactional outbox (writing events to outbox inside the PostgreSQL transaction, then relaying them to Kafka)? If Booking Service wrote to PostgreSQL and published directly to Kafka in two separate network calls, a crash in between would leave the search index thinking a booked car is still available forever. Committing the outbox row inside the booking transaction guarantees at-least-once delivery; downstream consumers deduplicate by event id.

  6. Inventory approach 1: per-date rows (sparse and dense)

    In the per-date model, availability is broken into discrete calendar dates [start_day, end_day) in the listing's local time zone.

    Example: Nightly stay checking in Dec 18, checking out Dec 22 -> [2026-12-18, 2026-12-22)
    Covers 4 date rows: 2026-12-18, 2026-12-19, 2026-12-20, 2026-12-21
    (Dec 22 is free for the next guest checking in on Dec 22.)
    

    There are two common ways to implement per-date rows:

    Variant 1A — Sparse per-date rows (only occupied dates exist; missing row = free):

    CREATE TABLE listing_days (
      listing_id bigint NOT NULL REFERENCES listings(id),
      day        date   NOT NULL,            -- local calendar date in listing's time zone
      booking_id bigint REFERENCES bookings(id),
      kind       text   NOT NULL,            -- HELD | BOOKED | HOST_BLOCK
      PRIMARY KEY (listing_id, day)
    );
    
    -- Inside Create-Booking transaction for [start_day, end_day):
    INSERT INTO listing_days (listing_id, day, booking_id, kind)
    SELECT :listing_id, d::date, :booking_id, 'HELD'
    FROM generate_series(:start_day::date, (:end_day::date - 1), interval '1 day') AS d;
    -- Any overlapping guest hits PRIMARY KEY violation (SQLSTATE 23505) -> ROLLBACK -> 409!
    

    Variant 1B — Dense per-date rows (pre-populated row for every day in the 365-day horizon):

    CREATE TABLE listing_inventory (
      listing_id   bigint   NOT NULL REFERENCES listings(id),
      day          date     NOT NULL,
      units_total  smallint NOT NULL DEFAULT 1,
      units_booked smallint NOT NULL DEFAULT 0,
      price        integer  NOT NULL,        -- supports custom per-day host pricing
      PRIMARY KEY (listing_id, day),
      CHECK (units_booked <= units_total)
    );
    
    -- Inside Create-Booking transaction for [start_day, end_day):
    UPDATE listing_inventory
    SET units_booked = units_booked + 1
    WHERE listing_id = :listing_id
      AND day >= :start_day AND day < :end_day
      AND units_booked < units_total;
    -- Verify updated_row_count == (end_day - start_day); if fewer, ROLLBACK -> 409!
    

    Where per-date rows shine—and where they hurt for cars:

    • They work in every relational database using standard B-tree primary keys, store custom per-night prices right on the row, and naturally handle multi-unit hotel room types (units_total = 20).
    • The catch for car rentals: A car picked up Friday at 10:00 and returned Monday at 10:00 touches both Friday and Monday. If whole calendar days are locked, a second guest cannot pick up that car on Monday at 14:00—wasting a full day of revenue! Making dense rows granular to 30-minute slots multiplies 365M rows by 48 into 17.52 billion rows.
  7. Inventory approach 2: range / interval rows

    In the range (interval) model, each booking, hold, or host block is stored as one single row containing a half-open timestamp range [start_at, end_at + buffer) (includes the start instant, excludes the end instant).

    Guest A books Fri 10:00 -> Mon 18:00 (with 2h host buffer):
      Stored range:  [Fri 10:00 .......................... Mon 20:00)
    Guest B books Mon 20:00 -> Wed 12:00 (with 2h host buffer):
      Stored range:                                       [Mon 20:00 ............ Wed 14:00)
                                                           ^ Half-open '[)' touches at Mon 20:00
                                                             with ZERO overlap!
    

    In PostgreSQL, an exclusion constraint (EXCLUDE USING gist) backed by a GiST index (Generalized Search Tree, an index structure built for interval overlap queries) enforces inside the storage engine that no two active reservations for the same listing_id (=) can ever have overlapping period ranges (&&):

    CREATE EXTENSION IF NOT EXISTS btree_gist;
    
    CREATE TABLE listing_reservations (
      id         bigserial  PRIMARY KEY,
      listing_id bigint     NOT NULL REFERENCES listings(id),
      booking_id bigint     REFERENCES bookings(id),     -- NULL for host blocks
      kind       text       NOT NULL,                    -- HELD | BOOKED | HOST_BLOCK
      period     tstzrange  NOT NULL,                    -- [start_at, end_at + buffer)
      expires_at timestamptz,                            -- populated while kind = 'HELD'
      active     boolean    NOT NULL DEFAULT true,
      EXCLUDE USING gist (listing_id WITH =, period WITH &&) WHERE (active)
    );
    CREATE INDEX listing_reservations_by_booking ON listing_reservations (booking_id);
    CREATE INDEX listing_reservations_holds ON listing_reservations (expires_at)
      WHERE active AND kind = 'HELD';
    
    -- Inside Create-Booking transaction:
    INSERT INTO listing_reservations (listing_id, booking_id, kind, period, expires_at)
    VALUES (
      :listing_id,
      :booking_id,
      'HELD',
      tstzrange(:start_at, :end_at + make_interval(mins => :buffer_minutes), '[)'),
      now() + interval '10 minutes'
    );
    -- Any overlapping range triggers exclusion violation (SQLSTATE 23P01) -> ROLLBACK -> 409!
    

    What if our database does not have exclusion constraints (for example MySQL)? Lock the parent listings row first to serialize concurrent checkouts for that specific car (SELECT id FROM listings WHERE id = :listing_id FOR UPDATE), then check SELECT 1 FROM listing_reservations WHERE listing_id = :listing_id AND active = true AND start_at < :new_end_with_buffer AND end_at > :new_start LIMIT 1 using a B-tree index on (listing_id, start_at) before inserting. Skipping FOR UPDATE on the parent row would let two concurrent transactions both see zero overlaps and both insert!

  8. Head-to-head comparison: per-date vs. range inventory

    Dimension               Per-Date Inventory                  Range / Interval Inventory
    ----------------------  ----------------------------------  ----------------------------------
    Time resolution         Whole days (30-min slots = 48x      Exact timestamps (minutes/hours)
                            row explosion)                      with host turnaround buffers
    Row count (1M cars)     365M dense; ~146M/yr sparse         ~36.5M/yr (1 row per trip/block)
    Double-book protection  Standard PRIMARY KEY or guarded     PostgreSQL EXCLUDE USING gist
                            UPDATE (any SQL DB)                 (or parent-row FOR UPDATE in MySQL)
    Multi-unit inventory    Easy: units_booked < units_total    Hard: requires assigning physical
    (e.g. 20 hotel rooms)   per night                           sub-units or complex overlap counts
    Custom daily pricing    Stored directly on each day row     Separate price_overrides range table
    30-day trip write cost  Inserts/updates 30 rows             Inserts 1 row regardless of length
    Time zones & DST        Must map timestamps to local dates  Pure UTC instants; overlap math is
                            carefully                           completely immune to DST shifts
    Horizon maintenance     Dense needs daily cron to roll 365d Zero horizon-rolling jobs needed
    

    Our choice for trip booking: Use range/interval rows in PostgreSQL as the authoritative inventory source of truth, because each listing is a single car with exact pickup/return times and turnaround buffers. For search (~1,200 req/s), store each listing's active busy ranges in a date_range array field inside Elasticsearch/OpenSearch and filter with MUST_NOT intersect [requested_start, requested_end + buffer).

  9. Deep dive: hold, payment, confirm, and failure recovery

    The trickiest operational bug in booking systems is mismatch between car inventory and card charges when networks fail mid-checkout. Here is the state machine that keeps them locked in step:

                POST /bookings                     POST /confirm
      (Start) -----------------> PENDING_PAYMENT -----------------> PAYMENT_IN_PROGRESS
                                    |       |                           |          |
                      10m TTL passes|       |guest cancels    charge OK |          |card declined
                                    v       v                           v          v
                                 EXPIRED CANCELLED                  CONFIRMED   PENDING_PAYMENT
                                                                        |       (try another card)
                                                            trip starts v
                                                                   IN_PROGRESS --> COMPLETED
    
    1. Create Hold (POST /v1/bookings): One fast PostgreSQL transaction checks idempotency_keys, deactivates any already-expired hold on :listing_id (UPDATE listing_reservations SET active = false WHERE listing_id = :listing_id AND active AND kind = 'HELD' AND expires_at <= now()—so even if the background sweeper lags, expired holds never block a new guest!), inserts bookings (PENDING_PAYMENT) and listing_reservations (HELD, expires_at = now() + 10 min), writes outbox, saves the idempotent response, and commits.
    2. Start Confirm (POST /v1/bookings/{id}/confirm):
      • Phase A (short DB transaction): Atomically transition status from PENDING_PAYMENT to PAYMENT_IN_PROGRESS (checking hold_expires_at > now() and total_amount = :expected_total), push listing_reservations.expires_at out to now() + 15 minutes so the sweeper cannot release the car while the card network is thinking, and insert a PENDING row in payments with idempotency_key = 'booking:{id}:payment:{payment_id}'.
      • Phase B (external call, zero DB locks held): Call the card processor passing booking:{id}:payment:{payment_id}. Notice why the processor key is scoped per payment attempt, not per booking: if Card 1 is declined, processors cache that decline under the key (and reject reusing the key with different card details), so trying Card 2 creates a new payments row with a fresh attempt key while PAYMENT_IN_PROGRESS guarantees two attempts never run simultaneously!
      • Phase C (outcome):
        • Succeeded: One DB transaction sets bookings.status = 'CONFIRMED', version = version + 1, listing_reservations.kind = 'BOOKED', expires_at = NULL, payments.status = 'SUCCEEDED', and emits BOOKING_CONFIRMED to outbox.
        • Declined: Set payments.status = 'FAILED', revert bookings.status = 'PENDING_PAYMENT', restore expires_at = hold_expires_at, and return 402 Payment Required so the guest can try another card before the original 10-minute clock runs out.
        • Timed out / crashed: Leave PAYMENT_IN_PROGRESS and return 202 Accepted. A Payment Reconciler queries stuck PENDING payments against the card processor every minute using booking:{id}:payment:{payment_id} and either finalizes confirmation or marks failed (issuing an automatic refund in the rare race where confirmation is no longer possible).
  10. Follow-up deep dive: extending an existing trip, scaling, and trade-offs

    Suppose Guest A booked Friday 10:00 to Monday 18:00 (with a 2-hour buffer, reserving [Fri 10:00, Mon 20:00)) and wants to extend return to Wednesday 18:00. Because the extra window costs money and might collide with Guest B's upcoming trip, an extension uses the same hold → pay → confirm pattern without touching the original confirmed booking if payment fails!

    Why the extension hold range starts at old_end_at + buffer (not old_end_at):

    Original BOOKED row:   [Fri 10:00 ................. Mon 18:00 + 2h = Mon 20:00)
    Extension HELD slice:                                               [Mon 20:00 .. Wed 18:00 + 2h = Wed 20:00)
    Combined blocked span: [Fri 10:00 ............................................... Wed 20:00)
    

    Starting the second listing_reservations row at old_end_at + buffer (Mon 20:00) means it touches Guest A's existing row at Mon 20:00 with zero self-overlap, while extending the blocked window (including the shifted 2-hour turnaround buffer!) all the way to Wed 20:00. If Guest B already holds [Mon 21:00, Thu 10:00), the exclusion constraint immediately catches [Mon 20:00, Wed 20:00) && [Mon 21:00, Thu 10:00) and returns 409 Conflict with the helpful hint latest_possible_end_at = Mon 19:00 (Mon 21:00 minus the 2h buffer = 2026-12-22T15:00:00Z / 07:00-08:00 local in our earlier example)!

    API and schema additions for extensions:

    CREATE TABLE booking_changes (
      id          bigint      PRIMARY KEY,
      booking_id  bigint      NOT NULL REFERENCES bookings(id),
      kind        text        NOT NULL,   -- EXTEND (extensible to SHORTEN)
      old_end_at  timestamptz NOT NULL,
      new_end_at  timestamptz NOT NULL,
      price_delta integer     NOT NULL,   -- extra trip + fees + taxes in minor units
      status      text        NOT NULL,   -- PENDING_PAYMENT | CONFIRMED | FAILED | EXPIRED
      payment_id  bigint      REFERENCES payments(id),
      created_at  timestamptz NOT NULL DEFAULT now(),
      CHECK (new_end_at > old_end_at)
    );
    CREATE INDEX booking_changes_by_booking ON booking_changes (booking_id);
    
    • POST /v1/bookings/{id}/extensions (with Idempotency-Key and If-Match: "2") verifies the booking is CONFIRMED or IN_PROGRESS, computes price_delta (either per-added-day or recalculated full-trip total minus already-paid total so multi-day discounts apply cleanly), inserts booking_changes (PENDING_PAYMENT), and inserts the contiguous HELD slice [old_end_at + buffer, new_end_at + buffer).
    • POST /v1/bookings/{id}/extensions/{ext_id}/confirm charges price_delta via a new payments row and atomically updates bookings.end_at = new_end_at, total_amount = total_amount + price_delta, version = version + 1, flips the extension's reservation slice from HELD to BOOKED, and emits BOOKING_EXTENDED to outbox. If the card fails or the 10-minute hold expires, only the extension slice is deactivated—Guest A's original Monday 18:00 return remains completely intact!

    Scaling to 100x and key trade-offs summary:

    • Scaling writes: If bookings grew 100x (~3,600 writes/s), shard PostgreSQL horizontally by listing_id so every inventory exclusion check stays inside one shard, and maintain a read projection keyed by guest_id (populated from outbox events) to serve GET /v1/bookings?role=guest.
    • Core trade-offs: Range rows + GiST exclusion constraints give exact timestamp precision and 1-row-per-trip compactness for single-unit vehicles (vs. per-date counters for multi-unit hotels); two-step hold-then-confirm adds one API call to keep slow payments out of database transactions; and serving search from an asynchronously updated index keeps p99 search under 500 ms while relying on PostgreSQL to reject stale clicks with 409.

Intuition & how it works

Imagine managing a single neighborhood rental car on a wall timeline: you can either slap a "Booked" sticky note onto entire calendar days (the per-date model, great for hotel nights, wasteful when Driver A returns a car at 10:00 AM and Driver B wants it at 2:00 PM) or draw a continuous bar from exact pickup time to return time plus cleaning time (the range/interval model). When a guest walks up to the counter, you pencil in a 10-minute "Hold" bar first, run their credit card outside the ledger, and ink the bar to "Booked" once the bank approves—erasing the pencil mark if they walk away.

A naive booking API breaks in three predictable ways. First, running a SELECT query to check if a car is free and then running INSERT in application code lets two simultaneous checkouts both see "free" and double-book the vehicle. Second, calling an external payment processor inside the database transaction holds row locks across a 1–2 second network call, stalling database connections, while charging before reserving the car forces messy refunds whenever someone else grabs the dates first. Third, storing dense half-hour slot rows across 1 million cars for 365 days explodes the table to 1M × 365 × 48 = 17.52 billion rows.

We solve all three by storing one half-open interval [start, end) (an interval that includes start and excludes end, so 18:00–20:00 and 20:00–22:00 touch without colliding) per trip inside PostgreSQL protected by an exclusion constraint (a database rule backed by a GiST index—Generalized Search Tree—that physically rejects overlapping active time ranges for the same listing_id), paired with a two-step Hold → Confirm API. Walk through Car 12 (which has a 2-hour turnaround buffer) across four concrete events:

  1. Guest A creates a hold (POST /v1/bookings) for Fri 10:00 → Mon 18:00: One fast transaction inserts a PENDING_PAYMENT booking and a HELD reservation covering [Fri 10:00, Mon 20:00) (including the 2-hour buffer) expiring in 10 minutes; Guest A then calls POST /confirm, charges the card outside DB locks, and flips the reservation to BOOKED.
  2. Guest B tries to book Mon 19:00 → Wed 10:00: [Mon 19:00, Wed 12:00) overlaps Guest A's [Fri 10:00, Mon 20:00), so PostgreSQL immediately aborts the insert (SQLSTATE 23P01) and the API returns 409 Conflict.
  3. Guest B books Mon 21:00 → Wed 10:00 instead: [Mon 21:00, Wed 12:00) does not overlap [Fri 10:00, Mon 20:00), so Guest B succeeds cleanly.
  4. Guest A later asks to extend return (POST /v1/bookings/{id}/extensions): Extending to Mon 18:30 inserts a second contiguous slice [Mon 20:00, Mon 20:30)—which neither overlaps Guest A's own [Fri 10:00, Mon 20:00) nor Guest B's [Mon 21:00, Wed 12:00)—and succeeds! If Guest A asks for Mon 19:30 instead, [Mon 20:00, Mon 21:30) collides with Guest B's Mon 21:00 pickup, returning 409 Conflict with latest_possible_end_at = Mon 19:00 (Mon 21:00 minus the 2-hour buffer) while leaving Guest A's original Mon 18:00 trip untouched.

Key trade-offs

  • Range/interval rows vs. per-date rows. Range rows store 1 row per trip (~36.5M/year at 100k bookings/day), support exact pickup/return timestamps and turnaround buffers natively, and add extensions as one contiguous slice; the trade-off is needing PostgreSQL's EXCLUDE USING gist constraint (or locking the parent listings row with SELECT ... FOR UPDATE on databases like MySQL). Per-date rows work on any SQL database with a plain PRIMARY KEY (listing_id, day) or a units_booked < units_total counter and store per-night prices directly on each row, making them ideal for multi-room hotels—at the cost of 365M dense rows (for 1M listings) and coarse whole-day granularity that blocks same-day car turnarounds.
  • Database constraint vs. application-level overlap check. Enforcing non-overlap in the database via a primary key or GiST exclusion constraint holds under any concurrency and across any number of API servers. Checking SELECT ... WHERE overlap in application code without first locking the parent listing row creates a race condition under concurrent requests.
  • Two-step Hold (POST /bookings) + Confirm (POST /confirm) vs. single-call checkout. Splitting checkout adds one extra HTTP round trip, a 10-minute hold-expiry sweeper, and a stuck-payment reconciler, in exchange for keeping slow external card-processor calls (500–2,000 ms plus 3D-Secure prompts) completely outside database locks and showing the guest a guaranteed total before charging.
  • Asynchronous search index vs. live SQL availability search. Serving GET /v1/listings/search (~1,200 req/s with geospatial radius + ranking) from Elasticsearch/OpenSearch updated via a transactional outbox (events committed inside the DB transaction and streamed to the indexer) keeps search fast and scalable; the trade-off is 1–3 seconds of staleness, which is safely caught as a 409 Conflict when creating a hold.
  • Distinct 409 vs. 412 vs. 422 status codes. Returning 409 Conflict when world state changed (dates just booked, hold expired), 412 Precondition Failed when the client's If-Match version (an optimistic concurrency token tracking the booking's current revision) is stale, and 422 Unprocessable Content when input rules fail (end_at <= start_at) lets client apps choose the exact right recovery action automatically.
  • In-place booking update + booking_changes table vs. immutable booking row versions. Updating bookings.end_at and version on confirm while recording every attempt in booking_changes and booking_events keeps GET /bookings/{id} fast and simple while preserving a complete financial and support audit trail.

Common mistakes

  • Running "check availability, then insert" without a database constraint or parent-row lock, allowing two concurrent guests to book the exact same car.
  • Using closed intervals [start, end] instead of half-open [start, end), falsely rejecting back-to-back trips where Trip 1 finishes (including buffer) at 20:00 and Trip 2 starts at 20:00.
  • Starting an extension's reservation slice at old_end_at instead of old_end_at + buffer, which collides with the guest's own original reservation ([start_at, old_end_at + buffer)) inside the exclusion constraint!
  • Mutating bookings.end_at before the extension payment succeeds, leaving an active trip corrupted if the guest's card is declined or they abandon checkout.
  • Using one card-processor Idempotency-Key per booking instead of per payment attempt (booking:{id}:payment:{payment_id}): if a guest's first card is declined, payment processors cache that decline under the key (and reject reusing the key with a different card), blocking the guest from paying with a second card—and colliding later when charging an extension!
  • Not pushing out listing_reservations.expires_at when entering PAYMENT_IN_PROGRESS, allowing the background sweeper to expire a hold at minute 10:01 while the card processor is mid-charge at minute 09:59, letting another guest book the car too.
  • Using HTTP DELETE /bookings/{id} to cancel, destroying audit records needed for host payouts, partial refunds, and dispute resolution.
  • Storing floating-point prices (89.99) or timezone-naive timestamps, causing penny-rounding mismatches and Daylight Saving Time off-by-one-hour bugs.

Follow-up questions

  • How would you adapt the API and schema when a traveler requests an early return (shortening an active reservation) instead of an extension? Model shortening with the same booking_changes table (kind = 'SHORTEN', new_end_at < old_end_at) guarded by If-Match: because shortening requires a partial refund rather than a new charge, a single PostgreSQL transaction updates bookings.end_at = new_end_at, shrinks the active listing_reservations.period down to [start_at, new_end_at + buffer) so the freed hours become immediately bookable, computes the policy-based refund delta, inserts a PENDING REFUND row in payments, and writes a BOOKING_SHORTENED outbox event. An async worker then executes the refund idempotently against the original charge(s).
  • Which inventory representation wins—and what changes in your SQL transactions—when each listing represents a pool of 20 identical rooms rather than a single unique vehicle? Switch to the dense per-date model (listing_inventory(listing_id, day, units_total, units_booked, price)): a single UPDATE listing_inventory SET units_booked = units_booked + 1 WHERE listing_id = :id AND day >= :check_in AND day < :check_out AND units_booked < units_total atomically claims one unit on every night (verifying the updated row count equals the number of nights, rolling back otherwise). Range rows are awkward for multi-unit pools because PostgreSQL exclusion constraints forbid any overlap (max_overlap <= 1) rather than max_overlap <= 20, and pre-assigning a specific room number at booking time causes calendar fragmentation that prevents hotels from packing stays efficiently at check-in.
  • How do you keep geographic search availability reasonably fresh under load while handling listing time zones and Daylight Saving Time transitions accurately? Every booking hold, confirmation, cancellation, or expiry commits an event to outbox, which streams within ~1–2 seconds to the search indexer to update that listing's busy_ranges array; if lag spikes (monitored via outbox age and the post-search 409 rate), Search Service can re-verify the top 20 candidate IDs against a PostgreSQL read replica before returning them. For time zones, API requests accept ISO-8601 timestamps with offsets, store exact UTC instants (timestamptz), and keep each listing's IANA time zone (like America/Chicago) so range overlap math happens in pure UTC (completely immune to 23-hour or 25-hour Daylight Saving Time days) while local calendar rendering and day-based pricing convert using the listing's zone.

Follow-up questions

Similar questions

More Turo interview questions

All 6 Turo questions →