The Problem#
We want to build an online travel agency for flights, like Expedia, Kayak with booking, or an airline's own website. A traveller types "London to New York, 12 June, back 19 June, 1 adult", sees a list of flight options with prices in about two seconds, picks one, enters passenger details, pays, and receives a confirmation and an e-ticket.
That sounds like ticket booking for concerts, but three things make flights very different:
- We do not own the inventory. The seats live in each airline's reservation system. We reach them through intermediaries (global distribution systems), newer airline APIs (NDC), or direct connections to low-cost carriers. Every question we ask those systems is slow (hundreds of milliseconds to seconds), may cost money, and is rate limited.
- Prices are extraordinarily complex. An airline does not have "a price" for a seat. It publishes hundreds of fares per city pair, each with rules (advance purchase, Saturday-night stay, which flights, which other fares it may combine with), and opens or closes cheap "booking classes" minute by minute based on demand. Finding the cheapest valid combination of flights and fares is, in the worst case, a provably hard problem.
- People search far more than they buy. A traveller might run dozens of searches before buying, and each search looks at hundreds or thousands of flight combinations. The ratio of searches to bookings (the look-to-book ratio) is in the hundreds to thousands. We cannot ask the airlines every time; we must cache, and cached prices go stale.
An analogy. Imagine a travel agent in 1990 sitting with a phone line to every airline. A customer asks for the cheapest trip to New York. The agent cannot call every airline for every possible combination of flights, so they keep a big binder of last week's prices, use it to shortlist a few good options, then phone the airlines to confirm the price and hold the seats. If the airline says "that price is gone", the agent apologises and offers the next option. Our system is that agent, at millions of searches per hour: a fast, slightly stale binder (the cache) for browsing, and a careful phone call (a live check with the airline) before taking anyone's money.
Background: a few terms used in this design#
- Airline reservation system (CRS / PSS). The airline's own system holding its schedules, seat inventory, fares and bookings. PSS stands for passenger service system, the wider suite that also covers check-in and departure control.
- Global distribution system (GDS). A network such as Amadeus, Sabre or Travelport (which runs Apollo, Galileo and Worldspan) that connects travel agencies to many airlines' reservation systems through one interface. A GDS holds no inventory of its own; it routes requests to the airline's system in real time and keeps a copy of the booking.
- NDC (New Distribution Capability). An XML-based standard launched by IATA in 2012 to replace the older EDIFACT messages behind the GDS channel, so agencies can get the same offers (bundles, seats, bags) that airlines sell on their own sites.
- Fare. The price for one-way travel between two cities (a market) on one airline, identified by a fare basis code such as "H14ESNR", with rules attached.
- Booking class (RBD). A one-letter code (Y, B, H, Q...) that controls how many seats the airline will sell at a fare level. An availability answer looks like "Y9 B4 H4 Q0": up to 9 seats in Y, 4 in B, 4 in H, none in Q. Airlines usually cap the displayed count at 9.
- Fare component and priceable unit. A fare component is a fare plus the flights it pays for. A priceable unit is a group of one to four fare components in a fixed shape (one way, round trip, open jaw, circle trip) within which rules such as "Saturday-night stay" are checked.
- PNR (passenger name record). The booking record: passenger names, contact details, flight segments, ticketing information, special service requests. It is identified by a six-character record locator, the code printed on your confirmation.
- Segment status. Each flight in a PNR has a status, for example HK (holding confirmed) for a confirmed seat.
- Ticketing time limit. A deadline by which the booking must be paid and ticketed, or the airline cancels the seats.
- E-ticket. A record in the airline's ticketing database (ticket number, fare, taxes, form of payment) that proves the passenger paid. A reservation without a ticket is only a held seat.
- ATPCO. The organisation through which airlines file fares and rules; it distributes them to GDSs and search engines.
- Look-to-book ratio. Searches per booking. High ratios are why flight search depends on caching.
- Codeshare and interline. A codeshare flight is sold by one airline but operated by another. Interline means one ticket covers flights on several airlines that have agreements to carry each other's passengers.
Clarifying Questions#
| Question | Assumed answer |
|---|---|
| Are we an airline or a travel agency? | An online travel agency (OTA) selling many airlines; we will also explain what happens inside the airline's system |
| Which providers do we connect to? | Two or three GDSs, NDC APIs for major airlines that offer them, and direct APIs for some low-cost carriers |
| Trip types? | One way, round trip and multi-city; up to 9 passengers per booking |
| Scale? | About 500,000 bookings a day worldwide, around 1.5 passengers each |
| Search volume? | Look-to-book of about 1,000: roughly 500 million searches a day |
| Search latency? | First results within 2 seconds, full results within 5 seconds (p95) |
| Do we hold seats before payment? | Yes: we create a PNR on the airline (held, with a ticketing time limit) and then take payment and issue the ticket |
| Who is the merchant of record? | Both models exist: sometimes the airline charges the card, sometimes we do. We support both |
| Price changes between search and checkout? | Must be detected before payment and shown to the user; never charge a price the user did not accept |
| Ancillaries (seats, bags, meals)? | Yes, via NDC offers or GDS ancillary services, sold as extras |
| Changes and cancellations? | Voluntary changes and refunds by fare rules; involuntary schedule changes pushed by airlines must be handled |
| Fare sales with sudden demand (for example, a "1 euro" sale)? | Yes: must survive traffic spikes of 10× normal without hurting other customers |
Requirements#
Functional requirements#
- Search flights for one way, round trip and multi-city trips by airports or cities, dates, passengers and cabin, with filters (stops, times, airlines, price) and sorting.
- Show prices per itinerary with taxes and fees, and the fare's main rules (bags, change and refund conditions).
- Re-price a chosen itinerary live with the provider before booking, and tell the user if the price or availability changed.
- Book: create a PNR with the airline (through the right provider) for all passengers and segments, holding the seats.
- Take payment and issue tickets before the ticketing time limit; send confirmation with record locator and ticket numbers.
- Sell ancillaries: seat selection, extra bags, meals, where the provider supports it.
- Manage bookings: view, cancel, change dates, request refunds, according to fare rules; handle airline-initiated schedule changes.
- Price alerts and saved searches (light; covered in the price tracker case study).
Non-functional requirements#
- Correctness of bookings. Never charge a customer without a confirmed, ticketed booking (or refund automatically), never issue duplicate tickets, never leave a ticketed booking unknown to us.
- Search latency. First results under 2 seconds, complete under 5 seconds, at about 20,000 searches per second at peak.
- Freshness. Prices shown in search should match the live price at booking for at least 90-95% of attempts (a "price accuracy" target), and any mismatch must be caught before payment.
- Cost control. GDS and provider calls cost money per transaction and are rate limited; the system must keep provider calls per booking within a budget.
- Availability. 99.95% for search and booking. A single provider outage must not take down search for other airlines.
- Durability and auditability. Every booking, ticket and payment step logged and reconcilable with the provider and the payment processor.
- Security and privacy. Passport data, dates of birth and card data are sensitive; PCI DSS for cards, strict access to PNR data.
- Elasticity. Absorb fare-sale spikes without degrading normal traffic.
Capacity Estimation#
Start from bookings, then searches, then what those searches ask of the providers. The striking number is how far apart the two ends are.
Bookings.
- 500,000 bookings a day, about 1.5 passengers and 2.2 flight segments each (round trips, some with a connection): 750,000 passengers and about 1.1 million segments a day.
- 500,000 / 86,400 ≈ 6 bookings per second on average. Evenings and fare sales push this to about 60 per second, and a big airline sale can briefly reach 200 per second.
Searches.
- With a look-to-book ratio of about 1,000, that is 500 million searches a day: about 5,800 per second on average and 20,000 per second at peak.
- Each search considers many flight combinations. Carl de Marcken's notes on air travel planning (ITA Software, 2003) give a sense of scale: San Francisco to Boston alone has close to 30,000 same-day flight combinations, and allowing next-day arrival pushes one-way options past a billion. A search engine prunes hard, but it still evaluates on the order of 1,000 flights per search.
- 20,000 searches per second × 1,000 flights = 20 million availability lookups per second at peak. de Marcken makes the same calculation for the whole industry (1 flight departing per second × 150 passengers × 100 searches per passenger × 1,000 flights per search = 15 million availability questions per second) and notes that airline computers and networks cannot answer that load. Neither can ours: availability must come from a cache.
Provider calls and their cost.
- Suppose a live search call to a provider costs a fraction of a cent and takes 1-3 seconds. Sending every search live to three providers would mean 1.5 billion provider calls a day, far beyond any rate limit and a daily bill likely larger than the commission earned on the bookings.
- Target instead: at most a few percent of searches cause a live provider call (cache misses and refreshes), and about 10 provider calls per booking (live re-price, create PNR, add ancillaries, ticket, retrieve). At 60 bookings per second that is 600 booking-path calls per second at peak.
Storage.
| Data | Calculation | Size |
|---|---|---|
| Scheduled flights | About 30 million flights a year in de Marcken's 2001 data; more today. Say 100,000 a day × 330 days on sale | 33 million flight-dates |
| Seat availability cache | 33 M flight-dates × 26 booking classes × 1 byte | under 1 GB (more with O&D variants) |
| Schedules | 100,000 daily flights × 1 KB of route, times, aircraft | 100 MB |
| Fares and rules | Airlines publish from a handful to hundreds of fares per market (British Airways had more than 280 between Boston and London in de Marcken's example); hundreds of millions of fare records with rules | tens to hundreds of GB |
| Search result cache | About 50 M distinct search keys a day × 20 KB of results | about 1 TB working set |
| Bookings and PNR copies | 500,000 a day × 10 KB | 5 GB a day, 1.8 TB a year |
| Tickets and EMDs | 750,000 passengers × 2 KB | 1.5 GB a day |
| Search and price logs (for accuracy and analytics) | 500 M searches × 2 KB | 1 TB a day, to the data lake |
Two numbers stand out:
- Seat availability for every flight on sale fits in about a gigabyte. Like the availability bitmaps in the hotel booking case study, the core data is small. The hard part is not storing it but keeping it fresh, because airlines change it constantly and do not lock it for us.
- The ratio between searches and bookings (1,000 to 1) shapes everything. The search path must be cache-first and cheap; the booking path can afford slow, careful, live calls.
| Quantity | Average | Peak |
|---|---|---|
| Searches | 5,800/s | 20,000/s |
| Flight availability lookups inside search | 6 M/s | 20 M/s |
| Live provider calls from search | about 200/s | 1,000/s (capped by quotas) |
| Bookings | 6/s | 60-200/s |
| Provider calls from bookings | 60/s | 600-2,000/s |
| Search cache working set | about 1 TB | |
| Availability cache | about 1 GB |
Core Entities#
- SearchRequest: origin and destination (airports or cities), dates, passengers by type (adult, child, infant), cabin, filters. Normalised into a cache key.
- FlightSegment: carrier, flight number, operating carrier (for codeshares), origin, destination, departure and arrival times (local and UTC), aircraft, cabin, booking class.
- Itinerary: one or more legs (outbound, return, extra legs for multi-city), each a list of segments.
- Fare / FareComponent: fare basis, carrier, market, amount, currency, booking class, rules reference; the segments it covers.
- Offer: a priced itinerary from one provider: itinerary, fare components, taxes, total, baggage allowance, conditions, provider and provider's offer id, cache timestamp, expiry.
- PricedOffer: the result of a live re-price: guaranteed (for a short time) total, ticketing time limit hint, and a signature.
- Booking: our internal record: user, passengers, priced offer, status, total, currency, links to one or more PNRs (more than one if the trip combines separately ticketed airlines).
- PNRRef: provider, record locator (GDS and airline locators can differ), segment statuses, ticketing time limit.
- Passenger: name exactly as on the passport, date of birth, gender, document details (where required), loyalty number, special service requests (meals, wheelchair).
- Ticket / EMD: ticket number per passenger (13 digits), coupons per segment and their status; EMDs (electronic miscellaneous documents) for paid ancillaries.
- Payment: amount, currency, processor reference, status, merchant of record (us or the airline).
- ScheduleChange: an airline-initiated change to a booked flight (time change, cancellation, new flight number), with the action needed.
API Design#
# Search (streaming, because providers answer at different speeds)
POST /v1/flight-searches
{ slices: [{from:"LON", to:"NYC", date:"2027-06-12"}, {from:"NYC", to:"LON", date:"2027-06-19"}],
passengers: {adults:1}, cabin:"economy", filters:{maxStops:1} }
-> 202 { searchId, pollUrl, sseUrl }
GET /v1/flight-searches/{searchId}/results?cursor=..&sort=price|duration|best
-> 200 { offers:[{offerId, itinerary, totalPrice, currency, fareBrand, baggage, conditions,
priceAsOf}], complete:false, nextCursor }
GET /v1/flight-searches/{searchId}/events # SSE: new offers as providers respond
# Offer details and live price check
POST /v1/offers/{offerId}/price
-> 200 { pricedOfferId, total, currency, changed:true|false, previousTotal,
fareRules, baggage, expiresAt, signature }
-> 410 { reason:"no_longer_available", alternatives:[...] }
GET /v1/offers/{pricedOfferId}/seatmap
GET /v1/offers/{pricedOfferId}/ancillaries
# Booking: create PNR (hold), then pay and ticket
POST /v1/bookings Idempotency-Key: <uuid>
{ pricedOfferId, signature, passengers:[...], contact:{...}, ancillaries:[...] }
-> 201 { bookingId, status:"held", recordLocators:["ABC123"], ticketingDeadline, total }
-> 409 { reason:"price_changed", newTotal, newPricedOfferId }
POST /v1/bookings/{bookingId}/payment Idempotency-Key: <uuid>
{ paymentMethodToken, acceptedTotal }
-> 202 { status:"ticketing" } # ticketing completes asynchronously, usually in seconds
GET /v1/bookings/{bookingId}
-> 200 { status:"ticketed", tickets:[{passenger, number}], segments:[...], changes:[...] }
# After booking
POST /v1/bookings/{bookingId}/cancel
POST /v1/bookings/{bookingId}/change-searches { newDates } # priced change options
POST /v1/bookings/{bookingId}/changes { changeOfferId, acceptedTotal }
# Provider-facing (inbound)
POST /v1/providers/{provider}/notifications # schedule changes, queue messages, NDC order changesDesign notes:
- Search is asynchronous. Providers answer in 0.5-5 seconds. The client gets a search id and receives results as they arrive (SSE or polling). Cached results appear first, often within a few hundred milliseconds. See Polling, Long Polling, SSE, WebSockets and Webhooks.
- Two price checks, not one. The price on a search result says when it was computed (
priceAsOf). The livepricecall returns a short-lived guaranteed total, and the booking call verifies the signature. acceptedTotalon payment. The client sends the total the user saw and accepted. If the provider's price differs at ticketing time, the server stops and asks again instead of charging a different amount.- Idempotency keys on booking and payment, because both cause irreversible side effects on external systems. See Idempotency and Safe Retries.
- Ticketing is asynchronous: issuing a ticket can take seconds and occasionally fails; the client polls the booking status or gets a push notification.
High-Level Design#
We build the design one requirement at a time, then put it together.
1) Searching across providers#
A search fans out to several providers in parallel, each through an adapter that hides the provider's protocol (EDIFACT or SOAP for GDSs, NDC XML, REST JSON for low-cost carriers). Results are merged into one list.
- The orchestrator normalises the request (city codes to airport sets, dates, passenger types) into a cache key and checks the cache first.
- On a miss or a stale entry, it decides which providers to ask: not every provider sells every route. A routing table built from schedules says that a London-New York search needs the GDSs plus the NDC APIs of the transatlantic airlines, but not a domestic Indian low-cost carrier.
- Each adapter has its own timeout (for example, 3 seconds), concurrency limit and circuit breaker. Slow providers do not block fast ones: results stream to the client as they arrive.
- The aggregator removes duplicates (the same flights and fare from two channels; keep the cheaper or the preferred channel), applies our markups and fees, and ranks.
2) Our own shopping engine for the cache-first path#
Asking providers for every search is too slow and too expensive (see the capacity estimate). Large OTAs and metasearch engines therefore run their own low-fare search engine over data they hold locally: schedules, filed fares and rules (from ATPCO), and a cache of seat availability. ITA Software's QPX, which powered sites such as Orbitz and Kayak and was bought by Google in 2011 (it underlies Google Flights), is the best-known example.
- Schedules change daily, filed fares about ten times a day (de Marcken's figure), and availability continuously.
- The shopping engine builds candidate itineraries from schedules, prices them with filed fares and rules, and checks booking-class availability from the cache. It answers in well under a second without calling anyone.
- What it cannot see: private and negotiated fares, NDC-only offers and dynamic prices that are never filed. Those still need live provider calls, which is why both paths exist.
3) Live re-price before booking#
When the user picks an offer, the pricing service asks the provider that produced it for the current price and availability of exactly those flights and fares. The answer is stored as a priced offer with a short expiry and a signature. If it differs from the search price, the client shows the change. The fresh answer also updates the caches, so the next searcher sees a better price.
4) Booking: creating the PNR#
- The booking service validates passengers (names as on passports, ages matching passenger types), writes a booking row in state
creating, then asks the provider to create the PNR (or NDC order) with all segments for all passengers. - The provider returns record locators and segment statuses. All segments must come back confirmed; otherwise we cancel what was created and tell the user.
- A durable timer is set for the ticketing time limit: if we have not ticketed by then, the airline will cancel the seats, so we must either ticket or release cleanly.
5) Payment and ticketing#
- If we are the merchant of record, we authorise the card, issue the ticket, then capture. If the airline is the merchant, the card details go to the airline (through the provider) with the ticketing request, and the airline charges the card.
- Ticketing returns ticket numbers per passenger. Only then is the booking
ticketedand the confirmation email sent.
6) After the booking: servicing and schedule changes#
Airlines change schedules constantly. GDSs place affected PNRs on queues that the agency must read; NDC airlines send order-change notifications. The servicing service reads them, updates our booking, decides whether the change is minor (a 10-minute shift) or needs the customer (a cancelled flight, a missed connection), and handles voluntary changes and refunds requested by users.
7) Events and analytics#
Every search result, price check, booking, ticket and change produces an event. Consumers update caches, measure price accuracy (search price versus live price), feed notifications and price alerts, and load the data lake for analytics and ranking models.
The full high-level design#
Components:
- API gateway and waiting room: authentication, per-client rate limits, and a virtual waiting room that can be switched on during fare sales.
- Search orchestrator: normalises queries, checks the result cache, asks the shopping engine, fans out live calls to providers, streams merged results.
- Shopping engine: our own low-fare search over schedules, filed fares and the availability cache.
- Provider adapters: one per provider protocol; translation, connection pools, timeouts, quotas, circuit breakers, request and response logging.
- Pricing service: live re-price; produces signed priced offers.
- Booking service: creates PNRs or NDC orders, owns the booking state machine.
- Payment service and ticketing service: authorise, ticket, capture; issue EMDs for ancillaries; refunds.
- Servicing service: schedule changes, voluntary changes, cancellations, refunds.
- Timer service: durable timers for ticketing deadlines, offer expiries and follow-ups.
- Stores: bookings DB (relational, strong consistency), ledger DB, fare and schedule stores, caches (Redis or a key-value store), Kafka, data lake.
Key Flows#
Flow 1: Search with streaming results#
- The client sends the search. The orchestrator normalises it (London means LHR, LGW, LCY, STN, LTN and SEN unless the user chose one airport) and builds a cache key from origin set, destination set, dates, passenger mix, cabin and point of sale (country and currency).
- On a fresh hit the results return at once. On a miss the orchestrator returns a
searchIdwithin 100 ms and starts two paths in parallel. - The cached path asks our shopping engine, which answers in hundreds of milliseconds from local data. Its results are labelled with how fresh their availability is.
- The live path asks only the providers that sell this market. Each adapter enforces its own timeout. Results stream back as each provider answers.
- The aggregator merges, removes duplicates (the same flight and fare seen through two channels), adds markups, and ranks. Results go to the client in batches over Server-Sent Events (or the client polls with a cursor).
- When all providers have answered or timed out, the merged result is cached with a TTL that depends on how soon the flight departs (see deep dive 3).
Flow 2: Re-price and hold (create the PNR)#
- The pricing service asks the provider that produced the offer for a live price. The result becomes a priced offer with a 10–20 minute expiry and a server signature, so the client cannot change the price it sends back.
- The booking request carries a client-generated idempotency key. The booking service writes a row in state
creatingbefore calling the provider, so a crash mid-call leaves a record that a recovery job can resolve. - The adapter sells the segments, adds passenger names, contacts and a ticketing time limit, and ends the transaction so the provider stores the PNR. All segments must come back confirmed (
HK). - The booking moves to
heldwith the record locator and deadline. A durable timer fires before the deadline.
Flow 3: Payment and ticketing#
- The client sends the total it agreed to (
acceptedTotal). If the server's current total differs, the request fails with 409 before any card is touched. - The card is authorised, not captured. An authorisation can be voided for free; a capture needs a refund.
- Ticketing stores the fare on the PNR again and issues the e-tickets. Only then is money captured and the confirmation sent.
- If ticketing fails, the authorisation is voided and the user is asked again. The PNR stays held until its deadline, so a retry is possible.
Flow 4: The price changed at checkout#
The price moves because the cheap booking class sold out or closed, a fare was refiled, or the cached result was simply old. The fresh answer is written back to the caches so the next user sees the correct price. Every such event is counted in the price-accuracy metric.
Flow 5: The airline changes the schedule#
Airlines change times, flight numbers and aircraft every day. The PNR segments move to a status that means "schedule changed, waiting for acceptance", and the agency must act. Our servicing service checks the effect on connections (is the minimum connecting time still met?), accepts minor changes automatically and asks the customer about major ones.
Data Model#
CREATE TABLE bookings (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
idempotency_key TEXT NOT NULL,
state TEXT NOT NULL, -- creating, held, ticketing, ticketed, ...
priced_offer JSONB NOT NULL, -- snapshot of fares, rules, taxes
total_amount NUMERIC(12,2) NOT NULL,
currency CHAR(3) NOT NULL,
ticketing_deadline TIMESTAMPTZ,
version INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (user_id, idempotency_key)
);
CREATE TABLE pnr_refs (
id UUID PRIMARY KEY,
booking_id UUID NOT NULL REFERENCES bookings(id),
provider TEXT NOT NULL, -- amadeus, sabre, ndc:LH, lcc:FR
record_locator TEXT NOT NULL,
airline_locator TEXT,
UNIQUE (provider, record_locator)
);
CREATE TABLE tickets (
ticket_number CHAR(13) PRIMARY KEY, -- 3-digit airline code + 10 digits
booking_id UUID NOT NULL REFERENCES bookings(id),
passenger_id UUID NOT NULL,
status TEXT NOT NULL, -- open, used, exchanged, refunded, void
amount NUMERIC(12,2) NOT NULL
);
CREATE INDEX bookings_deadline ON bookings (ticketing_deadline)
WHERE state = 'held';- The priced offer is stored as a snapshot. Fare rules, taxes and the exact fare basis codes are what the customer bought; we must be able to show and apply them years later, even after the airline refiles.
(user_id, idempotency_key)is unique, so a retried booking request finds the existing row.(provider, record_locator)is unique. Locators are only unique inside one system, so the provider is part of the key.- The partial index on held bookings lets the deadline sweeper find work cheaply.
versionsupports optimistic concurrency between the booking flow, the servicing flow and the timers (see Concurrency Control and Database Locking).
| Data | Store | Why |
|---|---|---|
| Bookings, PNR references, tickets, payments | PostgreSQL (sharded by booking id, or a distributed SQL database) | Transactions, constraints, modest volume |
| Ledger | Separate PostgreSQL database, append only | Money needs double entry and audit |
| Search result cache | Redis or a key-value store with TTL | Large, disposable, fast |
| Availability cache | In-memory key-value store, replicated per region | 20 M reads per second, small |
| Fares, rules, schedules | Columnar files plus in-memory indexes in the shopping engine | Bulk loaded, read-only between loads |
| Events | Kafka | Fan-out to caches, notifications, analytics |
| Provider request and response logs | Object storage, compressed, indexed by booking and search id | Debugging, disputes, audits |
| Analytics | Data lake | Price accuracy, ranking, cost reports |
See Choosing a Database: A Decision Guide for how to reason about these choices.
Deep Dives#
1. Searching across many providers#
An OTA does not own a single seat. Every result comes from someone else's system, and each of those systems has its own speed, price per call, data format and quirks. The search tier is mostly an exercise in fan-out under a deadline.
The provider landscape.
| Channel | What it gives | Typical protocol | Latency | Cost model |
|---|---|---|---|---|
| GDS (Amadeus, Sabre, Travelport) | Most full-service airlines, published and many private fares, booking and ticketing | EDIFACT or SOAP/XML web services | 1–5 s for a low-fare search | Per booking (segment fees), search quotas and look-to-book limits |
| Airline NDC API | The airline's own offers, bundles and ancillaries, sometimes cheaper than GDS | NDC XML (offers and orders) | 1–4 s | Contract specific; may avoid GDS surcharges |
| Low-cost carrier API | Carriers that do not sell through GDSs, or sell only a subset there | REST/JSON or screen-style APIs | 0.5–3 s | Often free per call but rate limited |
| Our own shopping engine | Filed fares and cached availability | Internal | 100–500 ms | Our compute plus data licences |
| Aggregators and consolidators | Net fares negotiated by others | Varies | Varies | Margin share |
A GDS does not store seats either. As the Wikipedia article on global distribution systems describes, the GDS passes availability and booking requests through to each airline's reservation system in real time, keeping its own copy of the PNR that holds the whole itinerary, while each airline holds only its own segments. That is why GDS answers can be slow: our request travels through the GDS to one or more airline hosts and back.
Choosing whom to ask. Asking everyone for every search wastes money and quota. A market routing table maps (origin, destination, sometimes date and point of sale) to the providers worth asking:
- Built offline from schedules (who flies this market, directly or with one stop) and from history (which provider has actually won this market recently).
- A carrier that sells only through its own API is asked only when it serves the market.
- Low-value providers for a market are dropped when the provider's quota is under pressure.
Parallel calls with a deadline.
deadline = now + 5 s # whole search budget
for p in providers_for(market):
async call(p, request, timeout = min(p.p99_latency * 1.5, deadline - now))
as each answer arrives:
normalise -> dedupe -> price with markups -> stream to client
at first_results_deadline (2 s):
send whatever is ready, mark "still searching"
at deadline:
cancel outstanding calls, mark result "complete" (with missing providers listed)- Per-provider timeouts come from that provider's measured latency, not one global number.
- A slow provider is not allowed to hold the whole result. Partial results with a "still searching" indicator are better than a blank screen.
- Outstanding calls are cancelled at the deadline, otherwise threads and connections pile up during a provider brownout.
- Each provider has a bulkhead: its own connection pool and concurrency limit, so one slow GDS cannot exhaust all worker threads (see Resilience Patterns: Timeouts, Retries and Circuit Breakers).
Normalisation. Every adapter maps its answer to one internal model: segments (carrier, flight number, operating carrier, times in local time and UTC, aircraft, cabin, booking class), fare components (fare basis code, fare amount, taxes by code), baggage allowance, change and refund rules, and the provider token needed to re-price and book. Times are the classic trap: always keep local times plus the airport's time zone, and compute durations in UTC, because a flight that leaves at 23:30 and arrives at 06:10 may arrive "the day before" when crossing the date line.
Deduplication. The same journey can appear many times:
- The same flights and fare from two GDSs.
- The same flights from the GDS and from the airline's NDC API, maybe with different prices or bundles.
- Codeshares: one physical flight sold under several flight numbers. A flight operated as XY 117 may also be sold by a partner as AB 6141 on the same aircraft. Dedupe on the operating carrier and operating flight number, then keep the best offer, but show "operated by" clearly.
The dedupe key is the list of (operating carrier, operating flight number, departure date) plus cabin and fare brand. When two offers share a key, keep the cheapest unless there is a reason to prefer one channel (lower provider cost, better servicing, richer content).
Virtual interlining. Some of the cheapest journeys combine two airlines that have no agreement with each other: a low-cost flight from Manchester to Milan, then another carrier from Milan to Dubai. No single provider will return this. Our engine builds it from two separate one-way searches, sells it as two separate bookings, and must be honest about the risk: if the first flight is late, the second airline owes the traveller nothing. Products that sell such journeys often add their own guarantee and a longer minimum connection time.
Ranking. Cheapest first is the simple default, but users care about duration, number of stops, departure time and airline. A common score combines price, total duration and a penalty per stop, with weights learned from clicks and bookings. Tabs such as "Cheapest", "Fastest" and "Best" expose different sort orders. Ranking must also account for price confidence: a cached price that is likely to change at checkout should not win the top slot just because it is stale and low.
Provider cost control. The search tier is where the bill is made:
- Results are cached and reused across users (deep dive 3).
- Live calls go only to the providers that can win.
- Each provider has a quota budget per minute; the orchestrator spends it on searches most likely to convert (logged-in users, near-term dates, markets with high conversion).
- Look-to-book ratios are tracked per provider and per market, because contracts may limit them.
2. Why flight search is computationally hard#
It is tempting to think of flight search as shortest path on a graph of airports. Carl de Marcken's paper "Computational Complexity of Air Travel Planning" (ITA Software, 2003) shows why it is much harder, and it is worth knowing for any interview where someone says "just run Dijkstra".
The size of the network. Using 2001 data, the paper counts more than 4,000 airports with service, about 30 million scheduled flights a year (roughly one departure per second worldwide), and a very skewed network: the top 1% of airports handle about 40% of departures and the top 10% about 85%. The average shortest path between airports, in flights, is about 3.5 in the United States and 5 worldwide.
The size of the answer space. For a simple domestic pair such as San Francisco to Boston, the paper estimates about 30,000 reasonable same-day flight combinations, and more than a billion one-way options if next-day arrivals are allowed. For international pairs, where the shortest route may take five or six flights, there can be more than 10^15 flight paths within a small factor of the best one. No engine enumerates them all.
Why prices break shortest path. If each flight had a fixed price, Dijkstra would work. But airlines do not price flights; they price fares, and fares have rules:
- A fare is a price for travel in one market (for example, Boston to San Francisco) under a fare basis code with rules.
- A fare component is one fare applied to a sequence of flights. Every flight in a ticket must be covered by exactly one fare component.
- A priceable unit groups one to four fare components into a shape (one-way, round trip, open jaw, circle trip). Many rules apply at the priceable-unit level: "must stay over a Saturday night" or "14-day advance purchase" are checked across the outbound and the return together.
The price of a flight therefore depends on what else is on the ticket. The paper's small example is a round trip on one airline between Boston and San Francisco: a nonstop one way and a return that connects in Dallas. Using a $1,000 Y fare for the nonstop and the same Y fare again for both return flights costs $2,000. If the rules of two other fares are met, the return can instead be paid with a $500 fare between Boston and Dallas plus a $300 fare between Dallas and San Francisco, for $1,800 in total, on exactly the same flights. The cheaper answer exists only because of how the flights were split into fare components. Dijkstra assumes the cost of reaching a node does not depend on how you got there; fare rules break exactly that.
How much data. Airlines publish between a handful and hundreds of fares per market; the paper mentions more than 280 for British Airways between Boston and London. Each fare has rules covering days of the week, dates, minimum and maximum stay, advance purchase, combinability with other fares, surcharges, and more. One example in the paper, an American Airlines Boston–San Francisco fare, is valid only on certain weekdays, needs 14-day advance purchase and a Saturday night stay, and carries rules about which fares it may be combined with.
The complexity results. The paper proves, by reduction from 3-SAT, that even narrow versions of the problem are NP-hard:
- Finding the cheapest ticket with one fare and a fixed route, but free choice of flights, is NP-hard.
- With fixed flights and fixed priceable units, choosing fares is NP-hard.
- With fixed flights and fares, choosing how to group them into priceable units is NP-hard.
- With the full generality of real fare rules, the problem is EXPSPACE-hard, and with some rule types it becomes undecidable.
- Even checking that a printed ticket is priced correctly is, in the worst case, NP-complete.
What real engines do instead. Because exact search is hopeless, engines use structure and pruning:
- Bound the flight space. Limit connections (two or three), total duration (for example, no more than 2.5 times the fastest option), and connection times (the airport's minimum connecting time up to a few hours).
- Enumerate flight combinations per direction, in a compact form. A common technique is to represent the many combinations as a graph that shares common parts (the same first flight feeding many connections), rather than as a list.
- Find candidate fares per market with indexes on (market, carrier, date), and check the cheap, local rules first (day of week, dates, booking class availability).
- Combine fare components into priceable units and check the non-local rules (minimum stay, combinability) only for combinations that survive.
- Search for the cheapest few answers using dynamic programming and branch-and-bound over the shared structure, rather than enumerating.
- Diversify: return not only the 50 cheapest (which are often near duplicates) but good options per airline, per number of stops and per departure time.
Precomputation for inspiration searches. Calendar views ("cheapest day this month") and "anywhere" searches cannot run a full search per cell. They use precomputed low fares per market and date, refreshed from real searches and offline batch jobs, and labelled as estimates.
What this means for the design. The shopping engine is CPU-heavy, memory-heavy (fares, rules and schedules are held in memory per node) and stateless between requests. It scales horizontally: each node loads the same data, and the load balancer spreads searches. A single search may use one to several CPU-seconds, so 20,000 searches per second at peak means tens of thousands of cores if every search ran the full engine, which is one more reason to cache results.
3. Fare caching and staleness#
Caching is the single most important lever in this design. Without it, every search costs provider money and seconds of latency. With too much of it, users see prices that vanish at checkout. The whole problem is managing staleness on purpose.
What to cache, at which layer.
| Layer | What | Key | TTL | Notes |
|---|---|---|---|---|
| CDN | Static pages, airport lists, inspiration pages with "from" prices | URL | Minutes to hours | Never cache personalised or checkout responses |
| Search result cache | Merged results of a normalised search | origin set, destination set, dates, passengers, cabin, point of sale | 5 minutes to 6 hours by days-to-departure | Shared by all users with the same query |
| Provider response cache | Raw answers per provider, per market and date | provider, market, date, passenger mix | Shorter than the result cache | Lets us re-merge without re-calling |
| Availability cache | Seat counts per flight and booking class | carrier, flight, date, class (and O&D where available) | Minutes; refreshed by booking-path feedback | Used by our shopping engine |
| Fare store | Filed fares and rules | market, carrier | Until the next filing load | Bulk loaded, not a TTL cache |
| Priced offer store | Live price per offer | pricedOfferId | 10–20 minutes | Must never be reused across users without re-pricing |
The search result cache is cache-aside: the orchestrator checks it, calls providers on a miss and writes the result back. The CDN layer behaves as a read-through cache. Write-through does not fit here because we never write prices ourselves; the airlines do. Eviction is LRU with TTLs; long-tail markets fall out naturally while popular ones stay hot.
Getting the key right.
- Normalise everything that does not change the answer: upper-case codes, sort passenger types, map "London" to its airport set.
- Include everything that does: dates, passenger mix (a child fare differs), cabin, point of sale (the same flight can be priced differently when sold in another country or currency), and loyalty or corporate identifiers that unlock private fares.
- Do not include things that only change presentation (sort order, filters). Filter and sort the cached result instead.
A good key raises the hit rate from a few percent to 30–60% on popular markets: many people search London to New York for the same summer weekends.
TTL by days to departure. Prices for flights next week change by the hour as cheap classes sell out; prices for flights six months away change rarely. A simple and effective table:
| Days to departure | TTL for search results |
|---|---|
| 0–3 | 5–10 minutes |
| 4–14 | 15–30 minutes |
| 15–60 | 1–2 hours |
| 61+ | 3–6 hours |
Better still is a volatility-based TTL: track how often re-prices for this market disagreed with the cached price, and shorten the TTL when the disagreement rate rises. During a fare sale the volatility spikes and TTLs shrink automatically.
Measuring staleness: price accuracy. Every live re-price is a free experiment. Log (cached price, live price, cache age, market, days to departure, provider). Then:
- Price accuracy = share of re-prices where the live price is within a tolerance (for example, ±1% or ±£2) of the displayed price. A target of 90–95% is reasonable.
- Availability accuracy = share of offers still bookable at re-price.
- Plot both by cache age to choose TTLs from data rather than guesses.
Feedback from the booking path. Re-prices and bookings return fresh availability. Writing that back to the availability cache keeps hot markets fresh at no extra provider cost. When a re-price says "class K sold out on XY117 on 12 June", every cached result containing that class on that flight is now suspect. Two choices:
- Precise invalidation: an index from (flight, date, class) to cache keys; delete or mark those entries. Exact, but the index is large.
- Cheap marking: store a "changed at" time for each (flight, date); when a cached result is read, compare its creation time with the change times of its flights and re-price on the fly if any changed. This is cheap and usually enough.
Proactive refresh of hot markets. Popular markets (top few thousand origin-destination-date combinations) are refreshed in the background before their TTL ends, using spare provider quota at off-peak hours. Users then nearly always hit a fresh entry. This is cache warming with a budget.
Stampedes. When a hot key expires, thousands of concurrent searches could all miss and call providers at once. Defences (see Cache Failure Modes: Stampedes, Hot Keys and Penetration):
- Request coalescing: one in-flight provider call per key; other requests wait for it.
- Serve stale while revalidating: return the old entry (flagged as older) and refresh in the background.
- Probabilistic early expiration: refresh a little before the TTL, with a probability that grows as expiry nears, so refreshes spread out.
When the cache itself fails. If Redis is down, every search goes to providers. A circuit breaker on the cache client fails fast, and the orchestrator switches to a degraded mode: only the shopping engine path, fewer providers, longer timeouts on results. Users get slightly worse results instead of a site that collapses under its own provider bill.
The cost model. Suppose a live search costs us on average 0.1 cents in provider fees and compute, and we run 500 million searches a day. Without caching: $500,000 a day. With a 60% hit rate and the shopping engine answering half the misses alone: about $100,000 a day. The cache pays for itself many times over. (The numbers are illustrative; real provider pricing is contract specific.)
4. Seat inventory and holds#
The hardest constraint in flight booking is that we cannot lock the inventory. The seats live in the airline's system, and the airline sells them through many channels at once: its own website, its call centre, every GDS, every NDC partner.
How the airline sees inventory. A flight has a physical capacity per cabin (say 30 business and 180 economy seats). Revenue management divides each cabin into booking classes (also called fare buckets), identified by single letters. Availability is shown as a count per class, for example Y9 B9 M7 K4 Q0 V0: up to 9 seats (the display is usually capped at 9) in Y and B, 7 in M, 4 in K, none in Q and V.
- Nesting. Higher classes can always use seats available to lower ones. If K shows 4, M and Y show at least 4. Selling a K seat reduces K, M, B and Y together.
- Classes close before the plane is full. Revenue management closes cheap classes to protect seats for later, higher-paying demand (deep dive 9). A class can close even if nobody booked, because the demand forecast changed.
- Origin and destination control. Many airlines decide availability based on the whole journey, not just the flight. The seat from London to New York may be open in class K for a passenger connecting onward to a long-haul destination (who pays more in total) and closed for a passenger flying only London to New York. The same flight therefore shows different availability depending on the full itinerary.
- Married segments. Connecting flights sold together under O&D control must be booked, changed and cancelled together; you cannot book the connection and then cancel one leg to keep a cheap local fare.
Why our cache can only be a hint. The availability we cached a minute ago may be wrong now: seats were sold elsewhere, or a class closed. De Marcken's paper estimates that an engine like ITA's would need to ask about 15 million availability questions per second to stay fully live, (one departure a second, 150 passengers a plane, about 100 searches per passenger, about 1,000 flights examined per search), which neither airline computers nor their networks could answer, so ITA built a distributed, scalable seat availability cache. The paper also notes there is no locking: an availability answer is not guaranteed for any period of time. The consequence for us: our search results are always a prediction, confirmed only by a live re-price and then by the airline accepting the sell.
Holds are PNRs, not rows in our database. In ticket booking or hotel booking, a hold is a row or a key in our own store. Here, the only hold that matters is the airline's:
- We sell the segments to the airline (through the GDS or NDC), which decrements its inventory.
- We add names and contacts and end the transaction, creating the PNR.
- The airline sets, or the fare rules imply, a ticketing time limit: pay and ticket by this time or the seats are cancelled. For some fares it is days; for many low fares it is "ticket within 24 hours of booking" or even "ticket immediately".
- Low-cost carriers often have no hold at all: booking and payment are one call.
So our booking flow adapts to the provider: hold then pay where holds exist, pay then book where they do not. In the second case the card is authorised first, then the airline booking is made, then captured; if the booking fails, the authorisation is voided.
Seat maps are not inventory. Choosing seat 23A is separate from having a seat on the flight. The seat map comes from a different airline service, may cost extra (an ancillary, ticketed as an EMD), and can usually be chosen after booking. Do not mix the two in the model.
Hold abuse. Holding seats costs the airline real inventory. Bots that create PNRs without ticketing, to block seats or to scrape prices, are a known problem, and GDSs and airlines penalise agencies with many unticketed or duplicate bookings. Our controls:
- Limit active unpaid holds per user, device and payment method.
- Require an account and a valid payment method before holding on fares with long time limits.
- Cancel unpaid holds well before the airline's deadline, releasing the inventory voluntarily.
- Detect duplicates (the same passenger name on the same flight twice) and stop them before they reach the provider.
Time limits and timers. Every held booking has a durable timer at, say, deadline minus 30 minutes. When it fires: if payment is complete, try ticketing again; if not, cancel the PNR and tell the user. The timer must be durable (a database row or a workflow engine timer), not an in-memory schedule, because missing a deadline means either a lost booking or a ticket we must issue without payment. See Pattern: Multi-Step Processes and Workflows.
5. The booking flow and PNRs#
What a PNR is. A Passenger Name Record is the airline industry's booking record. The concept grew out of interlining, when one journey had to be shared between several airlines' systems, and its format is standardised by an industry agreement called AIRIMP. A PNR must contain five things before it can be stored:
- Name of each passenger.
- Contact details (for the agency and, increasingly, the passenger).
- Ticketing information: a ticket number, or a ticketing time limit.
- Itinerary: at least one segment.
- Received from: who made the booking.
It also holds special service requests (SSRs) such as meals, wheelchairs or passport details, other service information (OSI), remarks, and government-required data. Every PNR has a record locator, a six-character code of letters and digits, which is what the traveller types at check-in.
One booking, several PNRs. When we book through a GDS, the GDS creates its own PNR with the whole itinerary, and each airline in the journey creates its own PNR for its segments, with its own locator. A booking of London–Frankfurt on one airline and Frankfurt–Singapore on another, made in Amadeus, may have three locators: one in Amadeus and one in each airline. Customers often need the airline's locator for check-in and seat selection, so we store all of them (the pnr_refs table). A virtual interline journey (deep dive 1) has two completely independent bookings, with separate PNRs and separate tickets.
The booking state machine.
Each transition is a guarded update (UPDATE bookings SET state = 'held', version = version + 1 WHERE id = $1 AND state = 'creating' AND version = $2), and each writes an event to the outbox in the same transaction, so downstream systems see every change exactly once (see Distributed Transactions: 2PC, Sagas and Outbox).
Segment statuses. Each segment in a PNR carries a status code. A few you will meet:
| Code | Meaning | What we do |
|---|---|---|
| HK | Holds confirmed | Normal |
| SS | Sold (sell request accepted, becomes HK after end of transaction) | Wait for end of transaction |
| UC / UN | Unable to confirm / flight not operating | Booking failed for this segment; cancel the rest and tell the user |
| HL | Waitlisted | We do not sell waitlists in this design; cancel |
| TK / UN plus a new segment | Schedule changed | Servicing flow (Flow 5) |
The exact codes vary by system; the principle is that a booking is not confirmed until every segment is confirmed.
The unknown state. The most dangerous moment is a timeout while creating the PNR. Did the airline sell the seats or not? Retrying blindly may create a second PNR with the same passengers, which airlines penalise as a duplicate booking. The recovery job:
- Waits a short time, then searches the provider for PNRs created by our office with this passenger name and these flights (GDSs support retrieving bookings by name and flight).
- If one exists, attaches its locator and moves the booking to
held. - If none exists after a few checks, marks it
failed; the user can retry with the same idempotency key, which now creates a fresh attempt.
Where providers support it (many modern APIs do), we pass our own booking id as a client reference or idempotency key, so a retry returns the existing PNR instead of creating a new one. See Idempotency and Safe Retries.
Multi-provider bookings. A journey sold as two bookings (virtual interline, or one leg from a GDS and one from a low-cost carrier API) is a small saga:
- Book leg A (hold if possible).
- Book leg B.
- If B fails, cancel A (the compensation).
- Pay and ticket both; if ticketing B fails after A is ticketed, try to rebook B on another flight, else void or refund A.
Book the leg that cannot be held (usually the low-cost carrier) last, so the leg that can be cancelled for free is the one at risk.
Queues: the agency's inbox. GDSs place PNRs on numbered queues when something needs the agency's attention: schedule changes, ticketing deadlines, waitlist clearances, messages from airlines. A queue reader polls each queue, removes items, and turns them into events for the servicing service. Queues are an old mechanism, but they are how most change notifications still arrive for GDS bookings; NDC adds push notifications for order changes.
Record locator versus our booking id. Our booking id is stable for life. The record locator can change (a PNR split when one passenger changes their trip moves that passenger to a new PNR), and different systems have different locators. Never use the locator as our primary key.
6. Payments, ticketing and settlement#
Who is the merchant? Two models exist, and many OTAs use both:
- Airline as merchant. We pass the customer's card to the airline in the ticketing request. The airline charges the card and the customer's statement shows the airline. We earn commission or charge a separate service fee. The card details must pass through our systems under PCI DSS rules, usually tokenised and sent through a vault that injects the card number into the provider request.
- Agency as merchant. We charge the customer, then pay the airline through the industry settlement system. We control the checkout, can bundle hotels and cars, and carry the fraud and chargeback risk ourselves.
Settlement through BSP and ARC. Agencies accredited by IATA report their ticket sales through IATA's Billing and Settlement Plan (BSP) in most countries; in the United States the equivalent is the Airlines Reporting Corporation (ARC). In broad terms, the settlement system collects what agencies owe for tickets issued in a period and pays each airline, net of commissions and refunds. Exact cycles and rules differ by country and change over time, so the design treats settlement as a batch reconciliation job against the settlement system's reports, not as a real-time flow.
Ordering the money and the ticket.
| Order | Risk | When to use |
|---|---|---|
| Authorise, ticket, capture | Small: an authorisation may expire if ticketing is slow | Default for agency as merchant |
| Capture, then ticket | We hold money for a product we may not deliver; refunds needed on failure | Avoid |
| Ticket, then charge | We owe the airline even if the card fails | Never, except for trusted corporate accounts |
| Airline charges at ticketing | The airline carries card risk; we must handle its declines | Airline as merchant |
The ticket. An e-ticket number is 13 digits: the airline's 3-digit ticketing code, a 4-digit form number and a 6-digit serial number, sometimes followed by a check digit. IATA made electronic ticketing mandatory for its members from 1 June 2008; paper tickets are essentially gone. Each ticket has coupons, one per flight, whose status moves from open to checked in to flown (or exchanged, refunded). Ancillaries such as bags and seats are sold on Electronic Miscellaneous Documents (EMDs), which replaced the older paper Miscellaneous Charges Order.
Reconciliation. Three records must agree for every booking: our ledger, the payment processor's reports, and the provider's ticketing reports (and later the settlement reports). A nightly job matches them:
- A ticket issued with no matching capture: money lost, investigate.
- A capture with no ticket: refund the customer.
- A ticket voided by us but still on the settlement report: dispute.
Voids are usually allowed only on the day of issue (often within 24 hours), so the reconciliation of ticketing failures must be fast.
Refunds and changes follow fare rules. A non-refundable fare may still refund taxes; a changeable fare charges a fee plus any fare difference. The rules come from the fare filed by the airline, which is why we store the fare basis codes and rule snapshot on every booking. When several fares are on one ticket, the most restrictive rule usually applies to the whole ticket.
Fraud. Airline tickets are a classic target for stolen cards: they are expensive, sold online, and the fraudster gains value immediately (they fly, or resell the ticket). Common signals are last-minute one-way trips, a passenger name that does not match the cardholder, mismatched country of card and IP, and many bookings from one device. Controls are 3-D Secure for risky transactions, a fraud score before ticketing, and manual review for high-risk bookings with departures far enough away. See Rate Limiting and Throttling for controlling automated abuse.
The ledger. Each booking produces double-entry records: customer receivable, airline payable, our commission or markup, taxes collected on behalf of governments, payment fees. The ledger is append only; corrections are new entries. Currency conversion is recorded with the rate used at the time.
7. Overbooking#
Overbooking is an airline decision, not ours, but an interviewer who asks about flight booking often asks about it, and it changes what our system must handle (denied boarding, rebooking, compensation claims).
Why airlines overbook. Some passengers with tickets do not show up (no-shows), especially on flexible fares that can be changed or refunded freely. If an airline sold exactly as many seats as it has, every no-show would fly as an empty seat. So airlines sell more tickets than seats, betting that enough people will not show.
The math. Model each ticketed passenger as showing up independently with probability p. With n tickets sold on a plane with C seats, the number who show is binomial (n, p). Two costs pull in opposite directions:
- Empty seat: lost revenue, say £200 (an average fare).
- Denied boarding: compensation, rebooking, hotel and goodwill, say £600 per passenger bumped.
For C = 180 and p = 0.92 (8% no-shows), the exact binomial gives:
| Tickets sold | P(more show than seats) | Expected passengers bumped | Expected empty seats | Expected cost |
|---|---|---|---|---|
| 180 | 0% | 0 | 14.4 | £2,880 |
| 186 | 0.2% | 0.003 | 8.9 | £1,779 |
| 190 | 5.6% | 0.11 | 5.3 | £1,125 |
| 193 | 22% | 0.55 | 3.0 | £928 |
| 195 | 40% | 1.21 | 1.8 | £1,091 |
The cost is lowest around 193 tickets: the airline accepts a 22% chance of an oversold flight, because the expected number of bumped passengers is only about half a person, while the expected empty seats fall from 14 to 3. If bumping became more expensive, the optimum would move down; with more no-shows, it would move up. Real systems estimate p per flight, date, fare class and passenger mix from history (groups and business travellers behave differently), and do not assume independence: a delayed inbound flight or a storm makes many passengers miss together.
What actually happens at the gate. Most oversales are resolved by volunteers, not by force. The Wikipedia article on overselling reports that in 2018 the 17 largest US airlines denied boarding to 351,904 passengers, of whom only 10,938 were involuntary. Some airlines run an auction: Delta began in 2011 asking passengers at check-in how much compensation they would accept to give up their seat, and the same article reports that, per 100,000 passengers, Delta bumped 96 in total but only 3 involuntarily, against 95 and 11 for United. Some airlines chose not to overbook at all; JetBlue, for example, did not overbook until 2017.
Regulation. Both the EU and the US require airlines to ask for volunteers first.
- EU Regulation 261/2004 sets lump-sum compensation of €250 up to €600 per passenger for denied boarding, cancellations at short notice and delays of more than three hours on arrival (four hours for long-haul flights), unless extraordinary circumstances apply. It covers every flight departing the EU, whatever the airline, and flights into the EU operated by an EU-based airline. So a London–New York flight on a US airline is covered (London was inside the EU when the rule was written, and the UK kept an equivalent rule), but the same airline's return flight is not. Our rules engine needs the departure country and the operating carrier's home to decide.
- United States, 14 CFR Part 250 requires a request for volunteers and sets minimum compensation for involuntary denied boarding, scaled by the length of the delay and the fare paid, with caps. The cap amounts are adjusted periodically, so the system should read them from configuration rather than hard-code them.
The cost of getting it wrong. On 9 April 2017, after a fully boarded United flight, the airline asked for four volunteers to give up their seats for $800 vouchers so four of its crew members could travel. Nobody volunteered, four passengers were chosen, and one who refused was forcibly removed by law enforcement officers. Videos filmed by other passengers spread worldwide. (United later said the flight was sold out rather than overbooked.) The same month, severe weather on the US East Coast caused Delta more than 3,200 cancellations in five days, and with so many stranded passengers the oversold flights led to unusually large voucher payouts. The lesson for design: denied boarding is a customer-experience event and a disruption-handling problem, not only an optimisation.
What our OTA system must do.
- Receive notifications of denied boarding, cancellations and long delays from the airline and the passenger.
- Help customers claim compensation under EU 261 where it applies (a common product feature).
- Rebook through the servicing flow, respecting the original fare's rules (involuntary changes usually waive fees).
- Record everything on the booking's event history for disputes.
Non-refundable fares are partly the airline's answer to overbooking: when a no-show forfeits the fare, the airline loses less from no-shows and needs less overbooking.
8. Price changes during checkout#
The most common complaint in flight booking is "the price went up when I clicked". It is also the clearest symptom of the trade-off between cache freshness and cost.
Why prices change between search and booking.
- The cached result was stale. The price was correct when cached but the cheapest booking class has since sold out or closed.
- Availability changed in the last seconds. Another channel sold the last seat in the class.
- The fare was refiled. Airlines file new fares several times a day; a fare can disappear.
- The shopping engine priced differently. Our engine priced from filed fares; the provider applies a rule we did not model, a surcharge, or a different tax.
- Currency and fees. Exchange rates move; card fees depend on the card.
Two checks, not one. We price live twice:
- At offer selection: the user sees the true price before entering passenger details. This is where most changes should surface.
- At booking and again at ticketing: the fare is stored on the PNR when booked, and the airline confirms it at ticketing. A change at this stage is rare but possible, especially after a long time between hold and payment.
The acceptedTotal contract. The client sends the total the user agreed to. The server compares it with the current total:
if current_total <= accepted_total:
proceed # a lower price is passed on
elif current_total - accepted_total <= tolerance(booking):
proceed and absorb the difference # e.g. up to £2 or 0.5%, funded by margin
else:
reject with 409 price_changed { new_total, reason }A small tolerance, paid from our margin, avoids interrupting users for trivial changes such as a few pence of currency movement. It must have a budget and alarms, because a bug in pricing could otherwise make us absorb large losses silently.
Telling the user. A good message says what changed and why: "The fare at £389 just sold out. The next available fare on the same flights is £431. Continue or see other flights?" Offering two or three alternatives from the cached results (with fresh prices) keeps the user in the funnel.
Reducing changes at the source.
- Shorter TTLs on volatile markets (deep dive 3).
- Price confidence in ranking: offers whose class shows only 1 seat left are risky; re-price them before showing them at the top, or show a "few seats left" label.
- Re-price the top few results in the background as soon as the result page loads, before the user clicks.
- Feed every disagreement back into the caches.
Price locks. Some OTAs and airlines sell a fee-based price freeze: the user pays a small amount to keep a fare for a few days. Under the hood this is either a real hold (a PNR with a long ticketing time limit, where the fare allows it) or a financial product: we promise to pay the difference if the price rises, and we price the fee from the volatility we measured. The second needs no airline cooperation but is a bet on our price models.
SLOs for this path. Track price-change rate at offer selection and at booking, by market and provider. A typical goal is that fewer than 5–10% of offer selections see a price change and fewer than 1% of bookings see one after the passenger details are entered.
9. Revenue management: why the same seat has ten prices#
Revenue management (also called yield management) is the airline's system for deciding which booking classes to open on each flight at each moment. We do not run it, but it explains most of the behaviour our caches see.
The core idea. A seat is perishable: once the aircraft leaves, an unsold seat earns nothing. Customers differ in willingness to pay: leisure travellers book early and are price-sensitive; business travellers book late and pay more. Airlines therefore sell the same physical seat at different prices, separated by fences (advance purchase, minimum stay, refundability), and control how many seats each price may take. The Wikipedia article on yield management dates the competitive power of this to 1985: on 17 January 1985 American Airlines launched "Ultimate Super Saver" fares, using its inventory system to match the low-cost carrier People Express on a limited number of seats while keeping higher fares for the rest; the head of People Express, Donald Burr, is quoted there describing how the airline went from years of profit to losing $50 million a month once those fares arrived.
Littlewood's rule (two classes). Suppose a flight has seats left, a high fare R1 and a low fare R2, and high-fare demand D1 that arrives later and is uncertain. Should we sell one more seat at the low fare now? Only if the low fare is at least the expected value of keeping the seat for a possible high-fare customer:
accept a low-fare request iff R2 >= R1 * P(D1 > y)
where y = seats currently protected for the high fare
=> protection level y1 solves P(D1 > y1) = R2 / R1This rule is usually credited to Ken Littlewood's 1972 work at BOAC (British Airways' predecessor). Worked example: R1 = £500, R2 = £150, and high-fare demand is roughly normal with mean 40 and standard deviation 12. Then P(D1 > y1) = 0.3, so y1 is the 70th percentile of demand: 40 + 0.52 × 12 ≈ 46 seats. The airline protects 46 seats for the high fare; once the remaining seats fall to 46, the low class closes, even if nobody has asked for the high fare yet.
Nesting. Protection levels are nested: the high class can always use seats from below, and the low class sees only the seats above the protection level. This is why availability displays show more seats in higher classes, and why one booking in a low class reduces the count in every class above it.
Many classes: EMSR. With more than two classes, exact optimisation is hard. The EMSRa and EMSRb heuristics (Expected Marginal Seat Revenue), developed by Peter Belobaba in his 1987 MIT doctoral work, extend Littlewood's rule. EMSRa computes pairwise protection levels and adds them; EMSRb merges all higher classes into one virtual class with a demand-weighted average fare, which usually performs better. Neither is exact, and modern systems also use Monte Carlo simulation and optimisation over forecasts.
Bid prices and network control. On a connecting network, a seat on London–Frankfurt may be worth more sold as part of a London–Singapore journey than as a short local trip. Network revenue management computes a bid price per flight leg (the minimum revenue the airline should accept for one more seat on it), often from linear programming or the dynamic programming formulations popularised by Kalyan Talluri and Garrett van Ryzin. An itinerary is accepted if its fare is at least the sum of the bid prices of its legs. This is the reason behind origin and destination availability (deep dive 4): the same seat is open for one journey and closed for another.
Why this matters to our design.
- Availability changes without bookings. Demand forecasts are re-run continuously; classes open and close as forecasts move. A cache hit can be wrong even if nobody bought anything.
- Most change happens close to departure and on full flights. De Marcken notes that sophisticated revenue management mainly increases profits when planes fly near capacity, which is also when our cache misses hurt most. Set TTLs accordingly.
- Prices go both ways. A class that closed can reopen after a cancellation or a forecast change, which is why price trackers and alerts are worth building (see the separate price tracker case study).
- O&D control limits caching. If availability depends on the whole journey, a per-flight availability cache is an approximation. Some providers expose journey-level availability calls; cache their answers per journey, with shorter TTLs.
Dynamic pricing beyond buckets. With NDC, airlines can price offers continuously rather than from a fixed set of filed fares and classes ("continuous pricing"), and personalise bundles. That makes our filed-fare shopping engine less able to predict prices, and pushes more traffic to live calls and to provider caches.
10. NDC offers and orders, bundles and ancillaries#
Why NDC exists. The GDS channel is built on EDIFACT messages designed before the web. It can express flights, booking classes and fares, but not rich products: a fare bundle that includes a bag, priority boarding and Wi-Fi, a seat with extra legroom shown with a photo, a personalised discount. IATA launched the New Distribution Capability in 2012 as an XML messaging standard to replace EDIFACT in the agency channel, so that travel agents could offer the same choices as the airline's own website.
Offers and orders instead of fares and PNRs.
| Classic GDS model | NDC model |
|---|---|
| Search returns flights plus fares that we price | Airline returns offers: a complete product at a price, with an id and an expiry |
| PNR for the booking, e-ticket for the flights, EMD for extras | Order: one record for everything bought, which the airline manages |
| We build the itinerary and price it from filed data | The airline builds and prices; we choose |
| Changes through PNR edits and ticket exchanges | Order change requests; the airline reprices |
For our system this means:
- NDC offers cannot be cached and recomputed by our engine. They are the airline's live answer, often personalised by point of sale and customer. We cache them only as "last seen price" with short TTLs and always reprice by offer id.
- The adapter has to manage offer ids and their expiries, which are typically short (minutes to an hour).
- Orders are a different object from PNRs. Our booking model stores a generic provider reference (
pnr_refswith provider type), not a GDS-specific locator, so both fit.
The commercial fight. Airlines want more sales through channels they control, because GDS fees are charged per booking. The Wikipedia article on GDSs reports that in June 2015 the Lufthansa Group added a €16 charge on bookings made through external GDSs, saying those systems cost several times more than its own, and that other large airline groups said they were watching the move. For an OTA this creates a routing decision per market: the same flights may be cheaper through NDC than through the GDS, but the NDC connection may lack servicing features. The orchestrator compares offers across channels and chooses per booking.
Ancillaries. Bags, seats, meals, lounge access, flexibility upgrades and insurance are a large part of airline and OTA revenue. Design points:
- Discovery: after an offer is selected, fetch the ancillary catalogue for that offer (seat map, bag options) in parallel with the re-price.
- Pricing: ancillaries are priced per passenger and segment; a bag on a two-flight trip may be priced once for the journey or per flight.
- Fulfilment: GDS ancillaries are issued as EMDs linked to the ticket; NDC ancillaries are items in the order.
- Failure handling: if the ticket is issued but the seat EMD fails, the trip is still valid. Retry the extra separately and refund it if it cannot be issued; never cancel the flight booking because a seat failed.
Branded fares. Many airlines sell "Light", "Standard" and "Flex" brands on the same flight, each a bundle of a fare with rules and included items. The search result must group them so users can compare, which means the normaliser maps each provider's brand names to a common feature model (bag included, changeable, refundable, seat selection).
11. Scaling, provider resilience and multi-region#
The tiers scale differently.
| Tier | Load at peak | Scaling approach |
|---|---|---|
| Search orchestrator | 20,000 searches/s | Stateless, horizontal; most time spent waiting on I/O, so async I/O and high concurrency per node |
| Shopping engine | A few thousand cache-miss searches/s, CPU heavy | Stateless nodes each holding fares, rules and schedules in memory (tens of GB); scale by cores |
| Availability cache | 20 M lookups/s | Replicated in memory per region; local reads; updates streamed through Kafka |
| Search result cache | 20,000 reads/s plus writes | Redis cluster sharded by key (see Distributed Caching with Redis and Memcached) |
| Provider adapters | Bounded by provider quotas | Connection pools per provider; quotas enforced centrally |
| Booking, payment, ticketing | Up to 200 bookings/s | Modest; correctness first; sharded PostgreSQL |
The striking thing is that our own compute is cheap compared with what providers charge and how slowly they answer. Most scaling work is about protecting providers and quotas, not about our servers.
Protecting providers and ourselves.
- Quotas as a shared budget. Each provider allows a certain number of transactions per second per connection and per office. A central token-bucket service (backed by Redis) hands out permits to adapters across all regions. Search traffic can use up to, say, 80% of a provider's quota; 20% is reserved for re-pricing and booking, which earn money. See Rate Limiting and Throttling.
- Bulkheads. Separate pools for search, pricing and booking calls to the same provider, so a search flood cannot starve bookings.
- Timeouts and circuit breakers per provider and per operation. When a GDS slows down, its breaker opens for search first (we can live without it), while booking calls continue with longer timeouts.
- Retries only where safe. Searches and price checks can be retried once on another connection. Sell and ticket calls are retried only with idempotency or after the recovery lookup (deep dive 5).
- Load shedding. Under extreme load, drop live calls for low-value searches (anonymous users, far-future dates) and serve from caches and the shopping engine.
Session-based providers. Some GDS interfaces are stateful: a booking needs a session in which segments are sold, names added and the transaction ended. Sessions are a scarce resource, limited per office. The adapter keeps a pool of sessions, assigns one to a booking for its duration, and must always close or end sessions, even on errors, or the pool drains.
Multi-region. Travellers search from everywhere, and latency to providers matters more than latency to users: a GDS data centre may be in one region, and a request from a distant region adds a round trip per call.
- Run search in several regions near users, with replicated caches and shopping engine data.
- Place provider adapters near each provider's endpoints, reached from all regions.
- Keep bookings in a home region per booking (by the user's region) with synchronous replication within the region and asynchronous replication to another region for disaster recovery. Bookings are low volume and must be strongly consistent, so a single writer per booking is simplest. See Multi-Region and Global Data.
- On a regional failure, searches move to other regions immediately; booking writes fail over after the replica is promoted. Bookings in flight during the failover are resolved by the recovery job using provider lookups.
Data loading for the shopping engine. Fares and rules arrive in bulk several times a day; schedules daily. A pipeline parses them, builds compact indexes and publishes a versioned snapshot to object storage. Engine nodes load the new snapshot in the background and switch atomically. A bad snapshot (a parsing bug that drops a carrier's fares) is caught by validation checks (counts per carrier and market compared with the previous version) before it is published. Old snapshots are kept so that a bad load can be rolled back in minutes.
Observability. The key dashboards:
- Search latency to first result and to completion, per region.
- Provider latency, error rate, timeouts and quota use per provider and operation.
- Cache hit rate and price accuracy by market group and days to departure.
- Booking funnel: offer selected, priced, held, paid, ticketed, with drop-off and error reasons.
- Ticketing failures, unknown states, deadline expiries.
- Provider cost per booking.
See Observability: Logs, Metrics and Traces. Keeping every provider request and response (with card data and personal data masked) is essential: disputes with airlines and providers are settled by those logs.
12. Fare sales and the virtual waiting room#
When an airline launches a big sale, or a pricing mistake (a "mistake fare") spreads on social media, traffic on a few markets can rise tenfold in minutes. Two different problems appear: search load and booking contention.
Search load. Everyone searches the same few markets and dates. That is the best case for caching:
- Coalesce identical in-flight searches so one provider call serves thousands of users.
- Shorten TTLs for these markets (volatility is high) but keep coalescing, so freshness costs one call per few seconds per key, not one per user.
- Pre-warm the expected markets if the airline announces the sale.
Booking contention. The cheap seats are few. Thousands of users click "book" on the same fare in the same minute. We cannot lock the airline's inventory, so most will see "price changed" or "sold out" at re-price. That is correct, but the burst of re-price and sell calls can exceed the provider's quota and get our office throttled or blocked, harming every other customer.
The virtual waiting room. For events like this, we can put a queue in front of the booking path, an idea borrowed from ticketing sites selling concerts:
- An operator (or an automatic trigger on traffic for a market) turns on the waiting room for specific markets or for the whole booking path.
- Users who want to book join a queue, stored as a Redis sorted set ordered by arrival time.
- The client holds an SSE or WebSocket connection and sees their position and an estimated wait, computed from the current admission rate.
- An admission job lets in users at a rate the provider quota can support (for example, 50 per second), adding them to an
admitted:{market}set with a TTL of 10 minutes. - The pricing and booking services check that set; requests from users not admitted are rejected with a friendly message.
- When the cheap fare sells out, the waiting room tells everyone still queued, rather than letting them wait for nothing.
This turns an uncontrolled stampede into a steady stream the providers can handle, and gives users a fair, first-come order. It is a heavy tool; most of the year it is off. See Pattern: Dealing with Contention and Pattern: Pushing Realtime Updates.
Mistake fares. When an airline files a wrong fare (a missing digit), it may later refuse to honour tickets. Our system should flag fares far below the market's normal range, slow down or pause automatic ticketing for them, and make the terms clear to users, because cancelling many tickets later is far more damaging than a short pause.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| A GDS slows down or fails | Searches slow, results incomplete, bookings fail | Per-provider timeouts and breakers; partial results; route bookings to another channel where possible |
| Provider quota exhausted | Throttling or account block, all users affected | Central quota service, reserved share for booking, coalescing, load shedding |
| Stale cache shows wrong prices | Price changes at checkout, lost conversions, complaints | TTL by days to departure and volatility, feedback from re-prices, background re-pricing of top results |
| Cache cluster down | Every search hits providers, cost explodes | Circuit breaker on cache, degraded mode using the shopping engine, replicas |
| Hot market during a fare sale | Stampede on the same key and provider | Request coalescing, serve stale while revalidating, waiting room |
| Timeout while creating a PNR | Unknown booking, risk of duplicates | Unknown state, recovery lookup by name and flight, client references |
| Ticketing fails after payment authorised | Customer charged nothing but has no ticket; seats at risk | Void authorisation, retry before deadline, alert operations |
| Missed ticketing time limit | Airline cancels seats | Durable timers well before deadline, sweeper on indexed held bookings |
| Bad fare or schedule load | Engine shows wrong or missing flights | Snapshot validation, versioned rollback |
| Schedule change not processed | Customer misses a changed flight | Queue reader monitoring, alerts on queue depth, automatic customer notification |
| Fraudulent card bookings | Chargebacks, airline debit memos | Fraud scoring before ticketing, 3-D Secure, review queue |
| Regional outage | Searches and bookings in that region fail | Multi-region search, booking failover with recovery job |
What Interviewers Expect#
Mid-level. Clarifies that the platform sells other companies' seats. Draws search, booking and payment services, with a cache in front of provider calls, and explains why searches must not all go to the airline. Knows that a booking needs a live price check and handles double submits with an idempotency key. Gives rough numbers for searches and bookings and notes the large look-to-book ratio.
Senior. Explains the fan-out to several providers with per-provider timeouts and partial streaming results. Designs cache keys and TTLs tied to days to departure, and measures price accuracy. Models the booking as a state machine with holds as PNRs and ticketing deadlines, orders authorisation, ticketing and capture correctly, and handles the unknown state after a timeout. Discusses provider quotas, circuit breakers and the price-change experience.
Staff and above. Frames the business trade-off between freshness, provider cost and conversion, and sets SLOs for each. Explains why flight pricing is not shortest path (fare components, priceable units, rule dependencies) and when to build an in-house shopping engine. Understands booking classes, nesting, O&D control and revenue management well enough to explain cache behaviour. Plans for NDC alongside GDS, multi-provider sagas, settlement and reconciliation, multi-region bookings, and fare-sale surges with a waiting room, and knows the operational side: snapshot validation, provider logs and disruption handling.
Deep Dive: sizing every tierShow
The capacity section gave the load. Here it becomes machines. The numbers are rough, but the reasoning is what an interviewer wants to see.
Search orchestrators. 20,000 searches per second at peak, each open for up to 5 seconds while providers answer and results stream: about 100,000 searches in flight. An async I/O node can hold around 5,000 open searches comfortably (each one a few in-flight calls and some buffered results), so about 20 nodes, doubled for headroom and zones: 40 nodes.
Search result cache. Suppose 50% of searches hit. Merged results compress to about 100 KB each. With 10 million distinct live keys, that is 1 TB. At 128 GB of usable memory per node, 8 primaries plus replicas gives 16–20 Redis nodes. Throughput is small for Redis (20,000 reads and 10,000 writes per second), but bandwidth is not: 20,000 × 100 KB = 2 GB/s, spread across the cluster, so keep values compressed and send only the first page of results on the first read.
Shopping engine. The 10,000 misses per second each run the engine. If a search takes on average 1 CPU-second (many take far less on simple markets, a few take much more), that is 10,000 cores: about 300 nodes of 32 cores. Each node holds fares, rules and schedules in memory (say 40–80 GB) plus its own copy of the availability cache. This is the biggest compute cost in the system, and it is why the hit rate matters so much: every extra 10 points of hit rate saves about 60 nodes.
Availability cache. 20 million lookups per second would be a lot for a network cache, but the whole availability table is small (under 1 GB as estimated in the capacity section). So it lives in-process in every engine node, as a compact hash table, updated by a Kafka stream of availability answers. Each lookup is a memory read of tens of nanoseconds; no network at all. The Kafka stream is modest: perhaps 50,000 updates per second at 100 bytes, 5 MB/s.
Provider adapters. Say 40% of misses also go live, to 3 providers each: 10,000 × 0.4 × 3 = 12,000 provider calls per second for search, plus about 600 per second for pricing and booking (200 bookings per second at a sale peak, each with a few calls). With 2-second average latency, that is about 25,000 concurrent provider calls. At 2,000 concurrent calls per async node, about 13 nodes, doubled: 25–30 adapter nodes, grouped by provider. In practice the limit is not our nodes but the provider quotas, which is why live calls are rationed.
Bookings database. 200 bookings per second at peak, each creating about 10 row writes over its life (booking, PNR references, passengers, events, payment, tickets): 2,000 writes per second. One PostgreSQL primary handles this, with a hot standby in the same region and an async replica in another. Data grows about 7 GB a day (PNR data plus tickets), 2.5 TB a year; partition by month and archive flown bookings older than two years. Shard by booking id only when growth demands it.
Ledger. About 10 entries per booking, 5 million entries a day, 1 KB each with metadata: 5 GB a day. A separate database with its own backups and strict access.
Kafka. Search summaries (20,000 per second at 2 KB) plus booking events and availability updates: about 50 MB/s in. With replication factor 3, 6–9 brokers, retention of 3 days.
Provider logs. Every request and response, compressed, about 1 TB a day, in object storage with an index by search id and booking id. Keep 90 days for search logs and 7 years for booking logs (financial and dispute needs).
Summary.
| Tier | Size at peak |
|---|---|
| Search orchestrators | about 40 nodes |
| Search result cache | 16–20 Redis nodes, 1 TB |
| Shopping engine | about 300 nodes of 32 cores |
| Availability cache | in-process, under 1 GB per node |
| Provider adapters | 25–30 nodes, bounded by quotas |
| Bookings DB | 1 primary, 2 replicas, 2.5 TB a year |
| Kafka | 6–9 brokers |
| Logs | 1 TB a day in object storage |
The shape is clear: reads and pricing dominate, and the transactional core is small. Optimise the hit rate before buying servers.
Deep Dive: what the public record tells usShow
A few public facts help calibrate the design and show it matches the industry. Only facts we are confident about are listed.
The first reservation systems. According to the Wikipedia article on airline reservation systems, American Airlines worked with Teleregister on the electromechanical Reservisor in 1946 and an improved Magnetronic Reservisor in 1952. Trans-Canada Air Lines built ReserVec with Ferranti, in service from 1961 and fully running by early 1963. United Airlines used a 1962 Teleregister system designed by Evelyn Berezin, with about one-second response times. The best known, SABRE, was built by American Airlines and IBM and went live in 1964; it cut the time to process a booking from about 90 minutes to seconds. American opened SABRE to travel agents in 1976. After US airline deregulation (the Airline Deregulation Act of 1978), fares and routes changed far more often, which made computerised systems essential.
GDSs today. The same article lists the major global distribution systems around 2009 as Amadeus, Sabre and Travelport (which ran the Apollo, Galileo and Worldspan systems). SITA Reservations hosted more than 100 airlines. Messages between airlines travel over SITA's network, as interactive "Type A" (EDIFACT) messages or older teletype "Type B" messages. Fares are distributed to these systems by ATPCO and SITA.
Electronic tickets. E-tickets appeared in the mid-1990s. IATA set June 2008 as the deadline for 100% electronic ticketing through its settlement plan, and reported industry savings of about US$3 billion from the switch.
ITA Software and Google Flights. ITA was founded in Cambridge, Massachusetts in 1996 by Jeremy Wertheimer, a computer scientist from the MIT AI Lab, with his partner Richard Aiken. Its QPX engine powered sites such as Orbitz and Kayak and several airlines' own websites; it was written largely in Common Lisp. Google announced the purchase in July 2010 for about $700 million; the US Department of Justice approved it on 8 April 2011, and ITA's technology underlies Google Flights. Google offered a simplified public API, QPX Express, from 2013 and ended it on 10 April 2018. Carl de Marcken's 2003 notes for ITA Software, cited throughout this page, explain from the inside why pricing is so hard.
NDC and distribution costs. IATA launched NDC in 2012. Lufthansa Group's €16 GDS surcharge in June 2015 marked the start of airlines actively steering bookings away from GDSs.
Overbooking and delays. US data for 2018 shows 351,904 passengers denied boarding on the 17 largest airlines, about 3% of them involuntarily. The US FAA counts a flight as delayed when it is 15 minutes late and has estimated the cost of delays to the US economy at about $22 billion a year.
What this tells us. The industry runs on systems designed in the 1960s, bridged by GDSs to the web, and is slowly moving to offer-and-order models. An OTA must speak both worlds for years to come, which is why the adapter layer and a provider-neutral booking model are central to the design.
Deep Dive: a 45-minute interview plan and follow-up questionsShow
Minutes 0–5: clarify. Are we an airline or an OTA? (OTA.) Which providers (GDS, NDC, low-cost carriers)? Scale: 500K bookings and 500M searches a day. Holds, payment model, ancillaries, changes? What matters most: correct bookings, fast search, honest prices, provider cost.
Minutes 5–10: estimate. About 6 bookings per second average, 200 at sale peaks. 20,000 searches per second at peak. Look-to-book near 1,000:1. Provider calls are slow (seconds) and cost money, so caching is required, not optional.
Minutes 10–25: high-level design. Search orchestrator with fan-out and streaming, provider adapters, caches and an optional shopping engine. Pricing service for live re-price. Booking service with PNR holds and the state machine. Payment and ticketing. Servicing for changes. Kafka for events.
Minutes 25–40: deep dives. Pick two or three, guided by the interviewer:
- Caching and freshness: keys, TTLs by days to departure, price accuracy, stampedes.
- Booking correctness: holds as PNRs, ticketing deadlines, unknown state, idempotency.
- Payment ordering: authorise, ticket, capture; voids; reconciliation.
- Provider resilience: timeouts, breakers, quotas.
Minutes 40–45: wrap up. Failure modes table, what to monitor, what you would build next (price alerts, NDC, virtual interlining).
Follow-up questions to prepare for.
- "Why not just call the airline for every search?" Cost, latency and quotas; show the look-to-book numbers.
- "How do you prevent two users booking the last seat?" We cannot; the airline decides at sell time. We handle the loser gracefully with a re-price and alternatives.
- "What if the airline times out while creating the PNR?" Unknown state, recovery lookup, client references, no blind retry.
- "How fresh are your prices?" Measure price accuracy; TTLs by days to departure and volatility; feedback loop.
- "What happens if ticketing fails after payment?" Authorisation only, so void it; retry ticketing before the deadline; alert.
- "How do you find the cheapest fare?" Explain fare components and priceable units; it is not shortest path; engines prune heavily.
- "How would you support price alerts?" Use the search result stream and scheduled searches for watched routes; that is its own system (the separate price tracker case study).
- "How do you handle a fare sale?" Coalescing, short TTLs, quota protection, waiting room.
- "Why do airlines overbook, and what does it mean for you?" Binomial reasoning, volunteers first, regulations, servicing flows.
- "How do you store PNR data safely?" Minimise, encrypt, restrict access, retention limits (see the privacy deep dive).
Deep Dive: one booking end to end, with timingsShow
Follow one traveller, Sam, who books a return trip from London to New York, 12–19 June, for two adults, paying by card. They use the mobile app. Times are realistic targets.
t = 0 ms: search. The app sends POST /v1/flight-searches. The gateway authenticates Sam (logged in), checks rate limits and forwards to the nearest region's orchestrator. The orchestrator normalises "London" to six airports and "New York" to JFK, EWR and LGA, builds the key, and checks the cache.
t = 15 ms: partial hit. The cache has a 40-minute-old result for this key. Departure is 6 weeks away, so the TTL is 2 hours and the entry is valid. The orchestrator returns searchId and immediately streams the cached results, labelled "updated 40 minutes ago". Because the route is popular, it also fires a background refresh to two providers whose quotas are healthy.
t = 120 ms: first screen. The app shows 250 itineraries, sorted by the "Best" score. The top three offers are re-priced in the background, since one of them shows only 2 seats left in its class.
t = 2.1 s: refresh arrives. The NDC answer from one airline has a new bundle 12 pounds cheaper than the GDS price for the same flights. The aggregator dedupes by operating flight numbers, keeps the NDC offer and streams an update. The app quietly updates one card.
t = 40 s: Sam picks an offer. They choose a nonstop outbound and a one-stop return on the same airline, Standard brand, £806 for two. The app calls POST /v1/offers/{id}/price and, in parallel, fetches the seat map and bag options.
t = 41.3 s: priced. The provider confirms availability and a total of £806.40 (a tax rounding difference of 40p). This is within the tolerance, so the app shows £806.40 without a "price changed" warning. The priced offer expires in 15 minutes.
t = 2 min 30 s: passenger details. Sam enters both names exactly as in the passports, dates of birth and contacts, and picks two seats (£25 each).
t = 2 min 31 s: hold. POST /v1/bookings with an idempotency key. The booking service writes creating, the adapter opens a provider session, sells four segments, adds names, contacts, SSRs for passport data, and ends the transaction. The airline returns a record locator with all segments HK and a ticketing deadline of 24 hours. The booking becomes held. Elapsed: 1.8 seconds.
t = 3 min 10 s: payment. Sam pays £856.40 (fare plus seats). The payment service checks acceptedTotal, runs a fraud score (low risk: known device, card matches name and country), and authorises the card with 3-D Secure, which Sam approves in their banking app.
t = 3 min 25 s: ticketing. The ticketing service asks the provider to store the fare and issue two tickets. The fare re-check matches. Two 13-digit ticket numbers return in 2.5 seconds. Then the seat EMDs are issued; one fails with a provider error.
t = 3 min 28 s: partial success. The flight tickets are valid, so the booking becomes ticketed and the payment of £806.40 is captured. The seat fee for the failed EMD is not captured. A retry job re-issues the EMD 30 seconds later, succeeds, and captures the remaining £25. Sam sees "Booking confirmed" at once and gets an email with both locators (the GDS one and the airline's), tickets and seats.
Later that day. Events from Kafka update the price-accuracy metrics (the cached price was within 1%), the cache for this market, Sam's trip page, and the ledger.
Three weeks later: schedule change. The airline moves the return flight 1 hour 40 minutes later. The PNR appears on the schedule-change queue. The servicing service checks the connection: still 2 hours 15 minutes, above the minimum. It accepts the change, the segments return to confirmed, and Sam gets a push notification with the new time.
What made this smooth: cache plus background refresh for search speed, re-price at selection so the price never jumped at payment, authorise before ticketing so a failure costs nothing, and treating ancillaries as separable from the core ticket.
Deep Dive: schedule changes and disruptionsShow
Schedule changes are the day-to-day reality of airline servicing. For a large OTA, a few percent of all future bookings are touched by some change each week, and during storms or strikes the volume spikes by orders of magnitude.
Kinds of change.
| Change | Example | Typical handling |
|---|---|---|
| Minor time change | Departure 10 minutes earlier | Accept automatically, notify |
| Major time change | 3 hours later, or the next day | Notify; offer accept, rebook or refund |
| Broken connection | Inbound now arrives after the onward flight leaves, or below minimum connecting time | Rebook proactively; refund if no option |
| Flight number or aircraft change | Same time, new number | Accept; update tickets if needed |
| Cancellation | Flight removed | Rebook on the airline's proposed alternative or another flight; refund on request |
| Same-day disruption | Delay, diversion, cancellation on the day | Real-time notification; airline usually rebooks; we mirror the new itinerary |
Rules engine. Whether a change is minor depends on thresholds (often per airline: some allow automatic acceptance under 30 or 60 minutes), the minimum connecting time at the connecting airport (published per airport and per type of connection, domestic or international), and the customer's preferences. Encode these as data, not code.
Re-issuing tickets. Some changes require the ticket to be revalidated or reissued to match the new flights. Involuntary changes usually waive change fees under the airline's policy, but the reissue still needs a call to the provider and creates new coupons.
Disruption at scale. When a hub closes for weather, thousands of bookings change within an hour. Design for it:
- The queue reader and notification receivers scale out, and the servicing service processes changes through a work queue partitioned by booking id so each booking is handled in order.
- Notifications are batched and rate-limited per user, so a customer does not get ten messages as the airline revises the schedule repeatedly. Debounce: wait a few minutes for the airline's changes to settle before suggesting rebooking.
- Customer contact volume spikes; self-service rebooking and refund flows in the app keep call centres from being overwhelmed.
- Compensation eligibility (EU 261 where it applies) is computed automatically from the delay and the flight's coverage.
Keeping our record in sync. The airline's PNR is the truth. After any change, the servicing service retrieves the full PNR and reconciles it with our booking (segments, statuses, tickets), rather than applying deltas blindly. A nightly job compares a sample of bookings departing in the next week with the provider's records and flags differences.
Deep Dive: protecting PNR and passenger dataShow
PNRs carry a lot of personal data. Beyond names and itineraries they may hold dates of birth, passport numbers, home addresses, phone numbers, email, payment details, special service requests that reveal health needs or religion (meal codes), and who travels with whom. Governments in many countries require airlines to send passenger data before flights, so passport details are increasingly mandatory.
The Wikipedia article on PNRs notes two concerns raised by privacy groups: cancelled and completed bookings are not erased but moved to archival storage that can be kept indefinitely, and on many sites a PNR can be retrieved with little more than the record locator and the surname printed on a ticket or boarding pass.
Design responses.
- Minimise. Collect passport data only when the airline or route requires it, and send it only to that airline.
- Separate. Store identity documents and payment tokens in separate, restricted stores, referenced by id from the booking. Card numbers never touch the booking database; a PCI-scoped vault holds them and injects them into provider calls.
- Encrypt. Field-level encryption for documents and contact details, with keys managed per region.
- Restrict access. Customer service agents see what they need for the task; access is logged and reviewed.
- Strong retrieval. "Manage my booking" needs the locator and surname plus a second factor (a code sent to the booking email) before showing sensitive fields or allowing changes.
- Retention. Keep bookings for the legal and financial periods required (often several years for accounting), then delete or anonymise personal fields while keeping the financial record. Provider logs must be masked before storage.
- Data residency. Some countries require local storage of citizens' personal data; the home-region design for bookings helps meet this.
- Subject requests. Support export and deletion on request where the law gives that right, with a clear exception for data we must keep for legal reasons.
Deep Dive: testing and operating against providersShow
Most production incidents in travel come not from our code but from the boundary with providers: changed message formats, unannounced behaviour, slow certification environments, and edge cases that occur only with real airlines.
Test environments. GDSs and airlines provide test systems, but they are slower, less available and contain fake inventory that does not behave like production. So:
- Contract tests for each adapter, recorded from real (masked) provider messages, run on every change.
- A provider simulator that replays recorded responses with configurable latency, errors and timeouts, used for load tests and chaos tests. It can simulate a provider timing out after the sell succeeded, which is exactly the case we must handle correctly.
- Canary bookings. Some teams make small real bookings on refundable fares in production and void them within the allowed window, to check the full flow end to end after deployments. This costs a little and catches problems test systems never show.
Deployments. Adapters change when providers change. Deploy them separately from the rest, behind feature flags per provider and market, and roll out gradually (see CI/CD and Deployment Strategies). A bad adapter release should be switched off for one provider without touching others.
Runbooks for the common incidents.
- Provider degradation: breakers open automatically; operators reduce search traffic to the provider and inform the business.
- Unknown bookings piling up: check recovery job health, provider retrieve calls, and alert if the count exceeds a threshold.
- Ticketing backlog near deadlines: prioritise by deadline; if a provider's ticketing is down, ask for deadline extensions or cancel and refund early.
- Price accuracy drop: often a fare load problem or a provider change; compare the latest snapshot and roll back.
- Fraud wave: tighten scores for affected routes and payment methods, pause automatic ticketing for risky bookings.
Cost reviews. Provider bills are a top cost. A weekly report of provider transactions per booking by market and channel finds waste quickly: a misconfigured routing table that sends domestic searches to an expensive GDS can cost more than all the servers.
Deep Dive: inside a low-fare shopping engineShow
Deep dive 2 explained why exact search is hopeless. Here is how an engine actually organises the work, at a level you could sketch in an interview.
Data held in memory per node.
| Data | Shape | Size (rough) |
|---|---|---|
| Schedules | Per (origin airport, date): departures with times, carrier, flight number, operating carrier, aircraft | A few GB for a year ahead |
| Connection rules | Minimum connecting times per airport and connection type | MB |
| Fares | Per (market, carrier): list of fares with basis code, amount, currency, rule references | Tens of GB |
| Rules | Rule records referenced by fares (dates, days, stay, advance purchase, combinability) | Tens of GB, heavily shared |
| Availability | Per (flight, date, class): seat count and freshness | Under 1 GB |
| Taxes and fees | Per airport, country and passenger type | MB |
Step 1: flight graph per direction. For London to New York on 12 June, the engine expands departures from each London airport, adds connections at hubs within the allowed time window, and stops at a limit on stops and on total duration relative to the fastest. Instead of a list of paths, it keeps a layered graph: nodes are (airport, arrival time) and edges are flights. Shared prefixes and suffixes are stored once. Thousands of itineraries may share the same first flight to a hub.
Step 2: candidate fare components. For each sequence of flights on one carrier that could form a fare component (a single flight, or two flights through a hub), look up fares for that market and carrier. Apply the cheap, local rule checks first: travel date and day of week, booking class availability from the cache, passenger type. Fares that fail are dropped early, which removes most of the work.
Step 3: priceable units. Combine fare components into one-way, round-trip, open-jaw or circle-trip units, checking rules that span components: minimum and maximum stay (the outbound and return dates), Saturday night rules, advance purchase measured from today, and combinability (which fares may share a ticket).
Step 4: search for the cheapest few. With the graph and the priced components, the engine finds low-cost covers of each itinerary by dynamic programming over the shared graph: for each node, keep the best few partial prices reaching it, with enough state to check the remaining rules. Branch-and-bound prunes partial solutions that already cost more than the current kth best.
Step 5: taxes, fees and diversity. Add taxes per segment and airport, carrier-imposed surcharges, and our fees. Then pick a diverse answer set: the cheapest overall, the cheapest per airline, per number of stops and per time of day, so the list is not 50 copies of the same flights with tiny fare differences.
A tiny illustration of the state problem.
// Simplified: why the price of a leg depends on the whole ticket
type Fare = { basis: string; amount: number; roundTripOnly: boolean; minStayDays: number };
function priceRoundTrip(out: Fare, ret: Fare, stayDays: number): number | null {
if (out.basis === ret.basis && out.roundTripOnly) {
// round-trip fare: valid only as a pair, rules checked on the pair
if (stayDays < out.minStayDays) return null;
return out.amount + ret.amount; // often half of a round-trip price each way
}
if (out.roundTripOnly || ret.roundTripOnly) return null; // cannot mix
return out.amount + ret.amount; // two one-way fares
}
// The same outbound flight costs 150 inside a valid round trip,
// or 420 as a one-way fare, depending on the return chosen and the stay length.Throughput tricks.
- Precomputed fare indexes keyed by market and carrier, with rules compiled into fast predicates when the snapshot loads.
- Memoisation within a search: the same fare component check is reused across many itineraries.
- Shared work across similar searches: a search for 12–19 June and one for 12–20 June share all outbound work.
- Time budgets: the engine returns the best found within its budget (for example, 500 ms), which keeps tail latency bounded at a small cost in optimality.
Accuracy against providers. An in-house engine prices from filed data. It cannot see private negotiated fares, NDC-only offers, or airline-specific logic not expressed in filings. So it is always paired with live re-pricing, and its accuracy is measured per carrier. Carriers with poor accuracy get more live calls and shorter TTLs.
Deep Dive: voluntary changes, exchanges and refundsShow
After the booking, customers change their minds. These flows are fiddly because the rules come from the fare and the money moves in both directions.
Voluntary change (exchange).
- Sam asks to move the return from 19 to 21 June. We start a change search constrained to the same airline (most fares allow changes only on the validating carrier), from the same origin and destination.
- For each option, the provider (or our engine) computes: the change fee from the original fare's rules, the fare difference between the original fare and the new fare (if the new fare is cheaper, many fares give no refund of the difference), and tax differences.
- Sam picks one. We check
acceptedTotalas for a new booking, charge the additional amount, and ask the provider to exchange the ticket: the old coupons are marked exchanged and a new ticket is issued, or the ticket is reissued with the new itinerary. - Our booking moves to
changed, then back toticketedwith the new tickets.
The exchange is atomic at the provider but not with our payment. Use the same ordering: authorise the additional amount, exchange, then capture; void on failure.
Refunds.
- Fully refundable fares: refund fare and taxes, minus any fee.
- Non-refundable fares: the fare is lost, but many taxes and fees collected for airports and governments are refundable, because they are charged only when the passenger flies.
- Partial use: refunding the unused return of a used outbound requires recalculating the fare for the flown part, which may cost more than the half-price share of a round trip. Providers offer automated refund calculations for most cases; complex ones go to a manual desk.
- Airline-initiated cancellations: customers are usually entitled to a full refund, regardless of fare rules.
Who refunds whom. When the airline is the merchant, it refunds the card. When we are, we receive the refund through settlement and refund the customer, so there is a timing gap that the ledger records as a receivable from the airline. Many OTAs refund the customer before the airline pays them back, to keep satisfaction high, and carry that working capital.
Voids. Within the void window (usually the day of issue), a ticket can be voided with no fees at all. A "free cancellation within 24 hours" product often relies on this, or on the US Department of Transportation's 24-hour rule (for bookings made at least a week before departure, the airline must either hold the fare or allow free cancellation within 24 hours; check the current text of the rule before relying on details). Our system must know each fare's void and cancellation rules and the exact cut-off time zone (usually the issuing office's local time).
Credits and vouchers. Some airlines convert cancelled non-refundable tickets into credits for future travel, valid for a period and usable only on the same airline. Track them as a balance attached to the passenger and the original ticket number, with expiry reminders.
Key Takeaways#
- An OTA sells inventory it does not own. Every seat and price lives in an airline system reached through GDSs, NDC or airline APIs; our design is built around that boundary.
- Look-to-book drives the architecture. With hundreds to thousands of searches per booking, caching, an in-house shopping engine and provider routing are needed for both latency and cost.
- Search is fan-out under a deadline. Per-provider timeouts, bulkheads and circuit breakers, with results streamed as they arrive and duplicates (including codeshares) removed.
- Flight pricing is not shortest path. Fares, fare components and priceable units with rules create long-range dependencies; exact search is NP-hard or worse, so engines prune and precompute.
- Staleness is managed, not avoided. TTLs by days to departure and volatility, feedback from every re-price, background refresh of hot markets, and price accuracy as a first-class metric.
- Price live before booking and confirm at ticketing. Use signed priced offers and an
acceptedTotalcontract so users never pay more than they agreed to without being asked. - Holds are PNRs with ticketing deadlines. We cannot lock the airline's inventory; we sell segments, store the PNR, and use durable timers to ticket or release in time.
- The unknown state is the dangerous one. After a timeout, recover by looking the booking up at the provider, and use idempotency and client references instead of blind retries.
- Authorise, ticket, capture. This order makes ticketing failures cheap; reconciliation against payment and settlement reports catches the rest.
- Revenue management explains availability. Booking classes, nesting, Littlewood's rule, bid prices and O&D control are why prices change without bookings.
- Overbooking is a binomial bet with human costs. Volunteers first, regulations such as EU 261 and US 14 CFR Part 250, and our servicing flows handle the consequences.
- Protect providers like a shared resource. Central quotas, reserved capacity for booking, load shedding and a waiting room for fare sales keep one surge from harming everyone.