Design a Chat-Driven Flight Search, Checkout, and Fare-Alert Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Design a chat-driven flight discovery, checkout, and fare-tracking platform serving roughly 30 million daily active users (DAU). Travelers converse with an AI assistant to explore routes, select and purchase flights (including multi-segment connecting itineraries, not solely nonstop routes), and subscribe to lowest-fare alerts on saved trips. User prompts range from exact specifications ("JFK to Tokyo, Oct 10–18, 1 adult, economy") to broad, open-ended wishes ("I'm hoping to visit East Asia this autumn").
Constraints & Operating Assumptions
- External ground truth: Live seat inventory, schedules, fare rules, and prices belong to external airline and Global Distribution System (GDS) suppliers and can shift between initial search and final payment. The language model is never a source of truth for flight data or booking status.
- Retry safety: Checkout and payment calls arrive over unreliable mobile and web networks and may be retried or submitted twice.
- Supplier limits & product semantics: Clarify peak traffic assumptions, supplier rate quotas / look-to-book caps, whether scheduling includes ticket issuance, what user context is known (home airport, flexible dates, trip duration, budget, preferences), what "lowest fare" means across cabin, baggage fees, refundability, and stops, and how fresh and frequent fare alerts should be.
Scope & Expectations
- Grounded conversational search: Explain how ambiguous natural-language requests become validated multi-leg searches without hallucinating airports, schedules, or fare terms, and how broad regional queries stay within supplier quota budgets.
- Safe repricing & checkout: Detail the API boundaries, data model, live quote verification, and idempotent payment-and-ticketing workflow when fares change or network calls time out.
- Scalable fare tracking: Show how tens of millions of active price watches detect meaningful drops and notify users promptly without flooding airline suppliers with duplicate polling traffic.
- Resilience, privacy, & trade-offs: Cover capacity math, priority rate limiting, handling of sensitive traveler/payment data, and graceful degradation when suppliers or model serving fail.
Step-by-step walkthrough
Clarify requirements and separate the three trust zones
Three very different systems hide behind this single product, and each has a completely different tolerance for mistakes:
- Conversational discovery: turn a vague wish ("I'm hoping to visit East Asia this autumn") into a structured, validated search. A mistake here only means a suboptimal suggestion that the user can refine.
- Checkout and booking: lock in a live fare, charge money, and issue an airline ticket. A mistake here means charging a card twice, booking the wrong fare, or taking money without issuing a ticket.
- Price tracking: watch fares across millions of saved trips and alert users when prices drop. A mistake here either spams users or floods airline suppliers with billions of repetitive calls.
The core architectural rule follows directly from those three trust zones: the Large Language Model (LLM) lives only in the discovery zone. It can suggest search parameters and summarize results returned by tools, but deterministic backend code validates every airport, checks every price, and runs checkout.
Functional requirements
- Let users chat naturally—from exact prompts ("JFK to Tokyo, Oct 10–18, 1 adult, economy") to open-ended ones ("I'm hoping to visit East Asia this autumn")—and refine trips across multiple turns.
- Search one-way, round-trip, and multi-city flights, including connecting itineraries, and display accurate total prices.
- Book a selected itinerary end to end: re-verify the live price, collect traveler details, process payment, issue the ticket, and send confirmation.
- Let users track the lowest price for a route or itinerary and send alerts when the fare drops meaningfully.
Non-functional requirements
- Scale & latency: ~30 million Daily Active Users (DAU); chat responses start streaming within ~1–2 seconds, and flight search cards render within ~4–5 seconds.
- Financial safety: booking and payment behave as idempotent operations (meaning if a user taps "Pay" twice or a mobile network retries a timed-out request, at most one ticket and one charge are ever created).
- Supplier quota protection: flight data comes from external Global Distribution Systems (GDS) (centralized reservation networks such as Amadeus or Sabre) and direct airline APIs. Suppliers enforce strict rate limits and look-to-book ratios (contractual caps on how many search queries we may send per completed booking before paying penalty fees), so live searches and bookings always take priority over background price checks.
- Privacy & graceful degradation: passport numbers and payment cards stay isolated from prompts and logs; if the LLM or one airline supplier goes down, users can still search via structured filters and complete bookings on healthy suppliers.
Clarifying assumptions (to confirm with the interviewer)
- Does "schedule" include purchasing? Yes: users both pick itineraries and buy tickets through a payment processor.
- What user context exists? Profiles may store a home airport, loyalty numbers, and saved traveler profiles; missing trip details use transparent defaults stated aloud in chat.
- What does "lowest price" mean? The all-in total in the user's currency for all passengers, including the baggage the user asked for, filtered by cabin class, maximum stops, and refundability. Comparing a bare basic-economy fare against a fare that includes a $75 checked bag misleads users.
- How fresh must price alerts be, and how frequent? Trips departing within 14 days are checked roughly hourly, trips 14–60 days out every ~4 hours, and trips further out every ~12 hours, capped at 1 alert per watch per day and 3 alerts per user per day.
Back-of-the-envelope capacity and quota math
Let's translate 30 million DAU into concrete request rates, storage sizes, and supplier API budgets so we can see where the real bottlenecks sit.
1. Conversational layer (assume 30% of DAU chat on a given day, 8 turns/session, peak = 3x avg) Daily sessions 30M x 0.30 = 9M sessions/day Chat turns 9M x 8 = 72M turns/day Turn throughput 72M / 86,400 s = ~833 turns/s avg, ~2,500 turns/s peak LLM token volume ~4,000 input + ~300 output / turn = 288B input + 21.6B output tokens/day (~250k output tokens/s avg, ~750k/s peak) Chat history store 72M turns x ~3 KB = ~216 GB/day (~19.4 TB for 90-day retention) 2. Flight search (assume 4 concrete searches per session) User searches 9M x 4 = 36M searches/day (~417/s avg, ~1,250/s peak) Route-date fan-out ~3 (origin, dest, date) units avg = 108M units/day (~1,250/s avg, ~3,750/s peak) (up to 20 units for broad prompts like "East Asia in autumn") Supplier search calls assume 60% cache hit rate = 43.2M live calls/day (~500/s avg, ~1,500/s peak) Offer cache size sized for sustained peak: 1,500 new entries/s x 1,800 s TTL x ~30 KB = ~2.7M entries, ~81 GB RAM 3. Checkout & booking (assume 1.5% of sessions buy a ticket) Completed bookings 9M x 0.015 = 135k bookings/day (~1.6/s avg, ~5/s peak) Design target 10 bookings/s -> tiny QPS; strict consistency is the whole challenge 4. Price tracking (assume 20% of sessions create a watch, active for 30 days on average) Active watches 9M/day x 0.20 x 30 days = 54M active watches Naive hourly polling 54M x 1 call/hour = 1.296B calls/day (~15,000 calls/s -> IMPOSSIBLE) Shared route keys ~10 watchers per unique (route, dates, pax, cabin) = 5.4M distinct PriceKeys Adaptive schedule checked every ~4 hours on average (6x/day): 5.4M keys x 6/day = 32.4M checks/day (~375/s) Search piggybacking 30% already refreshed by live user searches -> 22.7M polls/day (~263 calls/s!) Price history store (22.7M polls + 43.2M live searches) x ~430 B = ~28.3 GB/day (~10.3 TB/year)Three takeaways from the numbers:
- Naive price polling breaks supplier contracts immediately: 15,000 supplier calls/s is 10x our peak live search traffic. Deduplicating watches into shared keys and piggybacking on user searches cuts background polling ~57x down to ~263 calls/s.
- LLM serving is the biggest compute bill: 288 billion input tokens/day means we should keep prompts compact, cache shared system instructions, route simple slot-extraction turns to smaller models, and never spend output tokens formatting fare tables that client UI code can render directly.
- Booking throughput is tiny (~5/s peak): we do not need exotic NoSQL sharding for bookings—a single relational primary with a synchronous standby easily handles the load while giving us rock-solid ACID transactions.
API contracts: structured cards, live quotes, and idempotent booking
The chat stream uses Server-Sent Events (SSE)—a standard one-way HTTP connection over which the server pushes incremental updates as soon as text tokens or flight cards are ready. Every write endpoint that creates a watch or charges money requires a client-generated
Idempotency-Key(a unique UUID per user click so retries return the original result instead of duplicating work).1. Conversational discovery POST /v1/conversations -> 201 {conversation_id} POST /v1/conversations/{id}/messages body: {text, client_msg_id} SSE stream events: {type: "text", delta} streamed assistant explanation {type: "clarify", question, quick_replies[]} at most one clarifying question {type: "results", search_id, offers[]} structured flight cards from Search Service {type: "watch_prompt", spec} one-tap "Track lowest price" action GET /v1/searches/{search_id}?sort=price&max_stops=1 2. Live repricing (quote) before checkout POST /v1/offers/{offer_id}/quote -> 200 {quote_id, total, currency, price_breakdown, bags_included, fare_rules, expires_at, price_changed: true|false, previous_total} 3. Checkout & booking (driven by explicit UI button, NEVER by the LLM) POST /v1/bookings Header: Idempotency-Key: <uuid> body: {quote_id, accepted_total, traveler_ids[], payment_token} -> 202 {booking_id, state: "QUOTE_CONFIRMED"} async workflow started; client polls/subscribes -> 409 {code: "PRICE_CHANGED", new_quote_id, new_total, previous_total} zero money charged -> 422 {code: "IDEMPOTENCY_KEY_REUSED"} same key reused with different payload GET /v1/bookings/{booking_id} -> {state, pnr_locator, ticket_numbers[]} 4. Price watches POST /v1/price-watches Header: Idempotency-Key: <uuid> body: {spec: {legs[], passengers, cabin, max_stops, bags, refundable_only}, alert_rule: {min_drop_pct, min_drop_abs}} GET /v1/price-watches DELETE /v1/price-watches/{watch_id}Why this API boundary eliminates whole classes of bugs:
- Structured cards vs. prose: Prices, flight numbers, and layover times render directly from
offers[]JSON produced by the Search Service, never from raw LLM text. - Separate
quotestep: Search results may be cached for up to 30 minutes. Calling/quoteasks the airline supplier to verify seat availability right now and return a short-livedquote_id. accepted_totalguard: Sending the exact dollar amount the user saw on screen guarantees the server will never charge a higher price silently; a price jump returns409 PRICE_CHANGEDbefore any card hold happens.- Tokenized payments: The browser or mobile app sends card numbers directly to the payment processor (such as Stripe or Adyen) and passes us only a single-use
payment_token, keeping raw card numbers out of our servers and prompts.
- Structured cards vs. prose: Prices, flight numbers, and layover times render directly from
Data model: separating shared price keys from per-user filters
Airport and city identifiers use IATA codes—standard three-letter codes such as
JFK(New York Kennedy airport) orTYO(all major Tokyo airports). To make sure booking notifications are never lost or sent prematurely, state changes use a transactional outbox (an append-only event table written inside the exact same database transaction as theBookingrow, then relayed to Kafka).Conversation (Document store, keyed by conversation_id, 90-day TTL) conversation_id, user_id, turns[{role, text, tool_calls[], tool_result_refs[]}], current_trip_intent (latest validated JSON), created_at TripIntent (Validated JSON object, never free text) legs[{origins[IATA], destinations[IATA], date_window: {from, to}, stay_nights: {min, max}}] passengers: {adults, children, infants}, cabin, max_stops, bags: {carry_on, checked}, budget: {amount, currency}, refundable_only, assumptions[] # explicit defaults applied by the assistant, e.g. "1 adult, economy" Offer (Redis cache, 30-min TTL, immutable once written) offer_id, supplier_id, supplier_offer_ref, segments[{carrier, flight_no, origin, dest, dep_local, arr_local, duration_min}], base_fare, taxes, bag_fees, comparable_total, currency, refundable, observed_at Quote (Redis, ~5-15 min TTL matching supplier guarantee) quote_id, offer_id, verified_total, currency, fare_rules_text, supplier_quote_token, expires_at Booking (Relational DB primary, strongly consistent) booking_id (PK), user_id, idempotency_key, UNIQUE(user_id, idempotency_key), request_hash, quote_id, accepted_total, confirmed_total, state, version, payment_intent_id, supplier_order_id (PNR), ticket_numbers[], created_at, updated_at BookingOutbox (Same Relational DB, committed atomically with Booking) event_id (PK), booking_id, event_type, payload_json, published_at PriceKey (Key-Value store, partitioned by key_hash) key_hash = SHA256(exact_legs_and_dates + passenger_counts + cabin) watcher_count, next_check_at, last_checked_at, volatility_score, bucket_offers[] # top cheapest offers PER filter bucket (nonstop, <=1 stop, refundable, +bag) PriceWatch (Relational / wide-column store sharded by user_id; secondary index on key_hash) watch_id, user_id, key_hash, filters: {max_stops, bags, refundable_only, preferred_carriers[]}, baseline_price, last_alerted_price (nullable), last_alerted_at, expires_at (departure date) PlaceCatalog (In-memory replicated reference table) & FareCalendar (KV store) PlaceCatalog: code, type (AIRPORT|METRO|COUNTRY|REGION), parent_regions[], min_connect_mins FareCalendar: (origin_metro, dest_metro, yyyy_mm) -> {lowest_total, observed_at}Why splitting
PriceKeyfromPriceWatchis critical:One shared PriceKey: JFK -> TYO, Oct 10-18, 1 adult, Economy bucket_offers stored from ONE supplier poll: - cheapest overall (1 stop, no checked bag): $780 (+ $75 bag fee = $855 with bag) - cheapest with 1 checked bag included: $820 - cheapest nonstop: $1,040 Watch A (wants <=1 stop, carry-on only) -> evaluates bucket_offers -> sees $780 Watch B (wants <=1 stop, 1 checked bag) -> evaluates bucket_offers -> sees $820 Watch C (wants nonstop only) -> evaluates bucket_offers -> sees $1,040Notice why
bucket_offersstores the cheapest few flights within each filter combination rather than only the 50 cheapest overall: on long-haul routes where the 50 cheapest flights all have layovers, keeping per-bucket winners ensures nonstop watchers (Watch C) still get an exact price from the same single supplier call!High-level architecture
[ Mobile / Web Client ] | | chat + search (SSE) | | explicit checkout / watch actions (HTTPS) v v [ API Gateway: Auth, TLS, Per-User Rate Limits ] | | v v [ Conversation Service ] [ Booking Service ] (loads turns + TripIntent) (ACID DB + Saga Worker) | | v +-----> [ Payment Processor ] [ LLM Orchestrator ] | (tool calls ONLY; no DB/payment access) | | | | | v v v | [ Place [ Search [ Price Watch | Resolver ] Service ] Service ] | (Catalog) (Fan-out & | | Ranking) v | | [ Key Scheduler ] | | | due PriceKeys | | v | | [ Refresher Workers ] | | | | +------+-------+ | | | v | [ Offer Cache & Fare Calendar ] <------------+ | | v v [ Supplier Gateway: Priority Token Buckets, Single-Flight, Breakers ] | v [ Airline Direct APIs / GDS / Flight Aggregators ] (All live search + refresher results) --> [ Observation Stream (Kafka) ] | v [ Change Detector ] --> [ Notification Queue ]Three boundaries keep the system safe and fast:
- Strict sandbox around the LLM: The LLM Orchestrator has no network path or credentials for the Booking DB, Payment Processor, or raw Supplier APIs—only read/propose tools (
resolve_place,search_flights,suggest_watch). - Single Supplier Gateway: Every outbound airline call passes through one gateway that enforces per-supplier quotas in strict priority order: (1) Checkout Quotes & Bookings, (2) Interactive User Searches, (3) Scheduled Watch Refreshes, (4) Nighttime Calendar Backfills.
- Unified Observation Stream: Every interactive user search publishes its fresh fares onto the same stream used by watch refreshers, giving popular routes free real-time price updates.
- Strict sandbox around the LLM: The LLM Orchestrator has no network path or credentials for the Booking DB, Payment Processor, or raw Supplier APIs—only read/propose tools (
Deep dive 1: turning vague chat into grounded, hallucination-free search
An LLM does not know live airline schedules, airport closures, or baggage fees—and if allowed to guess, it will invent plausible-sounding flights that do not exist. We prevent hallucinations with a three-gate loop on every chat turn:
User: "I'm hoping to visit East Asia this autumn from the New York area" | v Gate 1 (Catalog Grounding): LLM calls resolve_place("New York area") -> [JFK, EWR, LGA] and resolve_place("East Asia") -> REGION:EAST_ASIA (candidate list) | v Gate 2 (Deterministic Intent Validator): Code checks proposed TripIntent JSON before any search runs. Invalid dates, passenger ratios, or unresolved codes return a tool error. | v Gate 3 (Post-Reply Fact Checker): After Search returns Offer cards, regex/entity parser extracts every price, airport code, flight number, and time in the LLM's prose summary and verifies each appears in this turn's tool output.Let's write the deterministic validator so we can verify every rule—including chronological leg ordering and preventing identical origin/destination airports:
def validate_intent(intent, resolved_codes, today, max_days_ahead=330): """Return a list of validation errors; an empty list means safe to search.""" errors = [] legs = intent.get("legs", []) if not legs: errors.append("at least one flight leg is required") prev_earliest_departure = today for idx, leg in enumerate(legs): origins = leg["origins"] destinations = leg["destinations"] # 1. Every place code must come from resolve_place in this conversation. for code in origins + destinations: if code not in resolved_codes: errors.append(f"unverified place code: {code}") # 2. Prevent degenerate single-place loops like [JFK] -> [JFK]. if len(origins) == 1 and origins == destinations: errors.append(f"leg {idx + 1} has identical origin and destination") # 3. Check bookable calendar bounds (~330 days ahead for most airlines) # and ensure multi-leg trips move forward in time. win_start = leg["date_window"]["from"] win_end = leg["date_window"]["to"] if win_start < today or win_end < win_start: errors.append(f"leg {idx + 1} has an invalid date window") elif (win_end - today).days > max_days_ahead: errors.append(f"leg {idx + 1} exceeds the {max_days_ahead}-day airline schedule window") if win_start < prev_earliest_departure: errors.append(f"leg {idx + 1} cannot depart before leg {idx}") prev_earliest_departure = win_start # 4. Airline safety rule: each lap infant requires an accompanying adult. pax = intent["passengers"] if pax["adults"] < 1: errors.append("at least one adult passenger is required") elif pax["infants"] > pax["adults"]: errors.append("number of infants cannot exceed number of adults") return errorsAsk vs. assume policy. Asking five clarifying questions before showing a single price feels like filling out a tax form; silently guessing everything produces irrelevant flights. Our rule: ask at most one question per turn, only when a missing field completely changes the search AND has no safe default. Everything else gets a sensible default recorded in
assumptions[]and stated openly ("Showing typical 7-night economy fares for 1 adult with a carry-on—tap any filter to adjust"):- Origin: Default to the user's saved home metro (
[JFK, EWR, LGA]); ask immediately if unknown. - Dates: If a whole year or season is given ("this autumn"), show cached month-by-month
FareCalendarprices first and ask "Which month works best?" before spending live supplier quota. - Passengers / Cabin / Bags / Stay length: Default to 1 adult, economy, 1 carry-on, 8 nights; confirm exact passenger names and bag counts before
/quote. - Fare rules: Quoted verbatim from the supplier's
fare_rules_textduring/quote. If Gate 3 catches any ungrounded price or rule in the LLM's draft prose, it retries generation once and otherwise falls back to a safe deterministic template ("Here are the best options I found:") above the structured UI cards.
- Origin: Default to the user's saved home metro (
Deep dive 2: searching a whole region and connecting flights on a quota budget
East Asia has over 350 commercial airports, and "autumn" spans ~90 departure dates. Querying
350 airports x 90 dates = 31,500live supplier calls for one chat message would blow through supplier rate limits and look-to-book caps instantly.Instead, we narrow broad regional searches in two fast stages:
Stage 1: Score destinations locally in < 10 ms using our cached FareCalendar & PlaceCatalog score(dest) = w1 * budget_fit(FareCalendar[origin, dest, month], user_budget) + w2 * route_popularity(origin, dest) + w3 * theme_match(dest_tags, user_chat_preferences) # e.g., street food, temples, rail hubs + w4 * schedule_reachability(origin, dest) # nonstop or 1-stop service exists - w5 * calendar_staleness_hours Stage 2: Spend a capped live budget (max 20 route-date units per turn, 4-second parallel deadline) 1. Collapse multi-airport cities into metro codes (TYO covers HND/NRT; SEL covers ICN/GMP). 2. Pick the top 6-8 scored destinations. 3. For each destination, pick the 2-3 cheapest date pairs from FareCalendar. 4. Query Offer Cache first (60% hit); send cache misses in parallel through Supplier Gateway. 5. Display remaining destinations from FareCalendar labeled "Typical price from $740 (seen 3h ago)" with an on-demand "Check live price" button.Handling connecting flights safely. We do not stitch separate airline tickets together on our own by default: if Flight A on Airline X is delayed and misses Flight B on Airline Y bought on a separate ticket, Airline Y treats the passenger as a no-show and cancels the trip. Instead, GDS and aggregator shopping APIs return single-ticket connecting itineraries (interline or codeshare connections) that already obey each airport's minimum connection time (the shortest legal layover needed to clear terminals and customs) and obligate the airline to rebook missed connections for free.
True "lowest price" ranking. Before ranking, we compute each offer's
comparable_total = base_fare + taxes + required_bag_fees, filter out offers violatingmax_stopsorrefundable_only, deduplicate identical flight segments across suppliers, and highlight the Pareto front—the set of itineraries where no other option is simultaneously cheaper, faster, and has fewer stops (surfacing "Cheapest", "Fastest", and "Best Value").Deep dive 3: safe booking under retries, timeouts, and checkout price jumps
Because checkout spans two external companies (Payment Processor and Airline Supplier) that do not share a database transaction, we coordinate them with a saga—a sequence of persisted local steps where every step has an explicit undo (compensating) action if a later step fails.
Booking State Machine (stored in one relational row, guarded by optimistic version checks): CREATED | (re-verify Quote with supplier) +---> [live_total > accepted_total] ---> PRICE_CHANGED (HTTP 409; $0 charged, user prompted) v QUOTE_CONFIRMED | (place card hold via Payment Processor using booking_id as outbound idempotency key) +---> [card declined] -----------------> PAYMENT_DECLINED v PAYMENT_AUTHORIZED | (create PNR / order with Supplier using booking_id as client reference) +---> [sold out / rejected] -----------> void card hold ---> ORDER_FAILED v ORDER_CREATED | (issue e-ticket numbers) +---> [ticketing error] ---------------> cancel PNR + void card hold ---> TICKETING_FAILED v TICKETED | (capture the authorized card hold) +---> [capture error after retries] ---> void ticket within carrier void window ---> CAPTURE_FAILED v CAPTURED ---> CONFIRMED (transactional outbox triggers receipt + e-ticket email) * Any network timeout moves row to UNKNOWN_<STEP> for the background Reconciler *Look closely at three critical ordering choices here:
- Why authorize before
ORDER_CREATED, and capture afterTICKETED? Placing an authorization hold first ensures we never issue a real airline ticket to a declined card. Waiting untilTICKETEDto capture actual funds means that if the last seat vanishes during order creation or ticketing, we simply void the hold (which disappears immediately) instead of issuing a settled card refund that ties up the user's money for 5–10 business days. (For instant-purchase low-cost carriers whose APIs combine order + payment in a single call, the adapter passes payment authorization inline and uses supplier cancellation on failure.) - What happens when the price rises at checkout? If the user saw
$780(accepted_total = 780), clicked "Book", and the live reprice returns$815, the workflow halts atPRICE_CHANGEDbefore touching the payment processor and returns409with the new$815quote. If the user decides to accept$815, the client submits a brand-newPOST /v1/bookingswith a newIdempotency-Keyandaccepted_total = 815. (If the live price dropped to$760, we proceed automatically and authorize$760!) - Never blindly retry a timed-out create call: If
create_ordertimes out after 5 seconds, the airline may have already created the reservation! Retryingcreate_orderblindly could book two seats. Instead, the worker marks the rowUNKNOWN_ORDER, and a Reconciler worker first callsget_order_by_reference(booking_id): if found, it records the PNR and advances toTICKETED; only if the supplier confirms "not found" does it retry creation. A nightly reconciliation batch cross-checks allTICKETEDrows against supplier sales reports and payment settlement files to catch any discrepancy.
- Why authorize before
Deep dive 4: scaling 54M price watches without overwhelming suppliers
To turn 54 million watches from a 15,000-calls/s nightmare into a polite ~263-calls/s background workload, we combine four techniques:
- Key sharing across filter variants: All watches with the same
(exact_legs_and_dates, passenger_counts, cabin)attach to onePriceKey. Popular holiday routes share 1 supplier call across 50,000+ watchers. (Flexible "any week in October" watches read from theFareCalendarand attach to the top 3 cheapest date-pairPriceKeys.) - Adaptive refresh schedule: Trips departing soon change prices frequently; trips 9 months out barely move. Each key computes its next poll interval dynamically:
def refresh_interval_hours(days_to_departure, watcher_count, price_changes_last_24h): """Compute how many hours to wait before polling a PriceKey again.""" # Base schedule gets tighter as departure approaches. if days_to_departure <= 14: hours = 1.0 elif days_to_departure <= 60: hours = 4.0 else: hours = 12.0 # Halve the interval for volatile routes or high-demand keys. if price_changes_last_24h >= 3: hours = hours / 2.0 if watcher_count >= 1000: hours = hours / 2.0 # Never poll the same key faster than once every 30 minutes. return max(hours, 0.5)- Piggybacking on live user searches + single-flight deduplication: Whenever a live user search fetches
JFK -> TYO, Oct 10-18, the Observation Stream updates thatPriceKeyand pushesnext_check_atforward for free. Inside the Supplier Gateway, single-flight (request coalescing)—merging concurrent identical requests so only one outbound call runs while duplicate callers share its response—ensures two workers never poll the same route simultaneously. - Noise-free alert evaluation: When a new observation arrives for
PriceKey K, the Change Detector checks whether any filter bucket's minimum dropped by at least 1%. If so, it scansK's watchers in pages and comparescurrent_priceagainstreference_price = watch.last_alerted_price if watch.last_alerted_price is not None else watch.baseline_price. An alert fires only when:current_price <= reference_price * (1 - min_drop_pct)(e.g., >= 5% drop), andreference_price - current_price >= min_drop_abs(e.g., >= $30 saved), and- the watch hasn't alerted in the past 24 hours, and the user has received fewer than 3 alerts today.
Using
reference_priceinitialized frombaseline_priceand ratcheted down on each alert ensures a fare bouncing between$749and$755never spams the user. Alerts flow into a rate-smoothed notification queue labeled with observation timestamps ("$720 seen at 09:15—tap to verify live availability").- Key sharing across filter variants: All watches with the same
Scaling, privacy, failure modes, and key trade-offs
Quota protection & horizontal scaling
- Priority token buckets in the Supplier Gateway: A token bucket is a rate-limiting counter that refills at the supplier's contracted calls-per-second limit and spends one token per outbound request. Each supplier gets four priority buckets (Quotes/Bookings > Live Search > Watch Refreshes > Nightly Backfill); when traffic spikes or daily look-to-book ratios tighten, background refreshes pause automatically while checkout stays 100% unthrottled.
- LLM cost control: Route simple turns (updating dates or passenger counts) to a fast small model and reserve the frontier model for open-ended multi-city planning; enable prompt prefix caching on the static system prompt + tool definitions.
- PII & PCI vaulting: Passport numbers, dates of birth, and redress numbers live in an encrypted Traveler Vault with strict audit logs. The LLM only ever sees opaque tokens like
traveler_profile_1.
Graceful degradation matrix
Component Failure User Experience Automated Handling LLM serving down or slow Clean structured search form (Origin, Dest, Dates, Pax) Circuit breaker (an automatic switch that stops calling a failing service after repeated errors) trips at ~3 s timeout; search and checkout run without the LLM LLM hallucinates price twice "Here are the flights matching your search:" + UI cards Gate 3 fact checker drops prose and renders verified structured cards One airline supplier down Flights from healthy suppliers + labeled cached fares Per-supplier breaker opens; quotes/bookings disabled only for that supplier Payment or supplier timeout at checkout "Confirming your reservation—please don't rebook" Saga moves to UNKNOWN_*; Reconciler queries bybooking_idbefore any retrySummary of core trade-offs
- LLM as translator vs. deterministic truth: Adding schema validation and post-reply fact checking adds ~100–200 ms and occasional template fallbacks, eliminating invented airports, fake prices, and unauthorized bookings.
- Capped 20-unit regional fan-out vs. exhaustive live search: Ranking destinations via
FareCalendarmeans minor airports show cached "typical" prices until clicked, keeping latency under 4 seconds and supplier look-to-book ratios healthy. - Shared adaptive
PriceKeys vs. per-watch polling: Alerts on far-out trips can lag a sudden flash sale by a few hours, in exchange for cutting supplier polling ~57x from 15,000/s to ~263/s.
Intuition & how it works
Think of this system like a friendly travel advisor sitting next to an airport departure board and a strict bank teller:
- The travel advisor (the Large Language Model, or LLM) is great at turning a fuzzy human wish like "I'm hoping to visit East Asia this autumn" into concrete travel parameters—but is never allowed to quote fares from memory or touch a customer's credit card.
- The shared departure board (our Search Service,
FareCalendar, and deduplicatedPriceKeystore) fetches real flight schedules from airline suppliers once and shares the board across thousands of travelers watching the exact same route. - The bank teller (our deterministic Booking Service) insists on re-checking the live airline price at the counter, places a temporary hold on the card, prints the official airline ticket, and only collects the money once the ticket number exists.
Why do the naive approaches fail? Letting an LLM answer directly or execute bookings leads to invented airport codes, hallucinated baggage rules, and accidental charges. Querying every airport across an entire region live or polling 54 million saved price watches once an hour generates over 15,000 external calls per second—instantly violating airline API quotas and look-to-book ratios (contractual limits on how many searches a travel site can send per completed booking before paying penalties). Finally, charging a cached search price or blindly retrying a timed-out booking request either bills the wrong fare or buys duplicate tickets.
Here is a step-by-step trace of one traveler's journey from vague prompt to safe checkout:
1. Vague chat -> Grounded regional search:
User (home: JFK) says: "I'm hoping to visit East Asia in October under $950."
- LLM calls resolve_place("East Asia") -> catalog returns candidate metro codes (TYO, SEL, OSA, TPE...).
- Search scores candidates using cached FareCalendar, picks top 6 metros x 3 cheapest October date pairs
(18 live queries <= 20-unit cap), and renders verified UI offer cards (e.g., JFK->TYO Oct 10-18, $780).
2. Shared price tracking (54M watches -> 5.4M shared PriceKeys):
User taps "Watch JFK->TYO Oct 10-18 (nonstop or 1-stop, 1 checked bag)."
- Watch attaches to existing PriceKey K alongside 1,200 other watchers of JFK->TYO Oct 10-18.
- One background poll (or another user's live search!) updates K's per-filter offer buckets for all 1,201 users.
3. Checkout with live repricing & retry safety:
User taps "Book" on a $780 card -> client calls POST /quote -> supplier says fare is now $815!
- If price jumped during POST /bookings (accepted_total=$780), server halts with 409 PRICE_CHANGED ($0 charged).
- User accepts $815 -> client sends POST /bookings with Idempotency-Key="uuid-42" and accepted_total=815:
QUOTE_CONFIRMED -> PAYMENT_AUTHORIZED ($815 hold) -> ORDER_CREATED -> TICKETED -> CAPTURED -> CONFIRMED.
- Mobile Wi-Fi drops and retries "uuid-42": server returns the exact same CONFIRMED booking without double-charging.
Key trade-offs
- LLM as intent planner vs. deterministic code as source of truth. Letting an LLM generate flight answers directly is fast to prototype, but language models hallucinate schedules and fare rules. Restricting the LLM to proposing a structured
TripIntentvalidated against ourPlaceCatalog, rendering prices from structuredOffercards, and running a post-reply fact checker adds ~100–200 ms of latency and occasional template fallbacks, while guaranteeing zero invented airports or prices. - Asking clarifying questions vs. applying transparent defaults. Asking five questions up front drives users away; silently guessing everything runs the wrong search. Asking only when a missing field radically alters results without a safe default (such as unknown origin or picking a month inside "this autumn") while stating explicit defaults (
assumptions[]: 1 adult, economy, carry-on, 8 nights) delivers useful prices on turn one. - Budgeted 20-unit regional fan-out vs. exhaustive regional search. Live-querying all ~350 regional airports across dozens of dates would violate Global Distribution System (GDS) (centralized airline reservation network) quotas and take tens of seconds. Using a cached
FareCalendarand metro codes (TYO,SEL) to spend ~20 live queries on the highest-scoring destinations keeps latency under 4 seconds, at the cost of showing minor destinations with labeled cached prices ("seen 3h ago") until clicked. - Single-ticket supplier connections vs. self-transfer hacking. Stitching two separate airline tickets together sometimes uncovers cheaper fares, but if the first leg is delayed, the second airline treats the traveler as a no-show. Relying on single-ticket connecting itineraries from suppliers ensures legal minimum connection times (shortest safe layover per airport) and free airline rebooking during delays.
- Authorize -> Order -> Ticket -> Capture saga vs. instant charge. Coordinating checkout as a multi-step saga (a persisted state machine where each external call has a compensating undo step) requires an asynchronous worker and a timeout reconciler, but guarantees we never issue a ticket on a declined card and never settle money if ticketing fails (voiding an authorization hold is instant, whereas refunding a captured charge takes days).
- Shared adaptive
PriceKeys vs. per-watch polling. Grouping watches by(route, dates, passengers, cabin), storing the cheapest offers per filter bucket, adapting poll intervals (1h near departure vs. 12h far out), and piggybacking on live user searches cuts supplier calls ~57x (from ~15,000/s to ~263/s), trading away sub-minute alert speed on distant trips.
Common mistakes
- Allowing the LLM to call booking or payment APIs, or trusting its chat message ("Your flight is booked!") as real state instead of triggering checkout exclusively from explicit UI actions backed by an ACID database.
- Charging the cached search price without a live quote. Search prices are snapshots that go stale in minutes; checkout must verify a live
Quoteand reject any fare above the user'saccepted_total. - Blindly retrying
create_orderorauthorize_paymentafter a timeout. A network timeout does not mean the external call failed—retrying without first querying the supplier or payment processor bybooking_idcreates duplicate tickets or double holds. - Omitting an
Idempotency-Key(a unique client-generated request ID stored with the booking row so duplicate submissions return the first result), causing double taps on slow mobile connections to buy two tickets. - Polling suppliers once per
PriceWatch, or splittingPriceKeys by every user filter. Includingmax_stopsorchecked_bagsinside thePriceKeyhash shatters cache sharing; store per-filter winners inside one sharedPriceKeyand evaluate each watch's filters locally. - Comparing bare base fares without required baggage fees, which surfaces fake "lowest prices" that cost $75 more once the user's checked bag is added.
- Sending passport numbers, birth dates, or credit card numbers into LLM prompts or application logs, violating privacy and payment-card security rules.
Follow-up questions
- What safeguards prevent the conversational assistant from fabricating airport codes, flight schedules, or fare restrictions? Every geographic code must come from the
resolve_placetool backed by ourPlaceCatalog, andvalidate_intentrejects any code not returned by that tool during the conversation before a search can run. Fare rules are displayed exclusively from the supplier'sfare_rules_texton a liveQuote(or explicitly marked "shown at checkout" if absent). Finally, a deterministic post-reply checker extracts every airport code, flight number, time, and dollar amount from the LLM's draft prose and requires an exact match against the turn's tool outputs—regenerating once on mismatch and otherwise falling back to a fixed template above the structured offer cards. - How can you handle a region-wide prompt (such as an entire continent or multi-country region) without issuing live queries to hundreds of airports? First collapse multi-airport cities into metro codes (
TYO,SEL,OSA) so one query covers several airports, and score candidate destinations locally in milliseconds using our cachedFareCalendar(price fit vs. budget, popularity from the user's origin, stated trip interests, and nonstop/1-stop reachability). Then spend a strict live budget of ~20(origin, destination, date_pair)units across the top 6–8 destinations and their 2–3 cheapest weeks with a 4-second parallel deadline. Remaining destinations render immediately from theFareCalendarwith an explicit age label ("from $740, seen 3h ago") and an on-demand live-check button, while every live search refreshes the calendar for the next user. - Walk through your checkout flow when the airline raises the fare between search selection and payment submission. Every booking request carries
accepted_total—the exact price the user agreed to on screen—and the server verifies the live supplier price before touching the payment processor. If the fare rose (say from$780to$815), the booking stops inPRICE_CHANGEDand returns HTTP409with$0charged, displaying the old price, new price, and updatednew_quote_idso the user can explicitly confirm (submitting a newIdempotency-Keyif accepted). If the fare dropped, we automatically authorize the lower amount; if the fare jumps in the split second between card authorization and supplier order creation, the saga immediately voids the card hold and prompts the user with the same choice. - When millions of travelers track the exact same popular route and dates, how do you avoid sending redundant polling requests to airline suppliers? Watches subscribe to a shared
PriceKeyhashed only by(exact_legs_and_dates, passengers, cabin)while applying filters like nonstop-only or checked bags locally against per-bucket winners stored on the key, collapsing ~54M watches into ~5.4M keys. Keys are hash-partitioned so a single scheduler owns each key, single-flight request coalescing merges any concurrent duplicate refreshes in the Supplier Gateway, and live user searches resetnext_check_atfor free via the Observation Stream. Combined with adaptive intervals (1h near departure down to 12h far out) governed by a low-priority supplier token bucket, background polling drops from ~15,000 calls/s to ~263 calls/s and yields automatically whenever live search traffic spikes.
Follow-up questions
- What safeguards prevent the conversational assistant from fabricating airport codes, flight schedules, or fare restrictions?
- How can you handle a region-wide prompt (such as an entire continent or multi-country region) without issuing live queries to hundreds of airports?
- Walk through your checkout flow when the airline raises the fare between search selection and payment submission.
- When millions of travelers track the exact same popular route and dates, how do you avoid sending redundant polling requests to airline suppliers?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System