Caching and Inventory Architecture for a Vacation Rental Platform
System DesignModel answerLast updated
Design a multi-tier caching system for a high-traffic rental marketplace that serves fast search results while guaranteeing zero double-bookings through authoritative holds.
Background
You are designing the caching and inventory management layer for a vacation rental marketplace — think short-term rentals of apartments, cabins, and villas worldwide. The platform serves a massive volume of read traffic as users browse listings and check availability, but the actual reservation process demands strict correctness: two guests must never end up with the same property on overlapping nights.
Your job is to connect the fast, potentially stale world of search caches with an authoritative booking engine that makes final decisions.
What You Need to Support
Core Features
- Search and browsing: Guests search by location, travel dates, and party size. Results should feel instant.
- Listing detail and pricing: Guests can view nightly rates, fees, and property details before committing.
- Checkout hold: Once a guest starts the checkout flow, the property nights are reserved temporarily (10 minutes) so no one else can book them while payment processes.
- Booking finalization: A successful payment converts the hold into a confirmed booking. A failed payment or expired timer releases the nights back to available inventory.
Quality of Service Goals
- Search and listing endpoints must respond at p95 under 100 ms.
- A given property-night must never be confirmed to two different guests.
- Search must continue functioning even when the booking transaction engine is degraded.
- Stale pricing or availability in search results is tolerable, as long as both are authoritatively verified before a hold is placed.
Scale to Design For
- 500,000 properties, averaging 40 bookable units per property.
- 50 million search requests per day (~600 QPS average, 3,000 QPS peak).
- 100,000 bookings per day (~1.2 QPS average, 15 QPS peak).
- Roughly a 500:1 read-to-write ratio.
What a Strong Answer Covers
- Multi-tier caching architecture — how you layer CDN, a distributed cache (e.g., Redis), and in-process memory caches, and which data lives where.
- Moving from cached search to an authoritative hold — the revalidation step and the full state machine:
AVAILABLE → HELD → BOOKED, including expiry paths. - Concurrency control and idempotency — how you prevent two simultaneous hold requests from both succeeding, and how retries stay safe.
- Cache invalidation and reconciliation — how booking events propagate back to update cached availability, and what happens when things fall out of sync.
Hints
Hint 1
Start by separating the read path from the write path. Search at 3,000 QPS and booking at 15 QPS have completely different requirements — your design should treat them as two distinct systems that share data, not one system that does both.
Hint 2
The cache is never the source of truth for whether a night can be sold. Think about what database primitive (row lock, conditional update, unique constraint) actually prevents two holds from claiming the same night, and work backward from there to figure out where Redis fits.
Hint 3
A hold that expires due to a crashed worker or a failed payment must automatically release inventory. Design the expiry as a condition that the database checks on the next claim attempt, rather than relying solely on a background sweeper — that way correctness does not depend on the sweeper running on time.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
The first thing to say out loud: this system has two paths with opposing requirements. Search is read-heavy (3,000 QPS peak), latency-sensitive, and tolerates briefly stale data. Booking is write-light (15 QPS peak) but must be exactly correct — no overselling, ever. A strong design keeps these paths separate and is explicit about which one is authoritative.
The cache accelerates reads. The database decides what can be sold.
Scale Sizing
- 500K properties × 40 units = 20M bookable units. At 365 nights each, that is roughly 7.3 billion unit-nights — create these lazily or partition by date range.
- 3,000 QPS is well within a single Redis cluster's capability (~100K ops/s per node), but a city search fans out across hundreds of properties. Key design must control that fan-out.
- 15 QPS peak on bookings is trivially small. A single well-indexed Postgres primary handles it. Spend design effort on correctness here, not throughput.
One clarifying question worth raising: does the platform sell unit types (e.g., "one-bedroom suite") or specific physical units? The problem states physical units, so the data model tracks individual unit-nights. Room-type counts can still be maintained separately for fast search display.
API Surface
GET /search?location=&checkin=&checkout=&guests= # cached, may be stale
GET /listings/{id}?checkin=&checkout= # cached quote + quote_id
POST /holds body: {unit_id, checkin, checkout, quote_id}
header: Idempotency-Key
-> {hold_id, unit_id, price, expires_at} # authoritative
POST /bookings body: {hold_id, payment_token}
header: Idempotency-Key
DELETE /holds/{hold_id}
Search and listing detail are served from cache. The hold endpoint bypasses the cache entirely and talks directly to the booking service.
Data Model (Source of Truth)
unit_night (
unit_id BIGINT,
night_date DATE,
property_id BIGINT,
unit_type_id BIGINT,
status ENUM('AVAILABLE', 'HELD', 'BOOKED'),
hold_id BIGINT NULL,
expires_at TIMESTAMPTZ NULL,
version INT,
PRIMARY KEY (unit_id, night_date)
)
hold (
hold_id BIGINT PRIMARY KEY,
user_id BIGINT,
unit_id BIGINT,
checkin DATE,
checkout DATE,
price_snapshot NUMERIC,
status ENUM('ACTIVE', 'EXPIRED', 'CONSUMED', 'RELEASED'),
expires_at TIMESTAMPTZ,
idempotency_key TEXT UNIQUE
)
booking (
booking_id BIGINT PRIMARY KEY,
hold_id BIGINT UNIQUE, -- one hold → one booking, enforced
payment_id TEXT,
status ENUM('CONFIRMED', 'CANCELLED'),
idempotency_key TEXT UNIQUE
)
outbox (event_id, aggregate_type, aggregate_id, payload, created_at)
The primary key (unit_id, night_date) is the structural guarantee against double-booking. No two rows can exist for the same unit on the same night.
Caching Architecture
CDN — photos, static assets, and property description pages. TTLs measured in hours to days; use versioned URLs for instant invalidation on content changes.
Static metadata cache (Redis + in-process LRU) — property name, amenities, location, and host details. These change rarely; a 5–30 minute TTL is safe. An in-process cache (e.g., Caffeine on the JVM) absorbs repeated reads within a single pod without a network hop.
Dynamic availability cache (Redis) — this is the critical layer for search performance.
- Key:
avail:{property_id}:{yyyy-mm} - Value: a compact per-night structure holding
{unit_type: count, min_rate}for each night in the month. - TTL: 1–5 minutes, with event-driven refreshes on top (see Cache Invalidation below).
- A search spanning N nights reads one or two month-keys per property with a single
MGET, keeping latency well under 100 ms even with moderate fan-out.
Search index (Elasticsearch) — holds geo/location data, amenity filters, star ratings, and a coarse "has availability" flag. Returns ranked property IDs; those IDs are then enriched from Redis. The search index and Redis together serve the entire read path. The booking database is never in this call chain.
Hold State Machine and Revalidation
The state transitions are: AVAILABLE → HELD → BOOKED, with HELD → AVAILABLE on expiry, explicit release, or payment failure.
When a guest initiates checkout, the booking service ignores the cache:
- Revalidate price against current rate tables using the
quote_id. If the price changed, surface the new price and require explicit guest acceptance before proceeding. - Claim nights atomically:
UPDATE unit_night
SET status = 'HELD',
hold_id = :new_hold_id,
expires_at = now() + interval '10 minutes',
version = version + 1
WHERE unit_id = :u
AND night_date >= :checkin AND night_date < :checkout
AND (status = 'AVAILABLE'
OR (status = 'HELD' AND expires_at < now()));
-- If rows_affected != expected_night_count: ROLLBACK, try next candidate unit
- Insert the hold row and an outbox event in the same transaction, then commit.
Two properties make this safe:
- The conditional update is an atomic compare-and-set on each night row. No separate lock is needed.
- Lazy expiry: expired holds are claimable by the next requestor without waiting for a sweeper. A background job also sweeps expired holds and emits events, bounding cache staleness — but correctness does not depend on it running on time.
On payment success, a second conditional update confirms the booking:
UPDATE unit_night SET status = 'BOOKED'
WHERE hold_id = :h AND status = 'HELD' AND expires_at > now();
Zero rows updated means the hold expired during payment. Void the payment authorization rather than confirming. To minimize this race, authorize the card first and capture only after the DB transition succeeds. Accepting holds up to expires_at + 30s for in-flight payments is a reasonable grace period worth mentioning.
Why not use Redis SETNX as the lock? Redis SET key NX PX 600000 is a useful fast pre-filter that can shed obvious contention before the request reaches the database. It cannot be the guarantee: Redis replication is asynchronous, so failover can lose keys; and a GC pause can allow two lock holders to proceed simultaneously. The database row is the final arbiter, always.
Idempotency
- Clients include an
Idempotency-Keyheader onPOST /holdsandPOST /bookings. - The key has a unique constraint. Retries return the stored response rather than creating duplicate holds or charges.
- Forward the key to the payment provider (Stripe and Adyen both support this natively) to prevent double charges on timeout-and-retry.
booking.hold_id UNIQUEensures one hold can never produce two confirmed bookings.
Cache Invalidation and Reconciliation
Event-driven updates: each state change (hold created, booking confirmed, hold expired, cancellation) writes an outbox row in the same transaction. A CDC tool (e.g., Debezium) publishes outbox rows to a message bus (Kafka). An availability projector reads these events, recomputes the affected avail:{property_id}:{month} key from the database, and overwrites the Redis entry. Recomputing from the database rather than incrementing/decrementing makes the projector idempotent and tolerant of out-of-order events. Include a version or updated_at timestamp so a stale event cannot overwrite a fresher value.
TTL as a fallback: even if events are dropped, cache staleness is bounded to a few minutes.
Nightly reconciliation: a batch job compares cached availability counts against actual database state and corrects discrepancies. This catches any drift from edge cases not covered by the event stream.
Common Mistakes
- Using Redis as the booking lock without a database backstop — asynchronous replication makes this unsafe under failure conditions.
- Letting the search path call the booking database — this couples availability to booking latency and availability, violating the high-availability requirement.
- Incrementing/decrementing cache counters on events — out-of-order events corrupt the count. Recompute from source.
- Not handling hold expiry in the claim query — if the sweeper is slow, inventory stays stranded. The
expires_at < now()condition in the UPDATE is the fix. - Missing idempotency on the payment capture — a network timeout between DB commit and payment capture can result in a captured payment for an expired hold.