“Book a flight” sounds like decrementing a seat count. Then you learn how airlines actually sell seats and the floor drops out. A single Economy cabin of 180 seats is not one pool; it is a stack of nested fare-class buckets (Y, B, M, H, Q, V…) where selling a cheap V-class seat quietly eats into the availability of every more expensive class above it, and where “how many seats are available in class M” is a computed answer, not a stored integer. Thousands of flights refresh these buckets continuously as a revenue-management engine retunes them. Meanwhile the read side is brutal: booking agents, online travel agencies, metasearch crawlers, and airline.com front ends fire millions of concurrent availability queries against this inventory worldwide, at a look-to-book ratio that can exceed 1000:1. And on the write side, correctness is absolute - two agents on opposite sides of the planet must never both sell the last seat.

The core of this problem is that a tiny, nested, continuously-retuned seat inventory must be allocated with strong per-flight consistency under a storm of global concurrent reads, without ever letting reads serialize behind the writes. If you guard the inventory with a lock that reads take, the million-QPS availability path dies. If you drop the lock, you double-book. The design exists to hold those apart: strong consistency where a seat is actually sold, lock-free reads everywhere else. The weapon is optimistic concurrency with a per-flight version counter - sell by compare-and-swap, let reads run free. Let me build it properly.

Functional Requirements (FR)

In scope:

  • Availability / shopping query. Given an origin, destination, date, and passenger count, return which flights have seats, in which fare classes, at what level. This is the single highest-volume operation in the system by orders of magnitude.
  • Nested fare-class inventory. Each flight-leg cabin is divided into booking classes (RBDs - Reservation Booking Designators) with nested booking limits, so the availability of a lower class is bounded by the limits of every class above it. Selling a seat updates the shared pool, not just one bucket.
  • Create a booking (PNR). Hold seats for a passenger itinerary across one or more legs, generate a Passenger Name Record, and keep the hold until ticketing or expiry.
  • Ticket issuance. Convert a held PNR into a ticketed, paid booking; the hold becomes a firm sale.
  • Multi-leg and connecting itineraries. A booking consumes inventory on each physical leg it traverses; availability for an itinerary is the intersection of per-leg availability.
  • Inventory retuning. A revenue-management (RM) feed continuously updates booking limits and authorization levels per class as demand forecasts change. The CRS must apply these without disturbing in-flight sales.
  • Overbooking. Sell slightly beyond physical capacity per class/cabin using an authorized overbooking factor, because no-shows are predictable.
  • Cancel / change. Release held or sold seats back to inventory, which immediately raises availability for affected classes.

Explicitly out of scope (name it so you own the scope):

  • Pricing and fare construction. Fare rules, taxes, currency, and fare-family logic are a separate pricing/fares engine I call; the CRS stores the booked fare basis and class, not the pricing math.
  • Revenue management forecasting. The RM optimizer that decides what the booking limits should be is upstream; the CRS consumes its limit updates and enforces them. I design enforcement, not forecasting.
  • Payment gateway internals. Card/UPI/agency-settlement rails are external async services with callbacks.
  • Departure control, check-in, seat maps. Physical seat assignment (12A vs 14C), boarding, and weight-and-balance are a Departure Control System; the CRS tracks class inventory, not the cabin map.
  • Loyalty, ancillaries, GDS billing. Treated as adjacent services consuming CRS events.

The decision that drives everything: inventory is not a flat per-class counter; it is one versioned document per (flight, date, leg, cabin) holding the nested limits and the booked vector, mutated only by compare-and-swap on its version. Nesting, oversell prevention, and global read scale all reduce to “compute availability as a pure function of that document, and change the document only by CAS,” and the rest of the system exists to serve that document to the world cheaply and keep its writes correct.

Non-Functional Requirements (NFR)

  • Scale: a large carrier or hosted CRS runs ~5,000-10,000 flights/day, each flight open for sale ~360 days ahead, with ~4-15 booking classes per cabin and 1-3 cabins. That is roughly 10-50 million live inventory keys (flight-date-leg-cabin). Bookings land at ~1-2 million passengers/day. Availability queries dwarf everything: a conservative look-to-book of ~500:1 puts shopping at ~500M-1B queries/day, averaging ~10-15K QPS but spiking to hundreds of thousands to ~1M QPS at the caching layer during shopping peaks and metasearch crawls.
  • Latency: an availability query must return in under ~100-200ms (it sits inside a shopping response that fans out across dates and routes). A booking/hold commit should return in under ~500ms-1s. Ticketing can be a touch slower.
  • Availability: 99.95%+ for shopping (revenue flows through it); the sell path must stay correct even when degraded. Shopping may serve slightly stale data; the sell commit may not.
  • Consistency: the sell path needs strong consistency per flight-leg-cabin - the booked vector and its derived availability must be linearizable per key. No two bookings may push a class past its nested limit. Availability queries are eventually consistent (seconds of staleness is normal and expected across a global read fleet).
  • Durability: a ticketed booking and its payment must never be lost. Once money is captured, the PNR and its seat consumption survive any crash.
  • Global reach: reads originate worldwide; p99 read latency must be low on every continent, which forces geo-distributed read replicas and edge caches while the authoritative write stays single-homed per flight.

The tension to state up front: strong per-flight consistency fights a million-QPS global read path. The naive reconciliation - lock the flight row, make everyone (readers included) take the lock - serializes reads behind writes and collapses the shopping path. We resolve it with optimistic concurrency: writes are compare-and-swap against a per-flight version counter (so concurrent sellers of the same flight are serialized only against each other, and there are few of them), while reads never take a lock at all - they read an immutable snapshot of the inventory document, locally, from a replica or cache. Consistency lives exactly on the write, and the read path is free.

Back-of-the-Envelope Estimation (BoE)

Real numbers with the arithmetic, because they dictate the architecture.

Inventory size (the contended state is small):

Flights/day:                 ~8,000
Booking window:              ~360 days open for sale
Legs per flight (avg):       ~1.5
Cabins per leg:              ~2 (Economy, Business; sometimes First/Premium)
=> live inventory keys = 8,000 * 360 * 1.5 * 2 ≈ 8,640,000 ≈ ~10M keys

Each key (one flight-date-leg-cabin) holds:
  classes (~8) * (limit int + booked int) + version + capacity + metadata
  ≈ a few hundred bytes.
10M keys * ~500 B ≈ ~5 GB of live inventory.

The headline: the entire authoritative seat inventory is ~5 GB. It fits in memory on a single well-provisioned node, and comfortably in a sharded in-memory / document store. The contention problem is not about data size; it is about correctness and read fanout.

Read vs write load:

Bookings/day:                ~1,500,000 passengers
Avg booking rate:            1.5M / 86,400 ≈ ~17 bookings/sec average,
                             peaking maybe ~200-500 bookings/sec at busy hours.
Writes to inventory are therefore MODEST: hundreds/sec globally, and for any
  single flight, a few sell attempts/sec even when hot (a flight has ~180
  seats total; it cannot physically take thousands of sales).

Availability queries: look-to-book ≈ 500:1 (OTAs, metasearch, calendar
  shopping that prices many dates per user action):
  1.5M bookings * 500 ≈ 750,000,000 queries/day
  average = 750M / 86,400 ≈ ~8,700 QPS
  shopping peaks + crawler bursts push the caching layer to
  ~300,000 - 1,000,000 QPS.

So the asymmetry is the whole story: reads outnumber writes by ~50,000:1. The write path is low-rate but must be perfectly correct; the read path is enormous but tolerates staleness. Any design that makes reads pay the cost of write correctness is dead on arrival.

Per-flight write contention is naturally bounded:

A single hot flight-cabin: ~180 physical seats, maybe ~200 with overbooking.
Even under heavy demand, it can absorb only ~200 successful sales total,
  spread over days/hours. Concurrent sell attempts on ONE flight at ONE
  instant are typically single digits, rarely low tens.
Contrast: availability queries for that same hot flight can be thousands/sec.

This is why optimistic locking is the right tool: write contention on any single key is tiny (a flight cannot be sold a million times), so CAS retries are rare and cheap, while the reads that are a million/sec never contend at all.

Storage for PNRs and events:

A PNR (passengers ~1.5 avg, itinerary, fare basis, status, payment ref) ≈ 3-4 KB.
1.5M PNRs/day * 4 KB ≈ ~6 GB/day ≈ ~2.2 TB/year of booking records,
  retained for years (audit, refunds, regulatory, interline settlement).
Inventory change-event log (every sell/cancel/limit-update):
  writes ~ hundreds/sec, each ~200 B => a few GB/day, rolled to cold storage.

The durable booking store grows into terabytes/year and needs ACID and rich queries; the inventory stays tiny and in-memory. That split - small hot versioned inventory vs large durable relational PNR store - is the backbone of the schema choices later.

Cache sizing:

Cache the computed availability per (flight, date, cabin) as a compact
  "availability status" (AVS) vector: ~8 classes * 1 byte (open/closed or a
  small count) ≈ tens of bytes per key.
10M keys * ~50 B ≈ ~500 MB of hot availability - trivially cacheable at the
  edge and in regional Redis, so the million-QPS read path hits cache, not
  the authoritative inventory.

The read storm collapses onto ~500 MB of cacheable availability vectors. The authoritative versioned inventory is only touched on a sell, on a cache miss that wants exact counts, or by the AVS refresh pipeline.

High-Level Design (HLD)

The spine: a global edge + shopping tier absorbs the read storm from cached availability; a stateless booking API validates sell requests and calls the inventory service, which owns one versioned inventory document per (flight, date, leg, cabin) and mutates it only by compare-and-swap on a per-flight version counter; a PNR service persists durable bookings in sharded SQL; ticketing/payment runs asynchronously; an AVS pipeline streams inventory changes out to regional read caches; and an RM limit feed applies booking-limit updates to the same versioned documents.

        Millions of availability queries worldwide (agents, OTAs, metasearch)
                               │  shop / price
                               ▼
                   ┌────────────────────────┐
                   │   Edge / CDN + regional │  cached availability (AVS)
                   │   shopping read fleet    │  vectors, short TTL, geo-local
                   └───────────┬────────────┘
             cache hit ◄───────┤ cache miss / exact-count / all SELL requests
                               ▼
                   ┌────────────────────────┐
                   │  Booking API (stateless)│  authN, validate itinerary,
                   │                          │  idempotency key, fare basis
                   └───┬──────────────────┬──┘
           shop reads  │                  │ sell / hold / cancel (writes)
                       ▼                  ▼
          ┌──────────────────┐   ┌──────────────────────────────────────┐
          │ Availability read │   │  INVENTORY SERVICE                   │
          │ replica / cache   │◄──│  key = (flight,date,leg,cabin)       │
          │ (eventually cons.)│AVS│  versioned doc: {ver, limits[],      │
          └──────────────────┘    │  booked[], cap}. Writes = CAS on ver.│
                   ▲ stream        │  Reads = lock-free snapshot read.    │
                   │               └───┬───────────────┬──────────────┬──┘
                   │        HOLD/SOLD  │   sold-out     │  RM limit    │
                   │                   ▼                ▼  updates      ▼
          ┌────────┴────────┐  ┌──────────────┐  ┌──────────────┐ ┌──────────┐
          │  AVS pipeline    │  │  PNR Service  │  │ Ticketing /   │ │ RM Limit │
          │ (Kafka -> caches,│◄─│ (SQL, sharded │  │ Payment       │ │ Feed     │
          │  GDS AVS msgs)   │  │ by PNR) durable│ │ (async, hold  │ │ (apply   │
          └─────────────────┘  │  source of truth│ │  TTL release) │ │ to docs) │
                   │           └───────┬────────┘  └──────────────┘ └──────────┘
                   ▼                   │ events (booked/ticketed/cancelled)
          ┌─────────────────────────────────────────────────────────────┐
          │  Event stream -> interline settlement, loyalty, analytics,    │
          │  audit, inventory event log (durable truth for rebuild)       │
          └─────────────────────────────────────────────────────────────┘

Shopping flow (the million-QPS path):

  1. An agent or OTA asks for availability on a route and date range. The request hits the regional shopping fleet and is answered from the cached AVS vector for each candidate flight-cabin - a compact “which classes are open and roughly how many seats” structure with a short TTL (1-5s). No lock, no authoritative read, served from the nearest region. This is where ~99% of all traffic is absorbed.
  2. On a cache miss, or when the caller demands exact counts (“Direct Access” / long-sell validation), the shopping tier reads a read replica of the inventory document - still lock-free, still possibly a few seconds stale - and computes availability as a pure function of limits[] and booked[].

Sell flow (the strongly-consistent path):

  1. A sell/hold request reaches a stateless booking API server. It validates the itinerary (which legs, which cabin), attaches an idempotency key, and determines the requested booking class.
  2. The booking API calls the inventory service for each leg’s key. The inventory service reads the current document and its version, computes the nested availability for the requested class, and if a seat is available, attempts a compare-and-swap: write the new booked[] vector only if the stored version still equals the one it read, bumping the version on success. If the CAS fails (someone else sold meanwhile), it re-reads and retries a bounded number of times. For a multi-leg itinerary, all legs must succeed (covered in the deep dive).
  3. On success the seat is HELD (not yet ticketed). The booking API creates a durable PNR in the sharded SQL store in HELD state and starts a hold TTL.
  4. Ticketing/payment runs asynchronously. On payment success the PNR flips to TICKETED and the hold becomes a firm sale; on failure or hold timeout, the inventory service releases the seat via another CAS (decrement booked[], bump version), which immediately raises availability for that class and every class nested above it.
  5. Every inventory mutation emits an AVS event; the AVS pipeline refreshes regional caches and replicas and, for GDS interoperability, emits availability-status messages to partner systems. The read fleet converges within seconds.

The structural insight: the only strongly-consistent operation is a compare-and-swap on one small versioned document, and concurrent CAS happens only among the handful of agents selling the same flight at the same instant. Readers - the overwhelming majority of traffic - never touch that path; they read snapshots from caches and replicas. Consistency is paid for exactly once, by the writer, on a key that is physically incapable of high write contention.

Component Deep Dive

The hard parts, naive-first then evolved: (1) nested fare-class inventory buckets, (2) optimistic locking with per-flight version counters, (3) the global high-throughput availability read path, (4) multi-leg atomicity and holds/overbooking.

1. Nested fare-class inventory buckets

The job: a cabin of ~180 seats is sold across booking classes Y > B > M > H > Q > V (high value to low). Availability of a class is not an independent counter - selling a low class must reduce what higher classes can still sell, so the cabin is never oversold and cheap seats never cannibalize the protected pool incorrectly.

Naive approach: one independent counter per class

Give each class its own allocation and counter: Y:40, B:30, M:30, H:30, Q:30, V:20 summing to 180. To sell class M, decrement M_avail; reject when it hits zero.

avail[Y]=40  avail[B]=30  avail[M]=30  avail[H]=30  avail[Q]=30  avail[V]=20
sell(M): if avail[M] > 0: avail[M]-- else reject

Where it breaks:

  • It cannot shift seats between classes. If V-class demand is huge and Y is empty, the flight departs with empty expensive seats and turned-away cheap demand, or vice versa. Fixed partitions waste the scarcest resource on a plane - seats - because real demand never matches the static split.
  • It does not model nesting at all. Airlines deliberately want a high-value class to access seats “below” it: a last-minute full-fare Y passenger should be able to buy a seat even if Y’s own little bucket is empty, as long as the cabin has room. Independent counters forbid exactly the sale the airline most wants to make.
  • Revenue management speaks in nested limits, not partitions. The RM engine outputs booking limits and protection levels (protect N seats for higher classes, cap lower classes), which are inherently nested. A flat-counter CRS cannot even represent what RM tells it to enforce.

Independent buckets are simple and wrong: they fragment a shared physical cabin into rigid pools that mismatch demand and cannot express the nested control airlines actually run on.

Evolved approach: serial-nested booking limits over a shared booked vector

Model the cabin as one shared pool with nested booking limits. Order classes 1..n from highest value to lowest. Store, per key, a nested booking limit L[i] = the maximum number of seats that may be occupied by class i together with every class below it, and a booked vector b[i] = seats currently sold in class i. Nesting requires L[1] >= L[2] >= ... >= L[n], and L[1] = cabin capacity (adjusted for overbooking). The top class can access the whole cabin; each lower class is progressively more restricted.

Availability of class i is a computed function, not a stored number:

AVL(i) = min over j = 1..i of  ( L[j] - Σ_{k >= j} b[k] )

Intuition: selling one seat in class i raises b[i], which counts against the
nested limit of class i AND every higher class j <= i. The sale is legal only
if it keeps EVERY one of those nested limits satisfied, so availability is the
tightest (minimum) headroom across all limits at or above class i.

Worked example - Economy cabin, capacity 180, nested limits and current sales:

class:   Y     B     M     H     Q     V
L[i]:   180   150   120    90    50    20     (nested: non-increasing)
b[i]:    10    20    30    25    15     5      (Σ b = 105 seats sold total)

AVL(V) = L[V] - (b[V])                         = 20 - 5              = 15
AVL(Q) = min( L[Q]-(b[Q]+b[V]), AVL headroom above )
       = min(50-(15+5), 90-(25+15+5), 120-(30+25+15+5),
             150-(20+30+25+15+5), 180-105)
       = min(30, 45, 45, 55, 75)              = 30
AVL(Y) = L[Y] - Σb = 180 - 105                = 75   (Y can reach the whole cabin)

Selling one V-class seat makes b[V]=6; recompute and AVL(Q), AVL(M), … all drop by one too, because the shared pool shrank. That ripple is exactly the nesting behavior independent counters could not express.

  • The stored state is tiny and pure. Per key we keep L[] (set by RM) and b[] (changed by sales). Availability for any class is a pure O(n) function over ~8 numbers. Nothing else needs storing; every “how many M seats are left” is derived on read.
  • Overbooking is one knob. L[1] = physical capacity * overbooking factor (say 180 * 1.1 = 198). The shared pool is allowed to exceed physical seats by the authorized margin; no-shows reconcile it at departure.
  • RM updates are just new L[]. When the forecast shifts, RM pushes a new limit vector; the CRS swaps L[] on the document (via the same CAS, deep dive 2). Sales already made (b[]) are untouched; availability simply recomputes against the new limits. If RM lowers L[Q] below current b[Q]+..., that class simply shows zero availability until sales fall back under the limit - no inconsistency, no data loss.
  • Closing a class is a limit, not a delete. To “close V,” set L[V] so AVL(V) <= 0. The bucket still exists; it reopens the instant the limit rises.

Why this is right:

  • One shared physical cabin, flexibly allocated. Seats flow to whichever class demand shows up in, bounded only by the nested protection levels - maximizing revenue per seat instead of stranding fixed partitions.
  • High classes can always reach down the stack, exactly as airlines require, because AVL(i) includes the whole pool up to L[1] for the top class.
  • It speaks RM’s native language. Booking limits and protection levels map directly onto L[]; enforcement is a pure function, so RM and the CRS never disagree about what a limit means.
  • Oversell is structurally bounded by L[1]: the min-over-limits guarantees total sales never exceed the top nested limit, so the cabin (plus authorized overbooking) is never breached regardless of which classes sold.

The principle: a fare-class inventory is not n counters; it is one pool with a monotone stack of limits, and availability is a derived minimum. Store the limits and the sold vector, compute the rest.

2. Optimistic locking with a per-flight version counter

The job: let many agents worldwide sell the same flight concurrently with strong per-flight consistency (never exceed a nested limit, never double-sell the last seat), while millions of availability reads run with no locking at all.

Naive approach: pessimistic row lock per flight

Wrap each sale in a transaction that locks the flight’s inventory row: SELECT ... FOR UPDATE, check availability, update b[], commit.

BEGIN;
SELECT limits, booked FROM inventory
 WHERE flight='AA100' AND date='2026-11-28' AND leg=1 AND cabin='Y'
 FOR UPDATE;                         -- exclusive lock on the flight's row
-- compute AVL(class) in app; if > 0:
UPDATE inventory SET booked = :newbooked WHERE ... ;
COMMIT;

Where it breaks:

  • Reads get entangled with writes. The dangerous version is when availability queries also take a shared lock (or read inside a serializable transaction) to see consistent data. At ~1M read QPS, readers queue behind every writer’s exclusive lock; the shopping path - the revenue path - stalls on seat sales. Even “read committed” readers can block on the row during the write window on some engines.
  • It does not scale geographically. A pessimistic lock implies a single lock manager. Agents in Singapore, Frankfurt, and São Paulo all round-trip to one region to take the lock before they can even look. Read latency worldwide is hostage to one lock’s location.
  • Lock hold time includes app round-trips. Computing availability and deciding happens while the row is locked; a slow app node or GC pause holds the flight’s lock and freezes every other seller and (if they lock) every reader of that flight.
  • It solves a contention problem that barely exists on writes. A flight can only be sold ~200 times ever; genuine concurrent sell attempts on one flight are single digits. Paying a global pessimistic-lock tax - and taxing the million-QPS read path - to serialize a handful of writers is wildly disproportionate.

Pessimistic locking is correct but it couples readers to writers and centralizes a lock for a workload whose write contention is tiny and whose read volume is gigantic. Exactly backwards.

Evolved approach: versioned document + compare-and-swap, lock-free reads

Store each flight-leg-cabin as a single document with a monotonically increasing version counter. Writers use optimistic concurrency: read the document and its version, compute the new state, then conditionally write only if the version is unchanged, bumping it. Readers never lock - they read whatever snapshot is current and compute availability from it.

inventory doc  key=(flight,date,leg,cabin):
  { version: 1187, cap: 198, limits:[180,150,120,90,50,20],
    booked:[10,20,30,25,15,5] }

SELL(class c):                              # on the authoritative owner
  loop (bounded, e.g. up to 5 tries):
    doc, ver = read(key)                    # lock-free snapshot read
    if AVL(doc, c) <= 0: return SOLD_OUT    # nested-limit check (deep dive 1)
    doc.booked[c] += 1
    ok = compare_and_swap(key, expected_ver=ver, new=doc, new_ver=ver+1)
    if ok: return HELD(class=c)             # version bumped atomically
    # else: someone else wrote; re-read and retry
  return RETRY_EXHAUSTED                    # extremely rare; see fallback

READ (availability query):                  # anywhere, any replica, any region
  doc = read(key)                           # no lock, no version check
  return AVL(doc, c)                         # pure function; may be seconds stale
  • The version counter is the serialization point - and it is per flight. Two concurrent sellers of flight AA100 both read version 1187; the first CAS succeeds and moves to 1188, the second’s CAS fails (expected 1187, actual 1188), so it re-reads 1188 and retries. The last-seat race is resolved by whoever wins the CAS; the loser sees the updated booked[] and correctly returns SOLD_OUT. Double-booking is structurally impossible - a stale write cannot land, because its version no longer matches.
  • Reads never participate. An availability query reads the document and computes AVL with no lock and no version check. It might read version 1187 while a sale advances to 1189 - fine, it is a snapshot, and the AVS pipeline will refresh it within seconds. The million-QPS read path is completely decoupled from write correctness. This is the entire point: optimistic locking moves the only synchronization onto the writer, so readers run free.
  • Contention is naturally low, so retries are rare. Because a single flight takes only single-digit concurrent sell attempts, CAS conflicts are infrequent and resolve in one retry. Optimistic concurrency shines precisely when conflicts are rare - which is guaranteed here by the physics of a 180-seat plane. We are not betting on low contention; the domain enforces it.
  • The write is a tiny critical region with no app logic inside a lock. There is no lock held across the app round-trip. The compute-then-CAS pattern means the only atomic step is the conditional write itself (a single conditional update in the store); the availability math happens on a local copy, outside any mutual exclusion.
  • Where it physically runs. The authoritative document is single-homed (one primary region/owner per flight) so CAS has a single arbiter, with synchronous replication for durability. Writes for a flight route to its home; reads go to the nearest replica. This keeps the strongly-consistent write local to one arbiter while reads are globally distributed - the write home can even follow the flight’s origin region.
  • Hot-key fallback. If a flight ever did see pathological write contention (a fare-sale flash), CAS retries could thrash. Fallback: switch that single key to a short-lived per-key lease / in-memory single-writer queue (serialize its writers through one owner, like a mailbox) just for the burst. This is a per-key degradation, not a system-wide lock, and it is rarely needed because write rates per flight are bounded.

Why this is right:

  • Strong per-flight consistency with lock-free reads. The version counter gives linearizable writes per key; the snapshot reads give a free, globally distributable read path. The two requirements that seemed to fight are separated cleanly.
  • No global lock manager. Each key is its own tiny consistency domain arbitrated by its own version counter on its own owner; there is nothing central to contend on or to place geographically.
  • Correct under concurrency by construction. A sell that read stale state simply fails its CAS and retries against fresh state; it can never overwrite a newer sale. Double-booking requires two writes at the same version, which the counter forbids.
  • Cheap in the common case, degradable in the rare case. Rare conflicts cost one retry; a freak hot key drops to a per-key serialized writer without touching anything else.

The move: replace a lock that readers must respect with a version that only writers must check. Readers stop paying for write safety entirely, which is the only way a million-QPS global read path and strict no-oversell can live in the same system.

3. The global high-throughput availability read path

The job: serve hundreds of thousands to ~1M availability QPS worldwide, at sub-200ms, from inventory that changes continuously, without hammering the authoritative documents or coupling to the write path.

Naive approach: compute availability live from the authoritative store on every query

Every shopping query reads the authoritative inventory document(s) for the candidate flights and computes AVL fresh.

Where it breaks:

  • It points the firehose at the one consistent copy. ~1M QPS of reads against the single-homed authoritative documents drowns the exact nodes that must stay responsive for sells. The read storm starves the write path.
  • Global latency is terrible. A shopper in Brazil reading an authoritative document homed in the US pays a transoceanic round-trip per flight, times dozens of flights per shopping response. Sub-200ms is impossible.
  • Shopping queries are fan-outs, not point reads. A single “flights NYC->LON next month” request touches dozens of flight-date-cabin keys. Multiply by 1M QPS and the authoritative store sees tens of millions of document reads/sec. No single-homed consistent store survives that.

Serving the read storm from the consistent copy destroys both read latency and write health; the consistency the authoritative copy provides is wasted on queries that do not need it.

Evolved approach: precomputed AVS vectors, geo-distributed caches and replicas, event-driven refresh

Decouple reads completely. Precompute a compact Availability Status (AVS) vector per (flight, date, cabin) - “which classes are open, and a bounded count/bucket” - and serve the read storm from edge caches and regional replicas, refreshed by an event stream off every inventory change.

  • AVS vectors, not raw counts. For each key, derive a tiny vector: per class, OPEN / CLOSED plus a coarse availability (exact small numbers like 0-9, “9+” above that - the GDS-style “numeric availability” / AVS convention). Most shopping decisions need only “is this class sellable,” so a few tens of bytes per key suffices, and the whole hot set is ~500 MB - cacheable everywhere.
  • Event-driven refresh (CDC). Every successful CAS on an inventory document emits a change event (new version, new booked[]/limits[]). An AVS pipeline consumes the stream, recomputes the affected AVS vectors, and pushes them to regional Redis and edge caches with a short TTL (1-5s). Staleness is bounded by stream lag plus TTL - a few seconds, which is standard and acceptable for shopping. The authoritative store is read once per change by the pipeline, not once per query.
  • Geo-distributed read fleet. Regional caches and read replicas of the inventory documents live on every continent. A shopper in Brazil reads a São Paulo cache; a cache miss falls to a regional replica; only pipeline refreshes and exact-count “Direct Access” calls reach the authoritative home. Read latency is local; the write home is irrelevant to readers.
  • The sell commit re-validates, so stale reads are safe. A shopper may see “M open” from a 3-second-old AVS vector and attempt to book; the sell path (deep dive 2) re-checks AVL under CAS against the authoritative document. If the class actually closed, the sell returns SOLD_OUT and the shopper reshops. Availability is advisory; the commit is authoritative. This is what lets the read path be aggressively cached and stale without ever causing an oversell.
  • Crawler and metasearch shaping. A large share of the read volume is automated crawling. Serve it from long-TTL edge caches, apply per-partner rate limits and a “polled AVS” subscription model (push AVS deltas to big partners instead of letting them poll every key), and the effective origin load drops by orders of magnitude.
inventory change -> event {key, version, new AVS vector}
      │
      ▼  AVS pipeline (Kafka consumers)
regional Redis (per continent)  +  edge CDN  <-- short TTL (1-5s)
      ▲                                   ▲
 cache miss                          shopping queries (geo-local)
      │
read replica (eventually consistent) of inventory docs
      │
authoritative doc (single-homed)  <-- touched only by pipeline + exact-count + sells

Why this is right:

  • The read storm hits cache, not consistency. ~99% of queries terminate at an edge/regional cache of a tiny precomputed vector; the authoritative documents see pipeline refreshes and sells only, staying fast for the write path.
  • Global sub-200ms reads. Every continent reads locally; no transoceanic hop on the hot path.
  • Bounded, safe staleness. Event-driven refresh keeps AVS within seconds of truth, and the sell re-check makes any residual staleness harmless - worst case a shopper reshops.
  • Write path protected. Separating the read fleet from the authoritative store means a crawler surge or shopping peak cannot starve seat sales; the two paths scale independently.

The principle: precompute the answer the reads need (a tiny AVS vector), push it to the edge on change, and let the sell commit be the one place that re-checks truth. Reads get cheap and global; correctness stays home.

4. Multi-leg atomicity, holds, and overbooking

The job: a booking often spans multiple legs (NYC->LON->BOM consumes inventory on two legs). The booking must take a seat on every leg atomically - all or nothing - hold them through payment, and respect overbooking limits, all while each leg is an independent versioned document.

Naive approach: sell each leg independently, in sequence

Loop over legs; CAS a seat on leg 1, then leg 2; if leg 2 is sold out, you already took leg 1.

Where it breaks:

  • Partial allocation leaks seats. Leg 1 succeeds, leg 2 fails, and now leg 1 holds a seat for a booking that cannot exist. Repeated under load, hot legs bleed phantom holds and show falsely sold out.
  • No atomicity across keys. The two legs are separate documents with separate version counters; a single CAS cannot span both. There is no built-in cross-key transaction, so naive sequential sells have no rollback discipline.
  • Holds never expire cleanly. If the booking abandons mid-flow, the leg-1 seat sits consumed forever unless something reclaims it.

Independent per-leg sells with no coordination produce orphaned holds and inconsistent availability across a connecting itinerary.

Evolved approach: two-phase hold across legs with TTL, compensation, and overbooking in the limit

Treat a multi-leg sell as a saga of per-leg holds with explicit compensation, each hold carrying a TTL, and fold overbooking into the nested top limit.

  • Phase 1 - hold every leg. For each leg’s document, CAS a HELD increment (holds count against booked[] just like sales, so availability reflects them). Record each successful hold with the PNR and a TTL. If any leg’s CAS returns SOLD_OUT after bounded retries, compensate: release every already-held leg via a reverse CAS (decrement, bump version), and return the whole itinerary as unavailable. The booking is all-or-nothing; no leg keeps a seat unless all legs succeeded.
  • Phase 2 - confirm or expire. The held PNR goes to payment. On payment success, the holds convert to firm sales (a state flag on the booking; inventory already counts them, so no further decrement is needed - the hold already reserved the seat). On payment failure or hold-TTL expiry, a reaper releases every leg via compensating CAS, raising availability for the affected classes (and all classes nested above them) immediately.
  • Idempotency protects the saga. Each leg hold carries the PNR + idempotency key; a retried hold request for the same PNR is recognized and does not double-decrement. A retried release is likewise idempotent. This makes the saga safe under client retries and network partitions, which are inevitable across a global agent network.
  • Overbooking lives in L[1]. Authorized overbooking is simply L[1] = capacity * overbooking_factor, so the nested-limit math (deep dive 1) already permits selling beyond physical seats by the sanctioned margin. No special case in the sell path - a seat is available because the top limit says so. No-show reconciliation and denied-boarding handling happen at departure in the DCS, out of CRS scope.
  • Ordering to reduce compensation. Hold legs in a deterministic order (e.g., by leg key) and, when possible, hold the scarcer leg first, so a doomed itinerary fails on its tightest leg before taking seats on the others - less compensation churn.
BOOK itinerary [leg1, leg2] class M:
  held = []
  for leg in ordered(legs):
     ok = CAS_hold(leg, class=M, pnr, ttl=20m)       # per-leg optimistic hold
     if not ok:
        for h in held: CAS_release(h, pnr)            # compensate prior holds
        return ITINERARY_UNAVAILABLE
     held.append(leg)
  create PNR(status=HELD, legs=held)                  # durable, sharded SQL
  -> payment (async)
     success -> PNR TICKETED (holds already count as seats)
     fail/TTL -> reaper CAS_release(all legs); PNR EXPIRED

Why this is right:

  • All-or-nothing across legs via hold-then-compensate: a connecting booking never leaves a seat stranded on one leg, because any failure releases every prior hold.
  • Each leg stays independently versioned. The saga coordinates separate CAS operations without needing a distributed transaction across documents; compensation, not 2PC, provides atomicity, which suits globally distributed, independently-homed leg documents.
  • Holds are self-cleaning. TTL + reaper guarantees abandoned bookings return their seats, so hot legs do not accumulate phantom holds.
  • Overbooking is free of special cases - it is one number in the nested limit stack, enforced by the same availability function as everything else.

The principle: cross-leg atomicity on independently versioned keys is a saga of optimistic holds with compensation and TTLs, not a global lock - the same per-key optimistic concurrency, composed across legs with explicit rollback.

API Design & Data Schema

External APIs

REST/HTTPS over the booking tier. Shopping is cache-served and read-only; sell calls carry an idempotency key.

GET /v1/availability?from=JFK&to=LHR&date=2026-11-28&cabin=Y&pax=1
  -> 200 {
       "flights":[
         { "flight":"AA100", "date":"2026-11-28", "legs":[1],
           "cabin":"Y",
           "classes":{ "Y":"9+", "B":"9+", "M":7, "H":4, "Q":0, "V":0 },
           "as_of":"2026-11-28T06:00:03Z" } ] }   // AVS vector, may be seconds stale

GET /v1/availability/exact?flight=AA100&date=2026-11-28&leg=1&cabin=Y&class=M
  -> 200 { "flight":"AA100", "class":"M", "avail":7, "version":1187 }  // Direct Access

POST /v1/bookings                 # create a held PNR (all-or-nothing across legs)
  headers: { Idempotency-Key: "agt77-AA100-20261128-M-01" }
  body: {
    "itinerary":[ {"flight":"AA100","date":"2026-11-28","leg":1,"cabin":"Y","class":"M"} ],
    "passengers":[ {"name":"A KUMAR","type":"ADT"} ],
    "contact":{ "agency":"OTA_X" }
  }
  -> 200 { "pnr":"X7K2Qp", "status":"HELD",
           "hold_expires":"2026-11-28T06:20:00Z",
           "segments":[ {"flight":"AA100","class":"M","status":"HELD"} ] }
  -> 409 { "error":"ITINERARY_UNAVAILABLE", "sold_out_leg":1 }  // compensated, no leg held

POST /v1/bookings/{pnr}/ticket    # pay + issue; hold becomes firm sale
  body: { "payment_ref":"pay_9c2...", "fare_basis":"MLXAP" }
  -> 200 { "pnr":"X7K2Qp", "status":"TICKETED", "ticket":"0012345678901" }

GET  /v1/bookings/{pnr}           # authz: owner/agency only (defeats enumeration)
  -> 200 { "pnr":"X7K2Qp", "status":"TICKETED", "segments":[...] }

DELETE /v1/bookings/{pnr}         # cancel -> releases every leg, raises availability
  -> 200 { "status":"CANCELLED", "refund":... }

PUT  /v1/inventory/limits         # internal: RM feed updates nested limits (CAS)
  body: { "flight":"AA100","date":"2026-11-28","leg":1,"cabin":"Y",
          "limits":[180,150,120,90,40,15], "expected_version":1187 }
  -> 200 { "version":1188 }  | 409 { "error":"VERSION_CONFLICT", "version":1190 }

Data model and store choices

1. Inventory - versioned document store with per-key CAS (in-memory / document DB). Strongly consistent per key via an atomic conditional write on version; lock-free snapshot reads. Single-homed per flight, synchronously replicated; reconstructable from the event log. The hot, contended state - and the heart of the design.

KEY  (flight, date, leg, cabin)           # e.g. AA100:2026-11-28:1:Y
  version    int          # per-flight optimistic concurrency counter
  cap        int          # physical capacity * overbooking factor (== limits[0])
  limits     int[]        # nested booking limits, non-increasing (set by RM)
  booked     int[]        # seats held+sold per class (changed by sell/release)
  class_map  str[]        # index -> RBD code (Y,B,M,H,Q,V)
  # availability is DERIVED: AVL(i) = min_{j<=i} (limits[j] - Σ_{k>=j} booked[k])
  # writes: compare-and-swap on `version`.  reads: snapshot, no lock.
  Shard key: the whole key -> one owner. Single arbiter per flight-leg-cabin.

2. Bookings / PNR - sharded SQL (Postgres), durable source of truth. Relational because a PNR is a transactional entity (passengers, segments, fare basis, payment, status) needing ACID, joins, and rich lookups for servicing, refunds, interline settlement, and audit. The money and the itinerary must be durable.

-- shard by PNR (hash) so a PNR lookup hits one shard
CREATE TABLE pnr (
  pnr            CHAR(6) PRIMARY KEY,         -- record locator (base36-ish)
  status         VARCHAR(10) NOT NULL,        -- HELD|TICKETED|CANCELLED|EXPIRED
  agency_id      BIGINT      NOT NULL,
  hold_expires   TIMESTAMPTZ,
  fare_paise     BIGINT,
  payment_ref    VARCHAR(40),
  idempotency_key VARCHAR(80) UNIQUE,         -- dedupe retries: no double PNR
  created_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE pnr_segment (
  pnr        CHAR(6) REFERENCES pnr(pnr),
  seq        SMALLINT,
  flight_no  VARCHAR(8) NOT NULL,
  flight_date DATE      NOT NULL,
  leg        SMALLINT   NOT NULL,
  cabin      VARCHAR(2) NOT NULL,
  booking_class CHAR(1) NOT NULL,             -- RBD actually sold
  status     VARCHAR(10) NOT NULL,            -- HELD|CONFIRMED|CANCELLED
  PRIMARY KEY (pnr, seq)
);
CREATE INDEX ON pnr (agency_id, created_at);                 -- agency queries
CREATE INDEX ON pnr_segment (flight_no, flight_date, leg);   -- flight manifest
CREATE TABLE pnr_passenger (
  pnr CHAR(6) REFERENCES pnr(pnr), seq SMALLINT,
  name VARCHAR(64), pax_type CHAR(3),         -- ADT|CHD|INF
  ticket_no VARCHAR(14), PRIMARY KEY (pnr, seq)
);

3. Inventory event log - append-only (Kafka / log store). Every CAS (hold, sell, release, limit update) emits an event with the new version. This is the durable truth to rebuild an inventory document after a crash and to audit “how did this class close.” Sequential, cheap.

event: { seq, key, version, type:HOLD|SELL|RELEASE|LIMIT, class, booked_after,
         limits_after, pnr, ts }      # replay -> reconstruct inventory doc

4. AVS read cache - regional Redis + edge CDN, eventually consistent. Compact AVS vector per (flight, date, cabin), refreshed from the event stream, short TTL. Serves the ~1M-QPS read storm; seconds-stale is fine because the sell re-checks the authoritative document.

5. Reference data - read-mostly SQL + CDN. Schedules, routes, equipment/capacity, RBD definitions, fare-class hierarchy. Changes slowly, cached hard at the edge.

Why this split: the contended write (nested-limit CAS) needs in-memory-fast, strongly consistent per-key conditional writes, so it lives in a versioned document store, not a lock-heavy relational row. The durable booking (money, PNR, passengers, interline) needs ACID and rich queries, so it lives in sharded SQL. The read storm needs cheap, stale-tolerant, geo-local fanout, so it lives in a cache + CDN fed by an event stream. SQL vs NoSQL is decided per access pattern: NoSQL/document + CAS for the hot versioned inventory, SQL for the relational durable PNR, cache for reads. Forcing one database to do all three fails at all three.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. The availability read storm (~1M QPS, global) - breaks first. Pointing it at the authoritative inventory kills both read latency and the sell path. Fix: precomputed AVS vectors in regional Redis + edge CDN, refreshed by the inventory event stream (CDC) with a 1-5s TTL (deep dive 3). ~99% of reads hit a geo-local cache of a tiny vector; the authoritative documents see only pipeline refreshes, exact-count calls, and sells. The sell commit re-checks truth, so stale reads are harmless.

2. Read-write coupling on the consistent copy. A single consistent store that readers must respect would serialize reads behind sells. Fix: optimistic concurrency with a per-flight version counter (deep dive 2). Writes CAS on version; reads take no lock and read snapshots from replicas/caches. The only synchronization is on the writer, so the read fleet is fully decoupled and independently scalable.

3. Hot-flight write contention and CAS retry storms. A fare-sale flash could make many agents CAS the same flight at once, thrashing retries. Fix: write contention per flight is naturally tiny (a plane takes ~200 sales ever), so CAS conflicts are normally one retry. For a pathological hot key, degrade that single key to a short-lived lease / single-writer queue (serialize its writers through one in-memory owner) just for the burst - a per-key fix, never a global lock.

4. Multi-leg orphaned holds. Partial sells across legs strand seats and show false sold-outs. Fix: a saga of per-leg optimistic holds with compensation and TTLs (deep dive 4) - all-or-nothing across legs, abandoned holds reaped on expiry, idempotency keys making retries safe.

5. Geo-distribution vs write consistency. CAS needs a single arbiter per key, but reads are worldwide. Fix: single-home each flight’s authoritative document (home it near the flight’s origin region) with synchronous replication for durability; serve reads from the nearest replica/cache. Writes for a flight are local to its home arbiter; readers never cross oceans. Consistency is local, reads are global.

6. RM limit updates racing live sales. A new limits[] could clobber a concurrent sale. Fix: RM updates use the same CAS on version as sells. A limit write that lost a race re-reads and reapplies; a sale that lost to a limit update re-checks availability against the new limits. One concurrency mechanism governs both; lowering a limit below current bookings simply shows zero availability until sales fall back, with no data loss.

7. PNR database write and lookup hot spots. Even at ~17 writes/sec average, bursts and multi-year retention stress one store. Fix: shard the PNR tables by record-locator hash for even spread and single-shard lookup; partition by flight month and archive past-travel PNRs to cold storage; keep the durable PNR write off the synchronous CAS path (write after the hold is granted). Agency “my bookings” served by the agency_id index or a read replica.

8. Single points of failure in an inventory owner. If the home of a hot flight dies, sells for it stall. Fix: synchronous replica per inventory shard with the append-only event log as durable truth; on failover the replica rebuilds limits[]/booked[]/version from snapshot + log and resumes CAS. No hold or sale is lost because the log is authoritative; a brief pause on one flight is acceptable, an oversell is not - correctness over availability on the sell path.

9. Storage growth (~2.2 TB/year of PNRs + event log, retained for years). Regulatory, refund, and interline-settlement rules forbid purging. Fix: partition PNR tables by journey month, archive flown bookings to cheaper cold storage, and roll the inventory event log to object storage after departure. Periodic snapshots of each inventory document bound how far a shard must replay to recover.

Shard keys, stated plainly: inventory and AVS shard by (flight, date, leg, cabin) - simultaneously the unit of contention, consistency, and the version counter’s scope. PNRs shard by record-locator hash for even write spread and single-shard lookup. Booking API and shopping servers are stateless (scale for load only). The authoritative inventory document for a flight is single-homed with synchronous replicas; reads come from geo-local replicas/caches. Never split one inventory key across writers - one key, one version counter, one arbiter is exactly what makes oversell impossible.

Wrap-Up

The trade-offs that define this design:

  • Optimistic concurrency, not pessimistic locks. The one thing that must be linearizable - a seat sale against nested limits - is a compare-and-swap on a per-flight version counter. Because a plane can only be sold ~200 times, write contention is tiny and CAS retries are rare, so we pay almost nothing for strict correctness. We trade a simple global lock for a per-key version that only writers check, which is what lets reads run free.
  • Inventory is a pool with nested limits, not n counters. Availability is a derived minimum over a monotone stack of booking limits, so seats flow to real demand, high classes can always reach down the stack, and RM’s limits map straight onto enforcement. We trade the simplicity of flat buckets for the revenue and correctness of true nesting.
  • Reads are cached, stale, and global; the commit is authoritative. A million-QPS shopping path is served from precomputed AVS vectors at the edge, refreshed by an event stream, while the sell re-checks the authoritative document under CAS. We trade perfectly live availability for a read path that does not melt and a write path it cannot starve.
  • Cross-leg atomicity is a saga, not a distributed transaction. Independently versioned legs are composed with hold-then-compensate and TTLs, so a connecting booking is all-or-nothing without a global lock across documents.
  • Correctness over availability on writes. If an inventory owner is uncertain, it halts that one flight rather than risk an oversell; a briefly stuck flight is recoverable, a double-booked seat and an involuntary denied boarding are not.

One-line summary: each flight-leg-cabin is one versioned document holding a monotone stack of nested booking limits and a booked vector, from which availability is a derived minimum; sells mutate it only by compare-and-swap on a per-flight version counter (so concurrent sellers of a flight serialize only against each other while millions of global availability queries read lock-free, geo-local, precomputed AVS vectors refreshed by an event stream), multi-leg bookings are a saga of optimistic per-leg holds with TTL and compensation, and the durable PNR lives in sharded SQL with an append-only inventory event log as the source of truth for scale, recovery, and audit - so thousands of daily flights are sold with strong per-flight consistency, never oversold, without ever serializing reads behind a lock.