Go Concurrency Internals and Flight-Booking Storage Design

Hard · System Design · Software Engineer · Technical Screen

Prompt

Walk through the following language-runtime and data-storage engineering topics, then bring them together in a concrete system design:

  1. Execution & I/O Semantics in Go: Differentiate synchronous versus asynchronous call flows from blocking versus non-blocking kernel I/O, explaining how Go's runtime bridges both layers.
  2. Goroutines vs. Kernel Threads: Compare operating-system threads against Go goroutines across scheduling architecture, stack allocation and growth, per-unit memory footprint, context-switching cost, and state coordination idioms (channels versus mutex-guarded shared memory).
  3. Cross-Language Concurrency Models: Contrast Go's concurrency runtime with at least one other mainstream language (such as Java, Python, or C++), examining how kernel/virtual threads, async/await event loops, or interpreter locks such as Python's GIL shape latency and throughput.
  4. Database Engine Families: Compare relational, document, analytic columnar, and key-value stores with respect to schema flexibility, transaction models (ACID vs. BASE), secondary indexing and joins, horizontal scaling via sharding and replication, and core use cases.
  5. End-to-End Flight Ticketing Storage Design: Architect the storage and caching tiers for a flight-reservation platform that serves rich multi-filter itinerary searches alongside heavy write concurrency—specifying primary database choices, table or document schemas, caching layers, read/write execution paths, and key architectural trade-offs.

Scope & Expectations

  • Go Scheduler & I/O Internals: Clear explanation of user-space G-M-P scheduling, network-poller integration, dynamic stacks, channels vs. mutexes, and edge cases where OS threads still block.
  • Cross-Runtime Trade-Offs: Grounded comparison of multi-core CPU parallelism, memory overhead, and tail-latency hazards across Go and alternative language runtimes.
  • Storage Architecture Comparison: Accurate contrast of transactional relational engines, nested document stores, column-oriented analytical warehouses, and low-latency key-value stores.
  • Cohesive Flight-Booking Design: Polyglot storage design separating high-QPS multi-leg itinerary search from strictly consistent, flash-sale-safe seat inventory and booking transactions.

Step-by-step walkthrough

  1. Frame the three parts around a Go flight-booking platform

    This interview prompt links three layers of backend engineering—Go concurrency, cross-language runtime trade-offs, and database architecture—and asks you to unite them inside a high-concurrency flight-booking platform. Rather than giving three disconnected mini-lectures, frame one end-to-end story where the Go concurrency concepts directly shape how the booking and search services talk to the databases.

    45-minute pacing and explicit assumptions: - Go I/O, G-M-P scheduler, channels vs. mutexes, and language comparison (12 min) - Relational, document, columnar, and key-value trade-offs (8 min) - Flight-booking storage design, schema, read/write paths, and flash-sale concurrency (25 min)

    State four concrete assumptions for the flight platform upfront: 1. Seat ownership: Our platform holds authorized seat allotments per flight and fare class (like an airline backend or ticket consolidator), so our database is the single authority on whether a seat is sold out. 2. Search workload: 50 million searches/day (~580/s average, ~3,000/s peak) across direct and 1-stop itineraries with cabin, time, and price filters. 3. Booking workload: 50,000 bookings/day (1,000:1 search-to-book ratio), spiking to 2,000 concurrent purchase attempts/s on a single promotional flight during flash sales. 4. Supplier feed workload: Airline revenue systems push 10,000 fare and seat-allotment updates/s on average (50,000/s peak). 5. Hard invariant: Never sell more seats in a fare class than authorized—and in our Go services, run one goroutine per request, attach deadlines (context.Context) to every call, and never hold a database transaction open across an external network hop.

  2. Call execution modes and kernel I/O behavior in Go

    Engineers frequently conflate these two pairs of terms, but they describe two completely separate layers: - Synchronous vs. asynchronous execution describes how the caller behaves: a synchronous call waits until the work finishes before running the next line of code, whereas an asynchronous call starts work in the background (returning a channel, future, or callback) so the caller can do other tasks first. - Blocking vs. non-blocking I/O describes what the operating-system (OS) kernel does to the calling thread: a blocking system call puts the OS thread to sleep until network bytes arrive, whereas a non-blocking system call returns immediately with EAGAIN ("no data ready yet"), letting a kernel event notifier (epoll on Linux, kqueue on macOS/BSD, IOCP on Windows) wake the program later when any of thousands of sockets becomes readable.

    Go's superpower: You write clean, easy-to-read synchronous, blocking-style code, while the Go runtime transparently executes non-blocking network I/O underneath!

    What happens when your Go code calls `conn.Read(buf)` on a network socket:
    
      Your Goroutine G1              Go Runtime Network Poller           OS Kernel (epoll / kqueue)
      -----------------              -------------------------           --------------------------
      1. Calls conn.Read(buf) -----> Non-blocking read gets EAGAIN
      2. G1 is "parked" (paused);    Registers socket fd in poller ----> Watches 50,000 sockets at once
         OS Thread M1 NEVER sleeps!
         M1 immediately runs G2, G3...
                                     <--- Kernel signals: socket ready!
      3. G1 marked runnable again <- Wakes G1 and puts it on run queue
      4. conn.Read(buf) returns bytes!
    

    When you actually want asynchronous fan-out in Go (for example, fetching a fare quote and a seat map in parallel), you launch a goroutine (a lightweight user-space concurrent function managed by the Go runtime) and collect its answer over a channel:

    // Synchronous style: simple sequential code (goroutine parks on network wait; OS thread stays busy)
    fare, err := fetchFare(ctx, flightID)
    
    // Asynchronous style: start fetchFare concurrently, fetch seat map meanwhile, then await channel
    fareCh := make(chan FareResult, 1)
    go func() {
        f, err := fetchFare(ctx, flightID)
        fareCh <- FareResult{Fare: f, Err: err}
    }()
    seatMap, seatErr := fetchSeatMap(ctx, flightID)
    fareRes := <-fareCh
    

    Two critical exceptions where Go does block a real OS thread: 1. Local disk file I/O and blocking syscalls: On Linux, regular disk files do not support epoll readiness notifications. When a goroutine reads a slow local disk file, the OS thread genuinely blocks; the Go runtime detaches its logical processor so another OS thread can keep running other goroutines—meaning 5,000 stalled disk reads can spawn 5,000 OS threads (crashing the process if it hits Go's 10,000-thread safety cap in debug.SetMaxThreads). 2. cgo calls into C libraries: Calling C code occupies the underlying OS thread until the C function returns.

  3. OS threads vs. goroutines: G-M-P scheduler, stacks, and switch cost

    An OS thread is a kernel-scheduled execution unit with its own CPU registers and fixed virtual-memory stack. Switching between two OS threads requires a context switch—trapping into the OS kernel, saving/restoring registers, and often losing CPU cache warmth. Go avoids that overhead with an M:N scheduler (multiplexing M lightweight goroutines onto N OS threads in user space), known as the G-M-P model:

    Go G-M-P Scheduler (GOMAXPROCS = 4 on a 4-CPU container):
    
      CPU Core 1                 CPU Core 2                 Global Run Queue & Netpoller
      +--------+                 +--------+                 [ G19 ] [ G20 ] ...
      |   M1   | (OS Thread)     |   M2   | (OS Thread)
      +--------+                 +--------+
          | holds                    | holds
      +--------+                 +--------+
      |   P1   | (Logical Proc)  |   P2   | (Logical Proc)
      +--------+                 +--------+
      Running: G1                Running: G8
      Local queue: [G2, G3, G4]  Local queue: []  <-- empty! Steals half of P1's queue ([G3, G4])!
    
    • G (Goroutine): Holds the instruction pointer, scheduling state, and a tiny dynamic stack.
    • M (Machine): A real OS kernel thread.
    • P (Logical Processor): An execution token (count = GOMAXPROCS, matching logical CPUs—and respecting Linux container CPU quotas automatically in Go 1.25+) holding a lock-free local queue of up to 256 runnable goroutines.
    • Work stealing & preemption: When a P's local queue runs dry, it steals half the goroutines from another P's queue so all cores stay busy without fighting over one global lock. A background monitor (sysmon) reclaims Ps from threads stuck in syscalls and preempts any goroutine hogging a CPU for more than ~10 ms (using OS signals since Go 1.14, so even tight math loops cannot freeze the scheduler).
    Property OS Thread (Linux pthread) Go Goroutine
    Managed by OS kernel (clone syscall) Go user-space runtime (G-M-P)
    Initial stack Fixed reservation upfront (~8 MB default virtual address space on Linux; ~1 MB in JVM) Starts tiny (~2 KB, adaptive since Go 1.19); grows/shrinks dynamically up to 1 GB
    How stack grows Cannot grow past reservation (triggers stack overflow); physical pages committed as touched Allocates a 2× larger contiguous block, copies stack, and updates pointers (safe because Go tracks every pointer)
    Memory per idle unit Tens of KB (touched pages + kernel stack + kernel metadata) ~2–4 KB
    Context-switch cost Order of ~1–2 microseconds (kernel trap + scheduler + TLB/cache impact) Order of ~100–300 nanoseconds (user-space register swap; exact number varies by CPU)
    Practical scale Thousands per process Hundreds of thousands to millions per process
  4. Goroutine communication: channels vs. shared-memory mutexes

    Go supports two ways for goroutines to coordinate safely: - Channels (chan T): Typed message pipes that transfer data and synchronize execution at the same time (Go's memory model guarantees a channel send completes in visibility before its matching receive finishes). An unbuffered channel waits for sender and receiver to meet (a synchronous hand-off); a buffered channel holds up to N items before blocking senders (a bounded queue). - Shared memory with a Mutex (sync.Mutex / sync.RWMutex): A mutual-exclusion lock guarding an in-memory struct or map in place so only one goroutine mutates it at a time.

    // Option A: Mutex — simplest and fastest for guarding in-memory state (caches, counters, pools)
    type FareCache struct {
        mu    sync.RWMutex
        fares map[int64]int64
    }
    
    func (c *FareCache) Get(flightID int64) (int64, bool) {
        c.mu.RLock()
        defer c.mu.RUnlock()
        price, ok := c.fares[flightID]
        return price, ok
    }
    

    Practical Go engineering rules: - Use mutexes (or sync/atomic) to protect shared structs/maps; use channels for multi-stage pipelines, worker pools, ownership hand-offs, and cancellation signals (ctx.Done()). - Always bound fan-out and attach timeouts (context.WithTimeout + errgroup.Group with SetLimit(16)), and run go test -race in CI to catch unsynchronized memory access. - Crucial architectural boundary: Neither a Go channel nor a sync.Mutex protects seat inventory across 20 stateless Go pods! In-process synchronization coordinates parallel network calls inside one request; cross-server seat invariants belong in the database.

  5. Go vs. Java, Python, and C++ concurrency

    To compare languages clearly, define three runtime concepts first: - GIL (Global Interpreter Lock): An internal mutex in standard CPython ensuring at most one thread per process executes Python bytecode at any instant. - Event loop (async/await): A single OS thread cooperatively switching among thousands of paused async functions whenever they await non-blocking I/O. - Virtual threads: Lightweight user-space threads added in Java 21 (Project Loom) that unmount from OS carrier threads during blocking I/O—bringing Go's programming model to the JVM.

    Language Concurrency model Multi-core CPU parallelism Throughput & tail-latency profile
    Go G-M-P goroutines; synchronous code over runtime netpoller Yes (up to GOMAXPROCS cores) High I/O concurrency with low RAM; concurrent GC keeps pauses sub-millisecond at modest CPU cost.
    Java 1:1 OS platform threads, or M:N virtual threads (Java 21+; synchronized pinning largely removed in Java 24) Yes Top-tier JIT CPU throughput; modern ZGC/Shenandoah keep GC pauses sub-ms, at higher baseline memory than Go.
    Python (CPython) OS threads (constrained by GIL) or single-threaded asyncio event loop (optional GIL-free build in 3.13+) Not for pure Python threads (use multiprocessing or C/Rust extensions like NumPy that release the GIL) Threads work fine for moderate I/O (syscalls release GIL), while asyncio handles high I/O concurrency—unless one careless synchronous call blocks the loop!
    C++ 1:1 std::thread + C++20 stackless coroutines + libraries (Asio, folly) Yes Highest peak throughput and zero GC tail pauses, at the cost of manual lifetime safety and explicit async wiring.

    Look at how easily a single blocking call ruins tail latency in Python's single-threaded asyncio loop (and introduces function coloring, where async functions can only be awaited by other async functions—a viral split Go avoids):

    import asyncio
    import time
    
    
    async def broken_endpoint():
        # BAD: time.sleep blocks the single OS thread running the event loop!
        # Every other concurrent request on this worker freezes for 1 full second.
        time.sleep(1.0)
    
    
    async def healthy_endpoint():
        # GOOD: yields control back to the event loop so thousands of other coroutines keep running.
        await asyncio.sleep(1.0)
    
  6. Four storage families: trade-offs and sweet spots

    Before comparing the four storage models, define the transaction spectrum: - ACID (Atomicity, Consistency, Isolation, Durability): guarantees multi-step writes succeed or roll back as one unit, obey schema constraints, isolate concurrent transactions, and survive crashes once committed. - BASE (Basically Available, Soft state, Eventual consistency): favors staying writable across nodes during network splits and letting replicas converge asynchronously over milliseconds or seconds. (Real databases sit on a tunable spectrum—DynamoDB offers optional ACID transactions and strong reads; PostgreSQL defaults to READ COMMITTED rather than strict SERIALIZABLE.)

    Store Family Data model & schema Transactions Indexing & joins Scaling pattern Sweet-spot use cases
    Relational (PostgreSQL, MySQL) Normalized tables with strict columns & foreign keys (plus jsonb escape hatch). Full multi-row, multi-table ACID. B-tree, GiST, GIN secondary indexes; rich ad-hoc SQL joins. Vertical + read replicas; horizontal write sharding via app/Vitess/Citus or Distributed SQL. Money, payments, flight seat inventory, orders.
    Document (MongoDB, Couchbase) Self-contained nested JSON/BSON documents; flexible per-document fields. Single-document atomic (multi-doc ACID supported since MongoDB 4.0 with overhead). Field & compound indexes; joins ($lookup) costly—prefer embedding. Built-in horizontal sharding by shard key + replica sets. Product catalogs, user profiles, CMS articles.
    Columnar (Analytics) (ClickHouse, BigQuery, Parquet) Tables stored column-by-column on disk (reads only queried columns + heavy compression). Append/batch-oriented; not for row-level OLTP point updates! Sort keys & min-max block skipping; fast parallel scans & star joins. Massively parallel distributed storage & compute nodes. BI dashboards, pricing funnels, scanning billions of search logs.
    Key-Value (Redis, DynamoDB) Lookup by primary key (DynamoDB adds sort key for single-partition ranges). Atomic per key (Redis Lua; DynamoDB TransactWriteItems up to 100 items). Primary key only (secondary indexes limited / eventually consistent). Effortless horizontal hash partitioning across nodes. Sub-ms caches, user sessions, rate limiters, idempotency flags.

    (Important distinction: do not confuse analytic columnar warehouses like ClickHouse—which store each column contiguously for aggregations—with operational wide-column stores like Cassandra/Bigtable, which are partitioned row stores optimized for massive key-based event writes.)

  7. Flight-booking platform: workload numbers and primary schema

    Scale & Back-of-the-Envelope Math
      Active catalog     50,000 flights/day x 330 days ahead = 16.5M flight-dates
                         x 10 fare classes ('Y', 'B', 'M'...) = 165M inventory rows
                         165M x ~120 B/row = ~20 GB raw (~50 GB with indexes & MVCC overhead)
      Search reads       50M/day = ~580/s avg, ~3,000/s peak (direct + 1-stop connections)
      Bookings           50,000/day = ~0.6/s avg, ~3/s normal peak
                         Flash sale: 2,000 concurrent purchase attempts/s on ONE hot flight!
      Airline feed       10,000 fare/allotment updates/s avg, 50,000/s peak across catalog
      Booking records    50,000/day x ~5 KB (passengers, tickets, rules) = ~250 MB/day
      Analytics stream   50M searches/day x ~1 KB = ~50 GB/day into ClickHouse
    

    Notice the two totally different "high write concurrency" shapes: 1. Airline feed (50,000 writes/s peak): High volume, low contention—updates spread across millions of flights and tolerate 1–2 seconds of batching. 2. Flash-sale bookings (2,000 writes/s peak): Modest global volume, extreme single-row contention—thousands of buyers fighting over 150 cheap seats on Flight SK204 with zero overselling allowed.

    Primary database choice: Sharded PostgreSQL. - Why relational wins as system of record: Preventing overselling requires atomic conditional arithmetic (sold + held + seats <= authorized) together with hold creation. Storing variable passenger lists, baggage ancillaries, and fare-rule snapshots inside a jsonb column on booking gives us Document-store flexibility inside the exact same ACID database! - Two shard rings (single-shard transactions everywhere): 1. Inventory shards (8 PostgreSQL primaries, hash(flight_id) mod 8): Holds flight, fare_inventory, and seat_hold. 8 shards easily absorb batched 50,000/s airline updates (~6,250 row updates/s per primary). 2. Booking shards (4 PostgreSQL primaries, hash(customer_id) mod 4): Holds booking, payment, and outbox. Sharding by customer_id keeps "My Trips" and UNIQUE (customer_id, idempotency_key) on a single shard (encoding the shard ID inside the 6-character record_locator so lookups by locator also route directly!).

    -- Inventory Shard (sharded by flight_id)
    CREATE TABLE flight (
      flight_id     bigint PRIMARY KEY,
      carrier       char(2) NOT NULL,
      flight_number smallint NOT NULL,
      dep_date      date NOT NULL,
      origin        char(3) NOT NULL,
      destination   char(3) NOT NULL,
      dep_at        timestamptz NOT NULL,
      arr_at        timestamptz NOT NULL,
      UNIQUE (carrier, flight_number, dep_date)
    );
    
    CREATE TABLE fare_inventory (
      flight_id    bigint NOT NULL REFERENCES flight(flight_id),
      fare_class   char(1) NOT NULL,            -- e.g. 'Y', 'M', 'Q'
      cabin        text NOT NULL,
      authorized   int NOT NULL,                -- seats airline permits us to sell
      held         int NOT NULL DEFAULT 0,
      sold         int NOT NULL DEFAULT 0,
      fare_cents   bigint NOT NULL,
      currency     char(3) NOT NULL,
      feed_version bigint NOT NULL DEFAULT 0,   -- monotonic supplier sequence number
      PRIMARY KEY (flight_id, fare_class),
      CHECK (held >= 0 AND sold >= 0)           -- note: no CHECK(sold <= authorized) because airlines can cut authorized below already-sold seats!
    );
    
    CREATE TABLE seat_hold (
      hold_id    uuid PRIMARY KEY,
      booking_id uuid NOT NULL,
      flight_id  bigint NOT NULL,
      fare_class char(1) NOT NULL,
      seats      smallint NOT NULL,
      status     text NOT NULL,                 -- HELD, CONFIRMED, RELEASED
      expires_at timestamptz NOT NULL,
      UNIQUE (booking_id, flight_id),           -- guarantees network retries never double-hold seats!
      FOREIGN KEY (flight_id, fare_class) REFERENCES fare_inventory
    );
    CREATE INDEX hold_expiry_idx ON seat_hold (expires_at) WHERE status = 'HELD';
    
    -- Booking Shard (sharded by customer_id)
    CREATE TABLE booking (
      booking_id      uuid PRIMARY KEY,
      record_locator  char(6) NOT NULL UNIQUE,  -- embeds shard prefix, e.g. '2K9P4M'
      customer_id     bigint NOT NULL,
      status          text NOT NULL,            -- PENDING_PAYMENT, CONFIRMED, TICKETED, CANCELLED, EXPIRED
      total_cents     bigint NOT NULL,
      currency        char(3) NOT NULL,
      idempotency_key text NOT NULL,
      details         jsonb NOT NULL,           -- passengers, segment snapshots, baggage, fare rules
      created_at      timestamptz NOT NULL DEFAULT now(),
      UNIQUE (customer_id, idempotency_key)
    );
    
  8. End-to-end architecture: read paths and write paths

                                   Web / Mobile / Partner Clients
                                                 |
                                    +-------------------------+
                                    | Go API Gateway          |
                                    | (auth, limits, timeouts)|
                                    +-------------------------+
                             search /                         \ price-check & book
                                   v                           v
    +--------------+  miss  +-----------------+       +------------------+      +--------------+
    | Redis Query  |<------>| Go Search Svc   |       | Go Booking Svc   |----->| Payment API  |
    | Result Cache |        | (3.3 GB RAM     |       | (stateless saga  |      | (Stripe/PSP) |
    | + SoldOut KV |        |  flight graph)  |       |  orchestrator)   |      +--------------+
    +--------------+        +-----------------+       +------------------+
                                   ^                     |            |
                                   |                     v            v
                                   |        +----------------+   +----------------+
                                   |        | PostgreSQL     |   | PostgreSQL     |
                                   |        | Inventory (x8) |   | Bookings (x4)  |
                                   |        +----------------+   +----------------+
                                   |           ^         | CDC/Outbox    | Outbox
                                   |           |         v               v
    Airline Feeds --> Kafka (compacted)        |      +-----------------------+
                           |                   |      | Kafka Event Bus       |
                           v                   |      +-----------------------+
                     Go Feed Batcher ----------+        |         |         |
                     (200 ms micro-batches)             v         v         v
                                                  Search Graph  Airline   ClickHouse
                                                  Delta Updater Ticketing (Analytics)
    
    1. Search read path (3,000/s peak): Gateway checks Redis for a cached normalized query (SFO:NRT:2026-10-14:2A:ECON, TTL 1–5 min). On a miss, a stateless Go Search Service computes top direct and 1-stop itineraries in < 20 ms purely from its in-memory flight graph—zero PostgreSQL queries!
    2. Live price-check read path: When a traveler clicks a specific itinerary to buy, the Go Booking Service reads the exact (flight_id, fare_class) rows from the PostgreSQL inventory primaries to verify live price and seats before checkout begins.
    3. Supplier feed write path (50,000/s peak): Airline updates enter a log-compacted Kafka topic (which retains the latest value per flight_id + fare_class key). Go Feed Batcher workers group 200 ms windows in memory—collapsing 5 rapid price tweaks on the same flight into 1 write—and execute batched INSERT ... ON CONFLICT DO UPDATE ... WHERE fare_inventory.feed_version < EXCLUDED.feed_version statements (~200–500 rows per short transaction).
    4. Analytics path: CDC (change-data capture) and gateway search logs stream asynchronously into ClickHouse for conversion funnels and route pricing analytics.
  9. Deep dive 1: High-concurrency booking without overselling

    1. Single-segment atomic hold (idempotent & lock-safe). Never SELECT seat counts into Go, subtract in memory, and UPDATE—concurrent goroutines will overwrite each other. Push the check and arithmetic into a single conditional PostgreSQL UPDATE:

    BEGIN;
    -- 1. Idempotency check: if a previous attempt timed out on the network after committing, reuse it!
    SELECT status FROM seat_hold WHERE booking_id = $booking AND flight_id = $flight;
    -- (If already 'HELD' or 'CONFIRMED', COMMIT immediately without touching held count twice!)
    
    -- 2. Atomic check-and-increment: acquires row lock on (flight_id, fare_class).
    --    Concurrent buyers wait ~1 ms; when woken, PostgreSQL re-evaluates WHERE against committed values!
    UPDATE fare_inventory
    SET held = held + $seats
    WHERE flight_id = $flight
      AND fare_class = $class
      AND sold + held + $seats <= authorized
    RETURNING fare_cents;
    -- (If 0 rows returned -> fare class is sold out! ROLLBACK and return HTTP 409.)
    
    -- 3. Record the 15-minute hold (UNIQUE(booking_id, flight_id) blocks any racing duplicate retry).
    INSERT INTO seat_hold (hold_id, booking_id, flight_id, fare_class, seats, status, expires_at)
    VALUES ($hold_id, $booking, $flight, $class, $seats, 'HELD', now() + interval '15 minutes');
    COMMIT;
    

    2. Multi-segment itineraries across shards via a Saga. A round-trip (SFO -> NRT on Shard 3, NRT -> SFO on Shard 6) spans two inventory shards plus one booking shard. Instead of slow two-phase distributed locks, the Go Booking Service runs a saga (a sequence of fast, single-shard ACID transactions paired with compensating undo steps if a later step fails): 1. Insert booking (status = 'PENDING_PAYMENT') on the customer's Booking Shard (UNIQUE (customer_id, idempotency_key) deduplicates double-clicks). 2. Run the 1–2 ms hold transaction on Shard 3 (SFO -> NRT), then on Shard 6 (NRT -> SFO). Because no lock is held across the two calls, cross-shard deadlocks are impossible! If Shard 6 is sold out, immediately run the compensating release (held = held - $seats, status = 'RELEASED') on Shard 3 and return 409. 3. Call the payment provider (idempotency_key = booking_id) with zero database transactions open. 4. Confirm each hold (UPDATE seat_hold SET status = 'CONFIRMED' WHERE hold_id = $h AND status = 'HELD', moving held -> sold atomically), then mark booking.status = 'CONFIRMED' and emit an outbox event for airline e-ticket issuance.

    A background sweeper expires stale holds (status = 'HELD' AND expires_at < now()) using the exact same WHERE status = 'HELD' guard, so confirmation and expiration can never both win.

    3. Surviving a 2,000 req/s flash sale on one row. Updating a single hot row with synchronous replication (~1.5 ms commit RTT) caps throughput at ~650 serial commits/s—yet a plane only has ~150–300 seats, so seats sell out in under half a second! Once sold + held == authorized, failed UPDATEs match 0 rows without writing WAL, and four Go-level guards protect the database: - Strict pool & context bounds: Cap db.SetMaxOpenConns per Go pod so 2,000 cheap goroutines wait cleanly on the Go connection pool with a 500 ms context timeout rather than exhausting PostgreSQL memory. - Short-lived Redis "sold_out" flag: As soon as an UPDATE returns 0 rows, set soldout:{flight}:{class} = 1 in Redis (EX 5), shedding 99% of subsequent flash-sale clicks before they hit PostgreSQL. - Counter splitting (only if needed for giant allotments): Split one fare row into 4 bucket rows of authorized / 4 seats each to multiply write concurrency 4×.

  10. Deep dive 2: In-memory flight graph, caching, failures, and trade-offs

    Why search lives in Go memory instead of SQL joins. Finding 1-stop connections (A -> Hub H -> B where H.dep_at falls 45 min to 8 hours after A.arr_at) across millions of flights at 3,000 queries/s would crush PostgreSQL with self-joins. Look at the memory math instead: - 16.5M flight-dates × ~200 bytes (compact Go struct of airports, timestamps, and 10 class prices/counts) = ~3.3 GB of RAM! - Every stateless Go Search Pod holds the entire global schedule in RAM (using flat value slices rather than pointer-heavy objects so Go's garbage collector barely scans it!), rebuilt nightly and updated continuously within 1–2 seconds via Kafka inventory deltas. - For origin -> destination on date, a goroutine looks up direct flights plus connections through the precomputed top 20 viable hubs H using binary search on time-sorted departure slices—finishing in < 10 ms, then caching the top sorted itineraries in Redis (1 min TTL for flights departing within 7 days; 5 min TTL for later dates, invalidated immediately on Kafka "class sold out" events).

    Failure modes - Inventory shard primary crash: Automatic promotion of its synchronous AZ standby completes in 15–30 s with zero lost holds or sales; Search continues uninterrupted from memory. - Go Booking Pod crashes mid-saga: A recovery worker scans booking rows stuck in PENDING_PAYMENT past 5 minutes, checks payment provider status by booking_id, and either finishes confirming holds or releases holds + voids any authorization. - Redis cache outage: Search falls back directly to the Go in-memory flight graph pods (scale out Search Pods on CPU); booking correctness is untouched.

    End-to-end trade-off summary

    Architectural choice What we gain Cost we accept
    Go (G-M-P + bounded pools) Clean synchronous code handling 10,000+ concurrent sockets per pod Must explicitly bound errgroup fan-out, DB pools, and context deadlines
    PostgreSQL + jsonb primary Rock-solid ACID seat math + flexible nested passenger/ancillary documents in one DB Requires explicit shard routing across Inventory (flight_id) and Booking (customer_id)
    Single-shard holds + Saga Zero cross-shard two-phase commit locks; 1–2 ms hold latency Requires compensating release logic + background recovery/expiry sweepers
    3.3 GB RAM graph + Redis cache < 20 ms multi-leg search; shields PostgreSQL from 1,000:1 read load 1–5 min search price staleness, reconciled at the live price-check step
    Compacted, batched airline feed Absorbs 50,000/s supplier updates without starving live bookings ~200 ms–1 s feed ingestion delay
    ClickHouse columnar analytics Sub-second scans over billions of historical search/price events Eventual consistency (seconds/minutes) and an extra storage system to run

Intuition & how it works

Picture a busy airport ticket hall with two distinct zones: out in the lobby, thousands of travelers browse giant digital departure boards, while behind the desk a few clerks stamp official paper seat ledgers. Go's concurrency runtime works like a small team of tireless clerks (OS threads—kernel-managed execution contexts) serving thousands of travelers (goroutines—tiny user-space tasks starting at a few kilobytes of RAM): the instant a traveler has to wait for a network reply from a bank or database, Go parks that traveler on a bench via non-blocking I/O (an OS mechanism that returns immediately instead of putting the thread to sleep) so the clerk immediately helps the next person in line. Meanwhile, our flight-booking storage architecture separates the lobby departure board (an in-memory Go flight graph + Redis key-value cache serving 3,000 searches/s) from the locked seat ledger (sharded PostgreSQL enforcing ACID—all-or-nothing, crash-safe—seat deductions).

Naive designs fail at both layers. On the compute side, dedicating one heavy 1–8 MB OS thread to every open network request wastes gigabytes of RAM and kernel context-switching time, whereas running a single-threaded async/await event loop stalls every user whenever one careless synchronous call blocks the thread. On the storage side, running multi-city flight connection joins directly against the booking database—or keeping a database transaction open while waiting 1–2 seconds for a credit-card network call—locks seat rows and freezes flash-sale checkouts, while moving seat inventory to an eventually consistent NoSQL store lets concurrent buyers read the same remaining count and oversell the aircraft.

Walk through a concrete 4-step trace when Flight SK204 (SFO -> NRT) has 2 cheap 'M'-class seats left: 1. 500 travelers search SFO -> NRT: Stateless Go Search pods read their 3.3 GB in-memory flight graph (or hit Redis) and return direct + 1-stop options in < 15 ms, placing zero load on PostgreSQL. 2. Priya and Mateo both click "Buy 2 seats" simultaneously: Two Go goroutines execute UPDATE fare_inventory SET held = held + 2 WHERE flight_id = 204 AND fare_class = 'M' AND sold + held + 2 <= authorized on Flight 204's PostgreSQL shard; while waiting 1.5 ms for the socket reply, both goroutines park without blocking any OS thread. 3. Database arbitrates atomically: Priya's UPDATE acquires the row lock first, increments held from 0 to 2 (2 <= 2), records a 15-minute seat_hold, and commits; Mateo's waiting UPDATE wakes up, re-evaluates sold + held + 2 <= 2 (4 <= 2 is false!), updates 0 rows, sets a 5-second Redis "sold_out" flag to shield the DB from the next 1,000 flash-sale clicks, and immediately offers Mateo the next cabin fare. 4. Lock-free payment & confirmation: Priya's goroutine calls Stripe outside any database transaction (idempotency_key = booking_id), then runs a 1 ms transaction moving held -> sold (status = 'CONFIRMED') and streaming the event via Kafka to update the Search graph and ClickHouse (a columnar analytics warehouse).

Key trade-offs

  • Go goroutines (M:N user-space scheduling) vs. 1:1 OS threads. Multiplexing hundreds of thousands of ~2–4 KB dynamically resized goroutine stacks onto a handful of OS threads lets engineers write clean synchronous code without callback spaghetti, at the cost of a garbage-collected runtime, OS threads still blocking on local disk syscalls or cgo, and needing explicit concurrency caps (errgroup.SetLimit, DB pool limits) so cheap goroutines do not overwhelm downstream databases.
  • Go channels vs. shared-memory mutexes (sync.Mutex). Channels (typed synchronization pipes) excel at passing data ownership across pipeline stages and waiting on cancellation (select with ctx.Done()), whereas mutexes (mutual-exclusion locks) are faster and simpler for reading/updating shared maps or counters in place—and neither replaces database constraints when state is shared across multiple server pods.
  • Go vs. Java, Python, and C++ concurrency. Go and modern Java (21+ virtual threads) combine simple blocking-style code with high I/O scalability; Python's GIL (Global Interpreter Lock—allowing only one thread per process to run Python bytecode at once) restricts CPU parallelism to multi-processing or native C extensions and makes asyncio vulnerable to accidental loop-blocking calls; C++ delivers zero garbage-collection pauses and peak CPU control at the steepest complexity and memory-safety cost.
  • Relational vs. document vs. columnar vs. key-value databases. Relational databases (PostgreSQL) enforce cross-row ACID invariants and ad-hoc joins; document stores (MongoDB) fit self-contained variable schemas; columnar stores (ClickHouse, BigQuery—storing each column contiguously on disk) scan billions of analytic rows in milliseconds but fail at small transactional updates; key-value stores (Redis, DynamoDB) deliver predictable sub-millisecond primary-key lookups without joins.
  • PostgreSQL + jsonb + specialized read stores vs. a single all-purpose database. Using PostgreSQL as the single source of truth (with jsonb for flexible passenger/baggage details) alongside an in-memory Go search graph, Redis cache, and ClickHouse analytics keeps every store in its sweet spot, trading 1–5 minutes of search cache staleness (caught cleanly by the pre-checkout live price check) and CDC pipeline maintenance.
  • Single-shard holds + Saga orchestration vs. Distributed SQL. Coordinating multi-flight round-trips via 15-minute holds and a saga (local single-shard ACID steps with compensating undo actions on failure) keeps every PostgreSQL write at 1–2 ms inside one shard, trading explicit hold-expiry and crash-recovery workers against the 10–100 ms cross-node consensus latency of Distributed SQL (Spanner, CockroachDB).

Common mistakes

  • Confusing "asynchronous" with "non-blocking I/O." Synchronous/asynchronous describes whether the caller waits before moving on; blocking/non-blocking describes whether the OS kernel sleeps the thread—Go code is usually synchronous at the language level and non-blocking on network sockets underneath.
  • Claiming goroutines never block an OS thread. Network sockets use the non-blocking netpoller, but local disk file reads, blocking OS syscalls, and cgo calls genuinely occupy an OS thread.
  • Saying Python threads cannot do concurrent work at all. Blocking network and disk I/O in Python releases the GIL, so Python threads handle moderate concurrent I/O fine; the GIL specifically prevents multiple threads from running CPU-bound Python bytecode in parallel on multiple cores.
  • Confusing analytic columnar databases (ClickHouse, Parquet) with wide-column stores (Cassandra, Bigtable). Columnar stores group values of one column together for analytic aggregations; wide-column stores are distributed key-partitioned row stores built for high-rate operational writes.
  • Checking available seats in Go (SELECT), subtracting in code, and writing back (UPDATE). Under flash-sale concurrency, dozens of goroutines read "1 seat left" simultaneously and oversell the flight; always put AND sold + held + $seats <= authorized inside a single atomic UPDATE.
  • Adding CHECK (sold + held <= authorized) on fare_inventory. Airlines routinely reduce authorized allotments on an already half-sold flight; a hard table CHECK would reject valid airline feed updates! Enforce sold + held + $seats <= authorized inside the seat-claiming UPDATE instead.
  • Keeping a PostgreSQL transaction open while calling Stripe or airline ticketing APIs. External network calls turn a 1.5 ms row lock into a 2,000 ms lock, dropping single-flight throughput from hundreds of bookings/s to 0.5/s and exhausting the database connection pool.

Follow-up questions

  • How would your storage and checkout design shift if external airlines owned the authoritative seat counts and your platform operated as an OTA aggregator? PostgreSQL remains the system of record for customer booking and payment state, while fare_inventory becomes a best-effort local cache fed by airline availability streams rather than the authority on remaining seats. During checkout, our Go Booking Service executes the same saga pattern, except the "place hold" and "issue ticket" steps become idempotent RPC calls (with strict context timeouts and circuit breakers) to airline Global Distribution Systems (GDS) or NDC APIs, voiding payment authorizations automatically if the airline rejects the final seat claim. Because airlines strictly rate-limit live availability calls, the 3.3 GB in-memory Go search graph and Redis query cache become even more critical, continuously refreshed whenever any traveler's live price-check reveals a fare change.
  • Under what conditions would you replace manually sharded PostgreSQL with a Distributed SQL engine such as Spanner or CockroachDB? Choose Distributed SQL when multi-shard ACID transactions are the norm rather than the exception, when strict regulatory or uptime requirements demand active-active strongly consistent writes across multiple geographic regions, or when a lean engineering team wants automatic range splitting and rebalancing without maintaining application shard routing. The trade-off is physics: every write requires Raft or Paxos quorum consensus across replicas (10–150 ms across regions vs. 1–2 ms inside one AZ pair), and a single hot flash-sale row still serializes on one range leader—making single-shard PostgreSQL holds faster and cheaper when regional primaries suffice.
  • How do you spot, diagnose, and prevent goroutine leaks in a live Go backend? Monitor runtime.NumGoroutine() in Prometheus and alert on steady upward slopes that do not drop when traffic subsides; when triggered, grab a live goroutine dump from net/http/pprof (/debug/pprof/goroutine?debug=2) to see the exact file, line number, and channel/lock where thousands of goroutines are parked forever. Most leaks happen when a child goroutine tries to send on an unbuffered channel after the parent already timed out and walked away—prevent them by using buffered result channels of size 1 (make(chan Result, 1)), passing context.Context everywhere, including case <-ctx.Done(): inside every blocking select, and running goleak.VerifyNone(t) in unit tests.

Follow-up questions

Similar questions

More TripStack interview questions

All 2 TripStack questions →