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
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_aton 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:
1physical car per listing. - Time granularity & turnaround buffer: Pickup and return times use 30-minute increments (such as Friday
10:00to Monday18:00) with a minimum trip length (for example 24 hours) plus a host-configured turnaround buffer (such as2 hoursfor 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.
- Search availability: Find listings near a geographic location that are free across
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 / yearWhat these numbers tell us:
- Write QPS is tiny (~36/s at peak). A single PostgreSQL primary with a synchronous standby handles booking writes with huge headroom.
- 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.
- 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 to17.5Bif forced below whole-day resolution.
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}/cancelinstead ofDELETE /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-Keyheader: A client-generated UUID per button press so network retries replay the original response instead of double-booking or double-charging.If-Matchheader: Carries the booking's currentversioninteger (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- Why split checkout into
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 likeAmerica/Los_Angelesthat 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'andWHERE 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.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 ReconcilerWhy use a transactional outbox (writing events to
outboxinside the PostgreSQL transaction, then relaying them to Kafka)? IfBooking Servicewrote 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 theoutboxrow inside the booking transaction guarantees at-least-once delivery; downstream consumers deduplicate by eventid.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:00and returned Monday at10:00touches both Friday and Monday. If whole calendar days are locked, a second guest cannot pick up that car on Monday at14:00—wasting a full day of revenue! Making dense rows granular to 30-minute slots multiplies365Mrows by48into 17.52 billion rows.
- 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 (
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 samelisting_id(=) can ever have overlappingperiodranges (&&):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
listingsrow first to serialize concurrent checkouts for that specific car (SELECT id FROM listings WHERE id = :listing_id FOR UPDATE), then checkSELECT 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 1using a B-tree index on(listing_id, start_at)before inserting. SkippingFOR UPDATEon the parent row would let two concurrent transactions both see zero overlaps and both insert!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 neededOur 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 adate_rangearray field inside Elasticsearch/OpenSearch and filter withMUST_NOT intersect [requested_start, requested_end + buffer).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- Create Hold (
POST /v1/bookings): One fast PostgreSQL transaction checksidempotency_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!), insertsbookings(PENDING_PAYMENT) andlisting_reservations(HELD,expires_at = now() + 10 min), writesoutbox, saves the idempotent response, and commits. - Start Confirm (
POST /v1/bookings/{id}/confirm):- Phase A (short DB transaction): Atomically transition
statusfromPENDING_PAYMENTtoPAYMENT_IN_PROGRESS(checkinghold_expires_at > now()andtotal_amount = :expected_total), pushlisting_reservations.expires_atout tonow() + 15 minutesso the sweeper cannot release the car while the card network is thinking, and insert aPENDINGrow inpaymentswithidempotency_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 newpaymentsrow with a fresh attempt key whilePAYMENT_IN_PROGRESSguarantees 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 emitsBOOKING_CONFIRMEDtooutbox. - Declined: Set
payments.status = 'FAILED', revertbookings.status = 'PENDING_PAYMENT', restoreexpires_at = hold_expires_at, and return402 Payment Requiredso the guest can try another card before the original 10-minute clock runs out. - Timed out / crashed: Leave
PAYMENT_IN_PROGRESSand return202 Accepted. A Payment Reconciler queries stuckPENDINGpayments against the card processor every minute usingbooking:{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).
- Succeeded: One DB transaction sets
- Phase A (short DB transaction): Atomically transition
- Create Hold (
Follow-up deep dive: extending an existing trip, scaling, and trade-offs
Suppose Guest A booked Friday
10:00to Monday18:00(with a2-hourbuffer, reserving[Fri 10:00, Mon 20:00)) and wants to extend return to Wednesday18: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(notold_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_reservationsrow atold_end_at + buffer(Mon 20:00) means it touches Guest A's existing row atMon 20:00with zero self-overlap, while extending the blocked window (including the shifted 2-hour turnaround buffer!) all the way toWed 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 returns409 Conflictwith the helpful hintlatest_possible_end_at = Mon 19:00(Mon 21:00minus the2hbuffer =2026-12-22T15:00:00Z/07:00-08:00local 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(withIdempotency-KeyandIf-Match: "2") verifies the booking isCONFIRMEDorIN_PROGRESS, computesprice_delta(either per-added-day or recalculated full-trip total minus already-paid total so multi-day discounts apply cleanly), insertsbooking_changes(PENDING_PAYMENT), and inserts the contiguousHELDslice[old_end_at + buffer, new_end_at + buffer).POST /v1/bookings/{id}/extensions/{ext_id}/confirmchargesprice_deltavia a newpaymentsrow and atomically updatesbookings.end_at = new_end_at,total_amount = total_amount + price_delta,version = version + 1, flips the extension's reservation slice fromHELDtoBOOKED, and emitsBOOKING_EXTENDEDtooutbox. If the card fails or the 10-minute hold expires, only the extension slice is deactivated—Guest A's original Monday18:00return remains completely intact!
Scaling to 100x and key trade-offs summary:
- Scaling writes: If bookings grew 100x (
~3,600 writes/s), shard PostgreSQL horizontally bylisting_idso every inventory exclusion check stays inside one shard, and maintain a read projection keyed byguest_id(populated fromoutboxevents) to serveGET /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 with409.
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:
- Guest A creates a hold (
POST /v1/bookings) forFri 10:00 → Mon 18:00: One fast transaction inserts aPENDING_PAYMENTbooking and aHELDreservation covering[Fri 10:00, Mon 20:00)(including the 2-hour buffer) expiring in 10 minutes; Guest A then callsPOST /confirm, charges the card outside DB locks, and flips the reservation toBOOKED. - 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 returns409 Conflict. - Guest B books
Mon 21:00 → Wed 10:00instead:[Mon 21:00, Wed 12:00)does not overlap[Fri 10:00, Mon 20:00), so Guest B succeeds cleanly. - Guest A later asks to extend return (
POST /v1/bookings/{id}/extensions): Extending toMon 18:30inserts 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 forMon 19:30instead,[Mon 20:00, Mon 21:30)collides with Guest B'sMon 21:00pickup, returning409 Conflictwithlatest_possible_end_at = Mon 19:00(Mon 21:00minus the2-hourbuffer) while leaving Guest A's originalMon 18:00trip untouched.
Key trade-offs
- Range/interval rows vs. per-date rows. Range rows store
1row per trip (~36.5M/yearat 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'sEXCLUDE USING gistconstraint (or locking the parentlistingsrow withSELECT ... FOR UPDATEon databases like MySQL). Per-date rows work on any SQL database with a plainPRIMARY KEY (listing_id, day)or aunits_booked < units_totalcounter and store per-night prices directly on each row, making them ideal for multi-room hotels—at the cost of365Mdense 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 overlapin 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 a409 Conflictwhen creating a hold. - Distinct
409vs.412vs.422status codes. Returning409 Conflictwhen world state changed (dates just booked, hold expired),412 Precondition Failedwhen the client'sIf-Matchversion (an optimistic concurrency token tracking the booking's current revision) is stale, and422 Unprocessable Contentwhen input rules fail (end_at <= start_at) lets client apps choose the exact right recovery action automatically. - In-place booking update +
booking_changestable vs. immutable booking row versions. Updatingbookings.end_atandversionon confirm while recording every attempt inbooking_changesandbooking_eventskeepsGET /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) at20:00and Trip 2 starts at20:00. - Starting an extension's reservation slice at
old_end_atinstead ofold_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_atbefore 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-Keyper 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_atwhen enteringPAYMENT_IN_PROGRESS, allowing the background sweeper to expire a hold at minute10:01while the card processor is mid-charge at minute09: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_changestable (kind = 'SHORTEN',new_end_at < old_end_at) guarded byIf-Match: because shortening requires a partial refund rather than a new charge, a single PostgreSQL transaction updatesbookings.end_at = new_end_at, shrinks the activelisting_reservations.perioddown to[start_at, new_end_at + buffer)so the freed hours become immediately bookable, computes the policy-based refund delta, inserts aPENDINGREFUNDrow inpayments, and writes aBOOKING_SHORTENEDoutbox 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 singleUPDATE listing_inventory SET units_booked = units_booked + 1 WHERE listing_id = :id AND day >= :check_in AND day < :check_out AND units_booked < units_totalatomically 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 thanmax_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'sbusy_rangesarray; if lag spikes (monitored via outbox age and the post-search409rate),Search Servicecan 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 (likeAmerica/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
- How would you adapt the API and schema when a traveler requests an early return (shortening an active reservation) instead of an extension?
- 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?
- How do you keep geographic search availability reasonably fresh under load while handling listing time zones and Daylight Saving Time transitions accurately?
Similar questions
- Near-Zero-Downtime Relational Database Major Upgrade
- Cluster HTTP Request Routing and Resilient Retries
- Word Path Search on a Grid
- XGBoost vs. LightGBM for Conversion Prediction
- Marketplace Booking Conversion Drivers
- Global Live Video Streaming Platform