Vehicle Rental Search and Reservation Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a nationwide online vehicle rental platform where travelers browse open cars, lock in an itemized fare quote, complete a reservation, and later amend or cancel their trip.

Support four core user journeys end to end:

  1. Availability search: Find open vehicles for a chosen pickup branch, a half-open rental window [pickup, return), a vehicle category (compact, midsize, SUV, minivan, etc.), and optional filters such as maximum budget, seating count, and gearbox type.
  2. Itemized quoting: Calculate and temporarily lock a full fare breakdown covering daily base rates, branch/airport surcharges, optional equipment add-ons, and local taxes.
  3. Reservation checkout: Secure a vehicle for the requested interval and coordinate external payment authorization.
  4. Amendments & cancellations: Shorten or lengthen trip dates, switch vehicle category or branch, or cancel an active booking under defined refund rules.

The central engineering tension is strict concurrency safety vs. extreme read skew: a single physical vehicle can never be committed to two overlapping bookings even when hundreds of shoppers click checkout simultaneously during a flash sale, while browse traffic runs orders of magnitude higher and must stay fast.

Use concrete, realistic operating assumptions such as the following (or state and justify your own):

  • Fleet footprint: ~2,400 branches averaging ~150 vehicles each (~360,000 physical vehicles total), with each vehicle assigned to a single home branch in the baseline design.
  • Workload skew: ~32 million reservations per year (~1 booking/sec average, spiking into the low hundreds of checkout attempts/sec during major sales) vs. ~1,000:1 browse-to-book skew producing tens of thousands of search queries/sec at peak.
  • Latency goals: Search p95 within ~200 ms; checkout can span a few seconds because card authorization crosses external banking networks.
  • Time & consistency model: Model every rental as a half-open UTC interval [pickup, return) paired with each branch's IANA time zone for local display and billing-day calculations (including Daylight Saving Time shifts). Reservation writes require strict transactional non-overlap guarantees; search results may lag by a second or two as long as checkout re-verifies availability atomically (a rare conflict notice on checkout is fine; a double-booking is never acceptable).

Scope & Expectations

  • Domain framing & sizing: Clarify key product rules—category-level vs. VIN-level assignment, quote lock TTLs, turnaround cleaning buffers, cancellation policies, and DST billing math—and use back-of-the-envelope numbers to separate real bottlenecks from non-issues.
  • Decoupled APIs & schemas: Present clean REST contracts (including idempotency and optimistic concurrency) and a relational data model that decouples bursty search traffic from strongly consistent reservation writes.
  • Concurrency & multi-day search: Show how the database prevents overlapping bookings on any physical car without holding locks across slow payment calls, and design an availability index that accurately answers contiguous multi-day searches rather than per-day approximations.
  • Lifecycle edge cases & resilience: Cover reservation date extensions, promotional spike protection, payment timeouts, and component failovers.

Step-by-step walkthrough

  1. Clarify requirements and scope

    An online vehicle rental platform has to satisfy two very different demands side by side:

    • Reservations demand strict correctness: one physical vehicle can never be committed to two renters over colliding intervals, even when hundreds of shoppers tap "Reserve" simultaneously during a holiday promo.
    • Browsing demands high throughput: roughly 1,000 shoppers filter and compare fares for every completed checkout. Browse endpoints must serve tens of thousands of requests per second with low latency, and returning inventory snapshots that trail live writes by 1–2 seconds is fine provided checkout re-verifies truth transactionally.

    Routing browse queries and reservation writes through one unified SQL query path creates an ugly trade-off: heavy range scans stall checkout locks, or relaxed locking invites double-bookings. Instead, we split checkout mutations and inventory search onto dedicated paths.

    Functional requirements

    • Search open vehicles by pickup branch, a [pickup, return) rental window, vehicle category (compact, midsize, SUV, minivan, etc.), and optional filters (budget cap, seat count, gearbox). A half-open interval [pickup, return) contains pickup and excludes return, so back-to-back windows such as [Tue 09:00, Fri 09:00) and [Fri 09:00, Sun 09:00) never collide.
    • Quote an itemized fare breakdown (daily base rates + airport/branch surcharges + equipment add-ons + local taxes) and hold that quoted price briefly during checkout.
    • Reserve a vehicle in the requested category across the chosen interval, coordinating card authorization safely.
    • Cancel or amend an active booking (shorten or lengthen dates, or switch category / branch).
    • Let fleet staff block specific vehicles for shop maintenance and enforce a turnaround buffer (cleaning and safety check) after every return.

    Non-functional requirements

    • Zero overlapping bookings — strict transactional guarantees across customer trips, short checkout holds, cleaning turnarounds, and maintenance windows.
    • Low-latency browse at scale — p95 <= 200 ms at ~40,000 search queries/second during flash promos; 1–2 seconds of projection lag is acceptable.
    • Bounded checkout latency — 2–5 seconds end-to-end is expected due to external card-network calls, without ever holding database row locks open across the network call.
    • Graceful contention behavior — if two shoppers race for the final vehicle, returning an honest conflict response with nearby alternatives is fine; double-booking is never acceptable.

    Clarifying assumptions

    • Category booking backed by physical vehicle assignment: Shoppers select a category at a branch (for example, "Minivan at DEN") rather than a specific VIN. When a shopper places a checkout hold, the backend immediately pins one concrete physical vehicle (car_id) from that category. Enforcing "zero colliding intervals per car_id" guarantees category capacity is never oversold, while fleet operations can atomically swap ("re-pin") a future trip onto another vehicle in the same category if a car enters the repair shop.
    • System of record: PostgreSQL using native range exclusion constraints (with MySQL row-locking equivalents covered in the follow-ups).
    • Rate management & quote locks: Pricing teams refresh daily rates per (location, class, date) a few times a day; generating a quote locks the fare for 30 minutes.
    • Time zones & billing days: Every timestamp is persisted in UTC alongside each branch's IANA time zone (standard region identifiers such as America/Denver that carry local daylight-saving rules). Rental days bill in 24-hour blocks on the pickup branch's local wall clock with a 29-minute grace window, plus a 60-minute cleaning turnaround appended to every return.
    • Cancellation rules: Full refund up to 48 hours prior to pickup; a one-day charge inside 48 hours.
  2. Back-of-the-envelope numbers

    Estimating scale up front tells us where bottlenecks actually live—and stops us from over-engineering parts that easily fit on one machine.

    Fleet inventory
      2,400 branches x ~150 cars/branch       = 360,000 physical cars total
      ~10 car classes per branch              = ~15 cars per (branch, class)
    
    Booking writes (the correctness path)
      32M bookings/year / 31.5M sec/year      = ~1 booking/s average
      Promotional peak (~100x average)        = ~100 holds/s (design with 3x headroom -> 300 holds/s)
      DB row writes per booking lifecycle     = ~5 rows (hold, confirm, idempotency_key, outbox, payment)
      Peak DB write rate                      = 300 x 5 = ~1,500 row writes/s -> fits easily on 1 PostgreSQL primary
    
    Why DB transactions cannot wrap payment calls (Little's Law: concurrency = arrival_rate x duration)
      Short DB hold transaction (~5 ms)       = 300/s x 0.005 s = 1.5 active DB transactions on average
      If DB tx waited for card auth (~5 s)    = 300/s x 5.0 s   = 1,500 open transactions holding locks & connections!
    
    Search reads (the scale path)
      Normal search QPS (1,000:1 read:write)  = ~1,000 searches/s
      Promotional spike (40x normal)          = ~40,000 searches/s
      Work per search (up to 5 nearby branches x 10 classes x 15 cars)
                                              = ~750 car checks per query, each a binary search over ~16 intervals
    
    In-memory availability projection size
      Future intervals per car (~70% utilized, ~4-day average rental, 3-month booking horizon)
                                              = (90 days x 0.70) / 4 ≈ 16 active future intervals per car
      Raw interval data                       = 360,000 cars x 16 intervals x 16 B (two 64-bit timestamps) ≈ 92 MB
      With reservation_id (16 B) + version (4 B) + map overhead
                                              = ~210 MB raw (~400 MB with in-memory index structures)
                                              -> the ENTIRE global fleet's availability fits in RAM on every search server!
    
    Persistent storage growth
      Reservations: 32M/year x ~1 KB/row      = ~32 GB/year
      Daily rate table: 2,400 x 10 x 365      = 8.76M rows/year x ~50 B ≈ 440 MB/year
    

    Three design conclusions from the math:

    1. Do not shard the booking database. 1,500 row writes/second is modest for a single modern PostgreSQL primary. The real write problem is lock contention when 300 users/second chase the same 15 minivans at DEN.
    2. Hold every car's busy schedule in RAM on each search server. At ~400 MB total, 12 stateless search servers (~5,000 QPS capacity each across 3 availability zones) can answer 40,000 searches/second purely from memory without ever querying PostgreSQL.
    3. Split "reserve the car" from "charge the card." Keeping a transaction open during a 5-second payment call multiplies active transactions 1,000-fold (1.5 -> 1,500), starving connection pools and row locks.
  3. API design

    To keep database transactions at a few milliseconds while locking prices and handling slow payments cleanly, we model checkout as three explicit steps: Quote -> Hold -> Confirm.

    Every state-changing endpoint requires an Idempotency-Key header — a unique client-generated UUID per user action so that if a mobile app times out and retries the exact same request, the server returns the original outcome instead of creating a second booking or charging twice. Modify and cancel endpoints also use If-Match: <version> (optimistic concurrency, where the update succeeds only if the reservation's version number has not been changed by another device since it was read).

    1. Search available classes
    GET /v1/search?pickup_location=DEN&return_location=DEN
                  &pickup_at=2026-11-10T09:00&return_at=2026-11-13T09:00
                  &class=MINIVAN&min_seats=7&transmission=automatic&max_total_cents=55000
      - Timestamps are local wall-clock times at each location; money is always integer cents ($550.00 = 55000).
    200 OK {
      "as_of": "2026-10-25T16:15:00Z",
      "results": [
        {
          "location": "DEN",
          "class": "MINIVAN",
          "availability": "few",                      // "available" (3+), "few" (1-2 left), or "sold_out"
          "price": {"total_cents": 37500, "per_day_cents": 12500, "currency": "USD"},
          "models": ["Honda Odyssey or similar"]
        }
      ],
      "nearby_alternatives": [...]                    // populated within 15 km when requested class is low/sold out
    }
    
    2. Lock a price quote (valid for 30 minutes)
    POST /v1/quotes
      {"pickup_location": "DEN", "return_location": "DEN",
       "pickup_at": "2026-11-10T09:00", "return_at": "2026-11-13T09:00",
       "class": "MINIVAN", "add_ons": ["child_seat"], "promo_code": "AUTUMN26"}
    201 Created {"quote_id": "q_52c...", "line_items": [...], "total_cents": 40500,
                 "currency": "USD", "expires_at": "2026-10-25T16:45:00Z"}
    
    3. Place a 10-minute inventory hold on a physical car (no payment yet; ~5 ms DB transaction)
    POST /v1/holds                                    Headers: Idempotency-Key: <uuid>
      {"quote_id": "q_52c...", "driver": {"name": "...", "license_number": "..."}}
    201 Created {"reservation_id": "res_78b...", "status": "HELD",
                 "hold_expires_at": "2026-10-25T16:25:00Z", "version": 1}
    409 Conflict CLASS_SOLD_OUT {"alternatives": [...]}
    410 Gone     QUOTE_EXPIRED
    
    4. Authorize payment and confirm the held reservation
    POST /v1/reservations/{id}/confirm                Headers: Idempotency-Key: <uuid>
      {"payment_method_token": "pm_tok_..."}
    200 OK       {"status": "CONFIRMED", "confirmation_code": "VR-61M8", "version": 2}
    202 Accepted {"status": "PAYMENT_PENDING"}        // card network slow; client polls GET /v1/reservations/{id}
    402 Payment  PAYMENT_DECLINED                     // hold stays alive until TTL so user can try another card
    409 Conflict HOLD_LOST {"alternatives": [...]}    // hold expired before payment & last car was taken
    
    5. Read, modify, or cancel
    GET   /v1/reservations/{id}
    PATCH /v1/reservations/{id}                       Headers: Idempotency-Key: <uuid>, If-Match: 2
      {"return_at": "2026-11-14T09:00"}               // optional: pickup_at, return_at, class, locations
    200 OK {"status": "CONFIRMED", "price_delta_cents": 13500, "version": 3}  |  409 NOT_AVAILABLE
    POST  /v1/reservations/{id}/cancel                Headers: Idempotency-Key: <uuid>, If-Match: 3
    200 OK {"status": "CANCELLED", "refund_cents": 40500}
    

    Why these API choices matter:

    • Coarse availability badges (available / few / sold_out) instead of exact counts: Because search reads a projection that lags by ~1 second, promising "exactly 1 car left" looks broken when a concurrent buyer takes it, and exact counts leak fleet sizes to competitors.
    • Server-stored quote_id: POST /v1/holds reads the dates, car class, and locked price from the stored quote_id row on the server—never trusting price numbers sent by the browser.
    • Integer minor units (cents): Storing $375.00 as 37500 eliminates binary floating-point rounding bugs (0.1 + 0.2 != 0.3).
  4. Data model

    We want the database engine itself—not just our Python or Go application code—to make double-booking physically impossible. PostgreSQL gives us an exclusion constraint: a table-level rule (generalizing UNIQUE) that rejects any INSERT or UPDATE if two rows match on car_id (=) and overlap on their blocked time range (&&) at the same time. PostgreSQL enforces this using a GiST index (Generalized Search Tree, an index structure designed for intervals and geometric ranges), combined with btree_gist so plain scalar columns like car_id can live in the same index.

    CREATE EXTENSION IF NOT EXISTS btree_gist;
    
    CREATE TABLE locations (
      location_id  text PRIMARY KEY,                       -- e.g. 'DEN'
      tz           text NOT NULL,                          -- IANA zone, e.g. 'America/Denver'
      turnaround   interval NOT NULL DEFAULT '60 minutes'  -- cleaning buffer after each return
    );
    
    CREATE TABLE cars (
      car_id       bigint PRIMARY KEY,
      vin          text UNIQUE NOT NULL,
      location_id  text NOT NULL REFERENCES locations,
      class_code   text NOT NULL,                          -- 'ECONOMY' | 'SUV' | 'LUXURY' ...
      seats        int NOT NULL,
      transmission text NOT NULL,
      model        text NOT NULL,
      status       text NOT NULL                           -- 'ACTIVE' | 'RETIRED'
    );
    
    CREATE TABLE reservations (
      reservation_id   uuid PRIMARY KEY,
      car_id           bigint NOT NULL REFERENCES cars,
      kind             text NOT NULL,                      -- 'RENTAL' | 'MAINTENANCE'
      customer_id      uuid,
      pickup_location  text NOT NULL REFERENCES locations,
      return_location  text NOT NULL REFERENCES locations,
      period           tstzrange NOT NULL,                 -- [pickup, return): customer-facing rental window
      blocked          tstzrange NOT NULL,                 -- [pickup, return + turnaround): full unavailable window
      status           text NOT NULL,                      -- 'HELD' | 'CONFIRMED' | 'PICKED_UP' | 'COMPLETED'
                                                           -- | 'CANCELLED' | 'EXPIRED' | 'RELEASED' | 'MODIFIED'
      hold_expires_at  timestamptz,
      payment_state    text NOT NULL DEFAULT 'NONE',       -- 'NONE' | 'PENDING' | 'UNKNOWN' | 'AUTHORIZED' | 'VOIDED'
      payment_attempt  int NOT NULL DEFAULT 0,
      payment_ref      text,
      quote_id         uuid,
      total_cents      bigint,
      currency         char(3),
      version          int NOT NULL DEFAULT 1,
      created_at       timestamptz NOT NULL DEFAULT now(),
    
      -- Guard against zero-length ('empty') ranges, because 'empty' && anything evaluates to FALSE in Postgres!
      CHECK (not isempty(period) AND lower(period) < upper(period)),
      CHECK (not isempty(blocked) AND lower(blocked) < upper(blocked)),
    
      -- Core invariant: no two active rows for the same physical car may ever overlap in `blocked` time.
      EXCLUDE USING gist (car_id WITH =, blocked WITH &&)
        WHERE (status IN ('HELD', 'CONFIRMED', 'PICKED_UP', 'COMPLETED'))
    );
    
    CREATE INDEX idx_res_sweeper  ON reservations (status, hold_expires_at) WHERE status = 'HELD';
    CREATE INDEX idx_res_customer ON reservations (customer_id);
    
    CREATE TABLE quotes (
      quote_id     uuid PRIMARY KEY,
      params       jsonb NOT NULL,
      line_items   jsonb NOT NULL,
      total_cents  bigint NOT NULL,
      currency     char(3) NOT NULL,
      expires_at   timestamptz NOT NULL
    );
    
    CREATE TABLE idempotency_keys (
      customer_id  uuid NOT NULL,
      idem_key     text NOT NULL,
      request_hash bytea NOT NULL,
      response     jsonb NOT NULL,
      created_at   timestamptz NOT NULL DEFAULT now(),
      PRIMARY KEY (customer_id, idem_key)
    );
    
    CREATE TABLE outbox (
      id           bigserial PRIMARY KEY,
      car_id       bigint NOT NULL,
      event_type   text NOT NULL,
      payload      jsonb NOT NULL,
      created_at   timestamptz NOT NULL DEFAULT now()
    );
    

    Why each schema detail is shaped this way:

    • Half-open tstzrange(a, b) defaults to [a, b): If Rental 1 has blocked = [Mon 10:00, Wed 11:00) (return at 10:00 + 60 min cleaning) and Rental 2 starts at Wed 11:00, && returns false—back-to-back bookings after cleaning fit seamlessly.
    • Explicit not isempty(...) check: In PostgreSQL, tstzrange(t, t) creates a special 'empty' range that never overlaps anything ('empty' && x is always false). The CHECK constraint guarantees every stored interval has strictly positive length.
    • MAINTENANCE shares the reservations table: Blocking a car for brake service inserts a row with kind = 'MAINTENANCE', status = 'CONFIRMED', so the exact same GiST constraint stops rentals from overlapping shop time.
    • Why COMPLETED stays inside the constraint's WHERE clause: When a customer returns a car at 10:15, we update status = 'COMPLETED' and set blocked = [pickup, 11:15) (actual return + 60 min cleaning). Keeping COMPLETED in the constraint prevents someone from booking that car at 10:30 while it is still being vacuumed! Once 11:15 passes, that historical range lies entirely in the past and never blocks future bookings.
    • Transactional outbox table: Writing an event row into outbox inside the same database transaction as the reservations change guarantees we never commit a booking without also queuing the update for our search servers (avoiding dual-write bugs if a server crashes mid-request).
  5. High-level architecture: two separate paths

    We separate the system into a strongly consistent write path (every write immediately sees the latest committed truth on one PostgreSQL primary) and an eventually consistent read path (stateless search servers read from an in-memory copy updated asynchronously within ~1 second).

                                  Web / Mobile Clients
                                           |
                            [ CDN ]  static assets & promo pages
                                           |
                            [ API Gateway ]  auth, per-user/IP rate limits,
                                             virtual waiting room during big promos
                             /             |                       \
                 GET /search/   POST /quotes                POST /holds, /confirm,
                           /               |                PATCH / cancel
                          v                v                         v
          [ Search Service x12 ]   [ Pricing Service ]      [ Booking Service ] ------> [ Payment Provider ]
            in-memory busy-interval   cached daily rates        |         ^              authorize / void / refund
            projection (< 500 MB)     & tax/fee rules           |         |
                     ^                                          |   [ Saga & Sweeper ]
                     |                                          v   [ Workers        ]
                     |                                [ PostgreSQL Primary ] --sync--> [ Standby (AZ-2) ]
                     |                                  reservations, cars, quotes,     + async read replica
                     |                                  idempotency_keys, outbox        ("My Trips" & admin)
                     |                                          |
                     |                                   [ Outbox Relay ]
                     |                                          v
                     +------------------------------- [ Kafka: reservation-events ]
                         consume in order (key = car_id)        |
                                                                +--> Email/Push Notifications, Analytics
    
    • Why search never touches PostgreSQL: During a promotion, 40,000 searches/second stay completely inside the 12 Search Service nodes' RAM. Even if search traffic spikes 10x, the PostgreSQL primary handling bookings and payments feels zero extra read load.
    • Why stale search cannot cause a double-booking: Even if search had zero lag, a car shown on screen while a user spends 20 seconds typing their driver's license could still be taken by someone else before they click "Hold." Therefore, POST /v1/holds must re-validate atomically in PostgreSQL regardless—which frees search to optimize purely for speed.
  6. Deep dive 1: the double-booking race and atomic car pinning

    Why naive "check then insert" fails. Suppose Car 42 is free on Nov 10–13, and Request A (Nov 10–13) and Request B (Nov 11–12) arrive at the same millisecond:

    Time   Request A (Car 42, Nov 10-13)                 Request B (Car 42, Nov 11-12)
    ----   -------------------------------------------   -------------------------------------------
    t1     BEGIN;
           SELECT count(*) FROM reservations
            WHERE car_id = 42 AND blocked && '[Nov10,13)'
           -> returns 0!
    t2                                                   BEGIN;
                                                         SELECT count(*) FROM reservations
                                                          WHERE car_id = 42 AND blocked && '[Nov11,12)'
                                                         -> ALSO returns 0 (A has not committed yet)!
    t3     INSERT INTO reservations ... (Car 42)
    t4                                                   INSERT INTO reservations ... (Car 42)
    t5     COMMIT;                                       COMMIT;  --> BUG: Car 42 is double-booked!
    

    Even raising PostgreSQL's transaction level from READ COMMITTED to REPEATABLE READ does not prevent this! PostgreSQL implements REPEATABLE READ using snapshot isolation: each transaction reads a frozen snapshot of the database as of t1/t2, and because A and B insert two different rows with no shared primary key conflict, neither blocks the other. This classic anomaly is called write skew (two transactions each read overlapping data, verify an invariant holds, and make disjoint writes that together break the invariant).

    To eliminate the race, the overlap guard and the insert must happen inside a single database-enforced step:

    Option How it makes check + write atomic Trade-off
    A. GiST exclusion constraint (chosen) INSERT checks the GiST range index directly; Request B blocks on Request A's uncommitted overlapping entry and fails with SQLSTATE 23P01 once A commits Impossible for any code path or admin script to bypass; PostgreSQL-specific
    B. Pessimistic lock on cars row SELECT 1 FROM cars WHERE car_id = :car_id FOR UPDATE serializes all bookings for Car 42 before running the overlap SELECT + INSERT Works on MySQL/Postgres/Oracle, but every writer must remember to lock cars first (at READ COMMITTED; see follow-up)
    C. Optimistic version on cars row Read cars.version = v, run overlap SELECT + INSERT, then UPDATE cars SET version = v + 1 WHERE car_id = :car_id AND version = v (0 rows -> rollback & retry) Works on any SQL DB without lock waits, but high contention causes retry churn
    D. SERIALIZABLE isolation Database tracks read predicates (SSI) and aborts one transaction on write skew Easy to forget on a new endpoint; higher false-positive abort rate on hot pages

    Pinning a physical car for a class booking. Because the customer booked "any Minivan at DEN," place_hold picks a specific free car_id and inserts the HELD row. Two subtle forces compete when ranking candidate cars:

    • Best-fit packing (avoid calendar fragmentation): Prefer a car whose idle gap around [pickup, blocked_end) is tightest, preserving wide 7-day open stretches on other cars for week-long renters.
    • Contention spreading during promotions: If 300 concurrent requests all compute the exact same #1 best-fit car, 299 of them queue behind one row lock and fail! Ranking by gap tightness and randomly shuffling the top K (e.g., top 5) near-ties spreads concurrent holds across different cars while still packing calendars cleanly.
    import random
    
    
    MAX_ATTEMPTS = 5
    
    
    def place_hold(db, quote, customer_id, idem_key, request_hash):
        # 1. Fast path: if this exact Idempotency-Key already finished, replay its saved response.
        saved = db.get_idempotent_response(customer_id, idem_key, request_hash)
        if saved is not None:
            return saved
    
        # 2. Lazily expire any stale holds in this (location, class) whose TTL has already passed.
        db.expire_stale_holds(quote.pickup_location, quote.class_code)
    
        # 3. Query candidate cars that appear free right now (a fast hint; the GiST constraint is the real guard).
        candidates = db.find_free_cars(
            quote.pickup_location,
            quote.class_code,
            quote.pickup_utc,
            quote.blocked_end_utc,
        )
        # Sort by tightest idle gap (best fit), then shuffle the top slice so concurrent callers spread out.
        candidates.sort(key=lambda car: car.idle_gap_seconds)
        top_slice = candidates[:MAX_ATTEMPTS]
        random.shuffle(top_slice)
    
        # Deterministic UUIDv5 ensures concurrent retries of the same idem_key target the exact same row ID.
        reservation_id = db.uuid_v5(customer_id, idem_key)
    
        for car in top_slice:
            try:
                # Single ~5 ms transaction: INSERT reservation (checked by GiST) + idempotency_keys + outbox.
                response = db.insert_hold_tx(
                    reservation_id=reservation_id,
                    car_id=car.car_id,
                    quote=quote,
                    customer_id=customer_id,
                    idem_key=idem_key,
                    request_hash=request_hash,
                )
                return response
            except db.ExclusionViolationError:
                # Another buyer grabbed `car.car_id` milliseconds ago; move on to the next candidate car.
                continue
            except db.IdempotencyKeyConflictError:
                # A duplicate mobile retry of OUR OWN request won the race; return its committed response.
                return db.get_idempotent_response(customer_id, idem_key, request_hash)
    
        # All candidates were just taken (or none existed): return 409 with nearby alternatives (not cached in idem table
        # if transient, or cached briefly so double-taps behave consistently).
        return {"status": "CLASS_SOLD_OUT", "alternatives": db.suggest_alternatives(quote)}
    

    Each candidate attempt runs in its own tiny transaction because in PostgreSQL, any constraint error (ExclusionViolationError) aborts the current transaction block.

  7. Deep dive 2: short holds, payment saga, and idempotency

    Why payment uses a saga instead of a database transaction. Authorizing a credit card takes 1–5 seconds over the internet—and up to several minutes if the bank triggers a 3-D Secure app challenge. Instead of holding database locks across that call, we use a saga: a sequence of short, local database transactions separated by external network steps, with an explicit compensating action (voiding the card authorization) if the final confirmation step cannot complete.

                  POST /holds (~5 ms)                   POST /confirm (card authorized)
       (none) --------------------------> HELD -----------------------------------------> CONFIRMED
                                         /  |  \                                              |
                    user leaves /       /   |   \ 10-min TTL elapsed (sweeper)                | pickup / cancel
                    cancels hold       v    |    v                                            v
                                 RELEASED   |   EXPIRED --- in-flight auth succeeds ---> CONFIRMED
                                            |               (if GiST check still passes;      or
                                            v                otherwise VOID card auth!)  PICKED_UP -> COMPLETED
                                    (card declined: stays
                                     HELD until TTL so user
                                     can try another card)
    

    How hold expiration works. PostgreSQL requires EXCLUDE ... WHERE (...) predicates to be immutable functions of the row's columns, so we cannot write WHERE hold_expires_at > now() inside the index definition. Instead, an expired HELD row stops blocking only when its status column changes to 'EXPIRED'. Two mechanisms flip stale rows promptly:

    1. Background sweeper running every 30 seconds in small batches: UPDATE reservations SET status = 'EXPIRED', version = version + 1 WHERE status = 'HELD' AND hold_expires_at < now() AND payment_state = 'NONE'.
    2. Inline sweep on contention: expire_stale_holds inside place_hold immediately expires overdue idle holds in the (location, class) a new buyer wants, so an abandoned hold never causes a false "sold out" even for 30 seconds.

    Notice AND payment_state = 'NONE' in the sweeper: if a payment call is currently in flight (PENDING or UNKNOWN), we give the saga worker a bounded window to learn whether the customer's card was charged before releasing their car. Even if an extreme network delay causes a row to be marked EXPIRED while a payment was in flight, our confirmation transaction handles it safely:

    def confirm_reservation(db, payments, reservation_id, payment_token, now_utc):
        res = db.get_reservation(reservation_id)
        if res.status == "CONFIRMED":
            # Safe idempotent replay after an earlier confirmation already succeeded.
            return {"status": "CONFIRMED", "confirmation_code": res.code}
    
        # Never start a brand-new card authorization unless the hold is actively HELD and unexpired!
        if res.status != "HELD" or now_utc >= res.hold_expires_at:
            return {"status": "HOLD_LOST"}
    
        # Atomic compare-and-set (CAS): transitions payment_state NONE -> PENDING and increments payment_attempt.
        # Returns None if another confirm click is already in flight on this hold.
        attempt = db.try_begin_payment(reservation_id)
        if attempt is None:
            return {"status": "PAYMENT_PENDING"}
    
        # Include `attempt` in the provider key: network retries of attempt #1 share a key (no double charge),
        # while trying a different card after a decline gets attempt #2 (so the provider won't replay decline #1!).
        provider_key = f"auth-{reservation_id}-{attempt}"
        auth = payments.authorize(
            amount_cents=res.total_cents,
            currency=res.currency,
            token=payment_token,
            idempotency_key=provider_key,
        )
    
        if auth.outcome == "DECLINED":
            # Reset payment_state back to NONE; the HELD row stays alive until hold_expires_at for a second card.
            db.set_payment_state(reservation_id, "NONE")
            return {"status": "PAYMENT_DECLINED"}
    
        if auth.outcome == "TIMEOUT_UNKNOWN":
            # Card may or may not have been charged; background saga worker will poll provider by `provider_key`.
            db.set_payment_state(reservation_id, "UNKNOWN")
            return {"status": "PAYMENT_PENDING"}
    
        # Payment succeeded! Flip HELD (or EXPIRED if swept during a long delay) -> CONFIRMED.
        # If status was EXPIRED, PostgreSQL re-checks the GiST exclusion constraint automatically!
        try:
            confirmed = db.mark_confirmed_tx(reservation_id, auth.auth_id)
        except db.ExclusionViolationError:
            confirmed = False
    
        if not confirmed:
            # Compensating saga step: someone else got the car after expiry, so void the card hold immediately.
            payments.void(auth.auth_id, idempotency_key=f"void-{auth.auth_id}")
            return {"status": "HOLD_LOST"}
    
        return {"status": "CONFIRMED", "confirmation_code": res.code}
    

    Resolving crashed or timed-out payments. Background saga workers poll rows stuck in payment_state = 'UNKNOWN' (or 'PENDING' for > 60 seconds because a server crashed mid-call) using SELECT ... FOR UPDATE SKIP LOCKED—a SQL clause that lets multiple workers grab different stuck rows in parallel without waiting on one another. Each worker queries the payment provider using auth-<reservation_id>-<attempt>, running mark_confirmed_tx if authorized or resetting/expiring the hold if the charge never went through.

  8. Deep dive 3: multi-day search with an in-memory busy-interval projection

    The classic trap: why daily counters break on multi-day trips. Storing an integer like open_cars[(DEN, MINIVAN, date)] and checking count >= 1 across every date looks appealing at first glance, yet fails with just 2 minivans at DEN:

    Fleet: 2 Minivans at DEN       Nov 10   Nov 11   Nov 12   Nov 13
    ----------------------------   ------   ------   ------   ------
    Car A                          BUSY     BUSY     free     free
    Car B                          free     free     BUSY     BUSY
    Per-day "free vans" counter:     1        1        1        1    --> Counter says "AVAILABLE"!
    
    Customer searches for ONE van from Nov 10 to Nov 14:
      - Car A is busy Nov 10-11.
      - Car B is busy Nov 12-13.
      -> ZERO physical vans are free for the unbroken 4-day trip! (Counter gave a 100% false positive.)
    

    Unless a customer wants to return Car B halfway through their vacation and swap into Car A, a multi-day search must check whether at least one individual car has a single uninterrupted free gap covering [pickup, return + turnaround).

    How the in-memory availability projection works. Each search node holds all active cars grouped by (location_id, class_code). Because PostgreSQL's exclusion constraint guarantees a single car's blocking intervals never overlap, sorting a car's busy intervals by start automatically sorts them by end as well! That lets us check whether a car is free for [pickup, blocked_end) in O(log B) time with a single binary search:

    Car 42 busy intervals:    [Nov 01, Nov 03)       [Nov 05, Nov 08)       [Nov 13, Nov 16)
    ends array:                    Nov 03                 Nov 08                 Nov 16
    
    Query: pickup = Nov 10, blocked_end = Nov 13
      1. Binary search `ends` for the FIRST interval ending strictly after Nov 10 (`bisect_right`):
         -> lands on index i = 2 ([Nov 13, Nov 16)), because Nov 03 <= Nov 10 and Nov 08 <= Nov 10.
      2. Every interval before index 2 ended at or before Nov 10, so none of them can overlap!
      3. Check whether interval 2 starts at or after `blocked_end` (Nov 13 >= Nov 13):
         -> True! Car 42 is completely free for [Nov 10, Nov 13).
    
    from bisect import bisect_right
    
    
    def is_car_free(starts, ends, pickup_ts, blocked_end_ts):
        """Return True if [pickup_ts, blocked_end_ts) overlaps none of the sorted non-overlapping [start, end) ranges."""
        # Find index `i` of the first busy interval with end > pickup_ts.
        i = bisect_right(ends, pickup_ts)
        if i == len(ends):
            # All existing busy intervals ended at or before `pickup_ts`.
            return True
        # Since intervals before `i` end <= pickup_ts, only interval `i` can possibly overlap;
        # the car is free iff interval `i` starts at or after `blocked_end_ts`.
        return starts[i] >= blocked_end_ts
    
    
    def count_free_cars_in_class(cars_in_class, pickup_ts, blocked_end_ts, filters):
        """Count physical cars matching user filters that are continuously free across [pickup_ts, blocked_end_ts)."""
        free_count = 0
        for car in cars_in_class:
            if car["seats"] < filters.min_seats:
                continue
            if filters.transmission and car["transmission"] != filters.transmission:
                continue
            if is_car_free(car["starts"], car["ends"], pickup_ts, blocked_end_ts):
                free_count += 1
        return free_count
    

    Keeping all 12 search nodes synchronized:

    • Every write to reservations appends an event (reservation_id, car_id, blocked, status, version) to outbox, which the relay publishes to Kafka topic reservation-events partitioned by car_id (preserving strict per-car ordering).
    • Each search node consumes all partitions, inserts/updates the interval when status is blocking (HELD, CONFIRMED, PICKED_UP, COMPLETED), removes it when CANCELLED/EXPIRED/RELEASED, and ignores any event with version <= last_applied_version[reservation_id].
    • Every few minutes, one node writes a compressed memory snapshot + Kafka partition offsets to S3/GCS so newly launched search servers boot in seconds and replay only the last few minutes of Kafka events.
  9. Pricing across time zones, cancellations, and modifications

    Billing across Daylight Saving Time (DST). Suppose a customer in Denver (America/Denver) rents a car from Saturday Oct 31, 2026 at 09:00 to Sunday Nov 1, 2026 at 09:00—the weekend clocks "fall back" 1 hour:

    Elapsed physical UTC time:   25 hours -> (25 h - 29 min grace) / 24 h = ceil(24 h 31 m / 24 h) = 2 days (OVERBILLED!)
    Local wall-clock difference: 24 hours -> (24 h - 29 min grace) / 24 h = ceil(23 h 31 m / 24 h) = 1 day  (EXPECTED!)
    

    Rule: store and compare intervals in UTC (timestamptz) so physical overlap checks are unambiguous, compute billing days using local wall-clock difference (LocalDateTime at return minus LocalDateTime at pickup in the pickup branch's IANA zone). On spring-forward day, nonexistent local times like 02:30 return 400 Bad Request asking for a valid time; on fall-back day, ambiguous 01:30 defaults to the first occurrence and echoes the exact UTC offset in the quote.

    Cancellations. POST /cancel runs an atomic compare-and-set (UPDATE reservations SET status = 'CANCELLED', version = version + 1 WHERE reservation_id = :id AND version = :v AND status = 'CONFIRMED'), writes an outbox event that frees the car in search ~1 second later, and voids or partially refunds the payment via an idempotent saga step (refund-<reservation_id>).

    Modifications (PATCH /reservations/{id}) have three distinct cases:

    1. Shortening dates on the same car: Shrink period and blocked in place (UPDATE). Shrinking a sub-interval can never create a new overlap, so it always succeeds; refund any price difference.
    2. Extending dates on the same car (the self-overlap trap!): Suppose Maya has [Nov 10, Nov 13) on Car 42 and wants [Nov 10, Nov 15).
      • Naive mistake 1 ("insert new row, then cancel old row"): Fails every time! PostgreSQL sees the new [Nov 10, Nov 15) row overlapping Maya's own active [Nov 10, Nov 13) row and rejects it.
      • Naive mistake 2 ("cancel old row in tx 1, then insert new row in tx 2"): Dangerous! If Nov 13–15 is already booked by Noah, tx 2 fails—and someone else may snatch Nov 10–13 in the gap, leaving Maya with no car at all!
      • Correct approach A (in-place UPDATE): Update period and blocked on Maya's existing row in one statement. PostgreSQL's exclusion constraint checks the updated row against all other active rows (never against its own prior state), succeeding atomically if [Nov 13, Nov 15 + turnaround) is free on Car 42 (and if Car 42 is busy Nov 13–15, we can try pinning another free minivan for the full [Nov 10, Nov 15) window before giving up!).
      • Correct approach B (replace inside one transaction): In a single BEGIN ... COMMIT block, set the old row's status = 'MODIFIED' (which drops it out of the GiST WHERE clause) and INSERT the new row. If the new row collides with another booking, the entire transaction rolls back and Maya's original reservation stays untouched.
    3. Changing car class or pickup location: Place a HELD row on the new class/location first, authorize any extra payment delta, then in a single database transaction mark the new row CONFIRMED and the old row MODIFIED. Never release the original car until the replacement is secured.
  10. Scaling promotions, failure modes, and key trade-offs

    Surviving promotional traffic spikes:

    • Gateway virtual waiting room & anti-hoarding limits: During mega-sales, the API gateway caps active hold rate and enforces at most 2 active HELD reservations per user (plus IP and card-fingerprint rate limits) so scraper bots cannot lock out the entire fleet in 10-minute holds without paying.
    • Short-lived identical-query cache: Search servers cache identical (location, pickup, return, filters) responses in memory for 5 seconds, absorbing bursts when thousands of users click the same promotional banner link.
    • Future sharding path: If fleet size ever grew 50x beyond one PostgreSQL primary, shard cars and reservations by geographic region (region_id)—every local rental stays a single-shard transaction, and only rare cross-region one-way rentals require a two-shard transfer workflow.

    Failure handling and operational safety net:

    Failure mode Impact How the system handles it
    PostgreSQL primary crash Writes pause ~15–30 s Promote synchronous standby in another AZ (zero committed bookings lost); clients retry safely with Idempotency-Key; search keeps serving from RAM
    Outbox relay or Kafka lag Search projection grows stale Booking correctness is unaffected; alert fires if lag > 30 s; slightly more holds return 409 CLASS_SOLD_OUT with live alternatives
    Payment provider outage authorize() times out Circuit breaker returns 202 PAYMENT_PENDING; UNKNOWN holds are protected from premature sweeping until saga workers reconcile them
    Previous renter returns late / car breaks down Next customer's pinned car_id is unavailable at pickup Operations runs atomic re-pin (UPDATE reservations SET car_id = :other_car_id) onto a free car of the same class—or upgrades to the next class up at no extra charge

    Finally, even though the GiST constraint prevents overlaps on every write, defense-in-depth runs a nightly verification query on the read replica that must always return zero rows:

    SELECT a.reservation_id, b.reservation_id
      FROM reservations a
      JOIN reservations b
        ON a.car_id = b.car_id
       AND a.reservation_id < b.reservation_id
       AND a.blocked && b.blocked
     WHERE a.status IN ('HELD', 'CONFIRMED', 'PICKED_UP', 'COMPLETED')
       AND b.status IN ('HELD', 'CONFIRMED', 'PICKED_UP', 'COMPLETED');
    

Intuition & how it works

Think of a vehicle rental platform like running both the big departures board in a train station lobby and the ticket counter that assigns physical seats. Thousands of travelers glance at the lobby board every second to compare options; nobody minds if that board lags behind reality by one second, as long as it loads instantly. By contrast, when a traveler steps up to reserve a trip, the counter must put an immediate, exclusive lock on one specific vehicle before waiting several seconds for the bank to approve their credit card—so two travelers can never walk away with overlapping bookings for the exact same car.

A naive design uses a single database path for everything: every search runs a range query over the live reservations table, and every checkout runs SELECT to check for overlaps, calls the payment gateway to charge the card, and INSERTs the reservation inside one transaction. That approach breaks down in three ways under promotion traffic: 40,000 range-scanning searches per second overwhelm the primary database, two concurrent buyers both read "0 overlapping rows" at the exact same millisecond and double-book the same car, and holding database transactions open across 5-second external payment calls exhausts locks and connections within seconds.

Here is how our split-path design handles a concrete race on 2 Minivans at DEN (Car 1 already booked Nov 9–11; Car 2 completely free) when Maya and Noah both try to book a Minivan for Nov 10–12:

  1. In-memory search (~1 ms): Maya and Noah both search DEN, MINIVAN, [Nov 10 09:00, Nov 12 09:00). A stateless search node checks Car 1 and Car 2 in RAM using binary search over each car's sorted busy intervals (including the 60-minute cleaning turnaround), sees Car 1 busy and Car 2 free, and returns availability: "few" without touching PostgreSQL.
  2. Atomic hold (~5 ms): Both click "Reserve" and call POST /v1/holds with locked quote_ids. PostgreSQL runs INSERT INTO reservations ... status = 'HELD' on Car 2, guarded by a GiST exclusion constraint (a database index rule that forbids any two active rows for the same car_id from having overlapping blocked time ranges). Maya's insert commits in 5 ms; Noah's concurrent insert immediately hits an exclusion conflict, sees no other free Minivans at DEN, and cleanly returns 409 CLASS_SOLD_OUT with nearby branch and upgrade options.
  3. Lock-free payment saga (~2–5 s): With Car 2 safely held for 10 minutes by a committed row, the booking service authorizes Maya's card outside any database transaction, then runs a second ~5 ms transaction flipping HELD -> CONFIRMED and writing an outbox event (a row committed alongside the booking so a background relay can publish the update to Kafka) that marks Car 2 busy on all search servers ~1 second later.

Key trade-offs

  • Separate write and read paths vs. querying PostgreSQL directly for search. Serving search from an in-memory availability projection (a derived, read-optimized copy of every car's busy intervals kept updated via Kafka events) lets 12 small servers handle 40,000 searches/second while keeping the PostgreSQL primary quiet for bookings. The trade-off is ~1–2 seconds of staleness, meaning a buyer occasionally clicks on a class whose last car just sold out milliseconds earlier and is offered alternatives at hold time.
  • Database exclusion constraint (EXCLUDE USING gist) vs. application-level locking. Enforcing non-overlapping [pickup, return + turnaround) intervals inside PostgreSQL guarantees that no future endpoint, fleet-maintenance tool, or application bug can ever create a double-booking. The cost is coupling the schema to PostgreSQL's btree_gist extension; on engines like MySQL, every writer must explicitly serialize per car_id via row locks or version numbers.
  • Pinning a physical car at hold time vs. class-level quota pools. Assigning a concrete car_id during POST /v1/holds reduces a complex multi-day capacity problem to a simple per-car interval check. The downside is calendar fragmentation (Car A free Mon–Tue and Car B free Wed–Thu cannot serve one Mon–Thu trip without moving an existing booking), which we mitigate with best-fit gap selection and background re-pinning of future reservations.
  • HELD state + TTL + saga vs. wrapping payment inside one DB transaction. Committing a 10-minute HELD row before calling the payment provider keeps database lock hold times around ~5 ms instead of ~5 seconds. In exchange, we must run a periodic hold sweeper, a background saga reconciliation worker for timed-out payment calls, and compensating void calls if an expired hold's car is taken before a delayed authorization returns.
  • Per-car busy intervals vs. per-day available counters in search. Storing sorted [start, end) intervals per car uses ~210–400 MB of RAM across 360,000 cars—more than simple daily integer counts—but answers contiguous multi-day queries accurately instead of claiming a class is free when different cars cover different days.
  • Local wall-clock days for billing vs. pure UTC math. Storing timestamptz in UTC keeps physical overlap checks immune to daylight-saving jumps, while computing 24-hour rental days on the pickup location's local wall clock prevents overcharging customers on the 25-hour autumn DST fallback weekend.

Common mistakes

  • Two-step check-then-insert (SELECT overlaps, then INSERT). Under concurrent requests, both transactions see zero overlapping rows and both insert—even under PostgreSQL's REPEATABLE READ (snapshot isolation), which does not block write skew between two newly inserted rows.
  • Keeping a database transaction open while calling the payment gateway. External card networks take seconds and occasionally hang; 300 holds/second × 5 seconds ties up 1,500 concurrent connections and row locks, collapsing the database during promotions.
  • Modeling search availability with per-day free counts. If Car A is free Monday and Car B is free Tuesday, daily counts say >= 1 free on both days even though zero single cars can fulfill a Monday–Wednesday rental.
  • Using closed intervals [pickup, return] or forgetting turnaround cleaning time. Closed bounds falsely block a 09:00 pickup after a 09:00 return, while omitting the 60-minute turnaround (or dropping COMPLETED rentals from the constraint immediately at return) lets a new renter book a dirty car before cleaning finishes.
  • Reusing a single static payment idempotency key across declined cards. Keying card authorization purely by reservation_id instead of (reservation_id, payment_attempt) causes the payment provider to replay the first card's decline when the user enters a valid second card, whereas starting a brand-new payment on an already-EXPIRED hold needlessly authorizes cards for lost cars.
  • Modifying a rental extension by inserting the new row before cancelling the old one. Extending [Nov 10, Nov 13) to [Nov 10, Nov 15) overlaps the customer's own active reservation, so a naive insert-first fails on self-conflict, while cancelling first in a separate transaction risks losing the original booking to another buyer.

Follow-up questions

  • When a customer lengthens an active trip on the same vehicle, the extended interval collides with their existing booking—why does inserting the new row first fail, and what are two safe ways to execute the change? Inserting the lengthened row first fails because PostgreSQL's exclusion constraint checks the candidate row against every active row on that vehicle—including the renter's own [Nov 10, Nov 13) booking—and rejects the self-overlap, whereas cancelling first in a separate transaction risks losing the car if another shopper grabs those dates in between. The cleanest solution is an in-place UPDATE of period and blocked (WHERE reservation_id = :id AND version = :v): PostgreSQL evaluates the updated row against all other active rows on car_id, never against itself, so it commits atomically whenever the added days are open. A second safe pattern runs two statements inside one BEGIN ... COMMIT block: flip the existing row to status = 'MODIFIED' (excluding it from the GiST WHERE predicate) and INSERT the replacement row, rolling back both statements cleanly if another renter holds the extension dates.

sql UPDATE reservations SET period = tstzrange(lower(period), :new_return), blocked = tstzrange(lower(blocked), :new_return + :turnaround), version = version + 1 WHERE reservation_id = :id AND status IN ('CONFIRMED', 'PICKED_UP') AND version = :expected_version;

  • How would you guarantee race-free overlap checks and inserts if the primary datastore were MySQL, which lacks PostgreSQL's GiST range exclusion constraints? Serialize all mutations for a physical vehicle through its parent row in cars inside one transaction at READ COMMITTED isolation: acquire SELECT car_id FROM cars WHERE car_id = ? FOR UPDATE, run the half-open overlap check (SELECT 1 FROM reservations WHERE car_id = ? AND status IN (...) AND blocked_start < ? AND blocked_end > ? LIMIT 1 backed by a (car_id, blocked_start, blocked_end) B-tree index), and INSERT when zero rows match. Running at READ COMMITTED matters because under InnoDB's default REPEATABLE READ, a plain SELECT reads a pre-lock snapshot if the transaction already issued an earlier query, missing the row a competing transaction just committed (unless you attach FOR SHARE to the overlap query). An optimistic lock-free alternative reads cars.version = v, inserts the booking, and runs UPDATE cars SET version = v + 1 WHERE car_id = ? AND version = v, rolling back to try the next vehicle if zero rows updated.
  • Where does a Redis distributed lock help in this architecture, and why is it unsafe as the sole guard against double-booking? Redis works well as a throughput shield or contention hint—powering virtual waiting rooms during flash sales, enforcing per-account hold caps, or steering concurrent workers toward distinct candidate car_ids—never as the authoritative correctness lock. Redis leases expire by wall-clock TTL: if an application server stalls during garbage collection or a network pause past the lease TTL, a second server can acquire the same lock and both will write overlapping rows; asynchronous Redis failover can likewise drop a freshly granted lock. Making an external lock safe requires passing a monotonic fencing token checked by the database on write, which puts the database back in charge anyway—so PostgreSQL's exclusion constraint (or MySQL's cars row lock) must remain the final enforcer.
  • What schema and search-index changes are required to support one-way rentals where a vehicle is picked up in one city and returned in another? Because a vehicle's branch now changes across trips instead of remaining static, each car's projection becomes an ordered chain of (start_time, end_time, pickup_branch, return_branch) segments. A car qualifies for a one-way trip [pickup, return) from Branch A to Branch B only when (1) [pickup, return + turnaround) has zero overlapping blocks, (2) the immediately preceding segment's return_branch (or the car's current lot if none exists) equals Branch A, and (3) either no future bookings exist after return or the very next segment starts at Branch B (unless ops inserts a scheduled TRANSFER block to relocate the vehicle). Operators pair this with dynamic directional drop fees and daily corridor caps per (A -> B) pair so high-demand destinations do not empty neighboring cities.
  • Suppose search displays a vehicle category as open, yet placing the hold fails because another renter grabbed the final car—how do you turn that conflict into a smooth checkout experience? First, make conflicts rare: place_hold tries up to 5 candidate vehicles in the requested category before giving up, and search renders "availability": "few" whenever 1–2 vehicles remain so shoppers anticipate scarcity. When the final vehicle truly disappears milliseconds before checkout, POST /v1/holds responds with a structured 409 CLASS_SOLD_OUT body carrying pre-quoted, immediately bookable alternatives fetched from the in-memory projection in the same call: the next category up at the same branch (optionally with a goodwill discount), the same category at branches within 15 km, or pickup shifted by ±1 hour. The client keeps the shopper's entered driver info intact for a one-tap switch while the outbox event flips search to "sold_out" within ~1 second.

Follow-up questions

Similar questions

More Moveworks interview questions

All 3 Moveworks questions →