Airline Reservation Backend and High-Throughput Live Polling
Medium · System Design · Software Engineer · Onsite
Prompt
Address both backend architecture scenarios below in a single design session.
Part A — Airline Reservation Backend
Architect the core reservation service for an online flight-ticketing platform where travelers search routes (for example, SEA to BOS on Flight 402), assemble an itinerary, pick seats such as 12A, and purchase tickets for one or more passengers without ever overselling cabin capacity or double-assigning a seat.
- Model core relational tables including
Flight,Passenger,Booking, andFlightTicketalongside cabin and seat inventory. - Specify which database indexes to create—and which to omit—and justify how internal B-tree page layout dictates SQL predicate and update patterns.
- Trace the end-to-end checkout workflow and exact SQL statements from route search through hold, payment, and ticket confirmation, ensuring concurrent buyers racing for the final seat never double-book.
Part B — Million-QPS Live Broadcast Polling
Architect a live promotional polling platform for a televised championship broadcast where mobile viewers rapidly tap to pick a limited-edition menu flavor (for example, "mango-habanero") and watch a public leaderboard refresh continuously.
- Sustain sudden bursts reaching multiple millions of taps per second while keeping vote acknowledgments fast, updating the public leaderboard within a couple of seconds, and staying resilient across abrupt traffic spikes.
- Detail the HTTP contracts, service tiers, durable event stream (such as Apache Kafka), parallel tally aggregation, and time-series velocity tracking—including how Kafka log segments/replication and time-series storage engines work under the hood, plus how you deploy and scale the workload on Kubernetes (EKS).
Scope & Expectations
- Schema, indexing, and B-tree internals (Part A): Entity relationships, composite and partial index choices, and concrete rules tying B+tree page structure to fast range scans and hot-row updates.
- Transactional checkout and contention safety (Part A): Hold-and-pay state transitions, idempotency, and SQL concurrency patterns that prevent write skew or seat collisions under flash-sale load.
- Streaming ingestion, counters, and storage internals (Part B): End-to-end data flow, Kafka batching and replication mechanics, stateful stream deduplication, and time-series database compression/indexing for live vote-rate charts.
- Kubernetes spike readiness (Part B): EKS capacity planning, pre-warming, and graceful load shedding when traffic jumps orders of magnitude in seconds.
Step-by-step walkthrough
Clarify requirements and contrast the two systems
Start by telling the interviewer why pairing these two prompts is so revealing: they sit at opposite ends of backend design.
- Part A (Flight Booking) has modest write volume (tens of bookings per second), but requires strict serial consistency on scarce inventory: we can never sell seat
12Ato two travelers or sell 181 seats on a 180-seat cabin. - Part B (Live Event Voting) has extreme write bursts (millions of taps per second during a 30-second TV commercial), where the live scoreboard can lag by 1–2 seconds (eventual consistency on reads), as long as every accepted vote is durably recorded and the final tally is exact.
Part A: Flight booking requirements & assumptions
- Functional: Search flights by
(origin, destination, departure_date, passenger_count); view cabin prices and remaining seats; select a 1-leg or 2-leg connecting itinerary and optional specific seats (12A); book for 1–9 passengers with temporary seat holds while paying; view or cancel bookings. - Non-functional: Search p99 (99th-percentile latency) < 500 ms (cached seat counts may be up to 60 s stale); booking and seat assignment are strongly consistent (zero double-selling); double-clicking "Pay" or retrying on mobile networks never creates duplicate bookings or double charges (idempotency).
- Scale assumptions: 50,000 daily departures bookable 365 days ahead; 1M bookings/day; 500 searches per booking; each cabin has a
sell_limit(equal to physicalcapacitywhen overbooking is off).
Part B: Real-time voting requirements & assumptions
- Functional: Logged-in users tap to vote for 1 of ~8 promotional menu flavors during a live broadcast; a live scoreboard displays total votes per flavor and a votes-per-second trend chart; admins open and close polls.
- Counting rule: At most one counted vote per user per poll—if an excited viewer taps 10 times, the app stays responsive, accepts the taps, and deduplicates so their earliest valid vote counts once.
- Non-functional: Peak bursts of 3,000,000 vote requests/s for ~30 seconds (~50,000/s baseline); vote API p99 < 100 ms at our edge; live scoreboard updates within ~2 s (p99 <= 5 s) for up to 10,000,000 concurrent viewers; zero lost acknowledged votes, backed by an auditable recount.
- Part A (Flight Booking) has modest write volume (tens of bookings per second), but requires strict serial consistency on scarce inventory: we can never sell seat
Back-of-the-envelope numbers for both parts
Part A: Flight Ticket Booking Active flights: 50,000/day x 365 days = ~18.25M rows x 200 B = ~3.7 GB Cabin inventory: ~2 cabins/flight x 18.25M = ~36.5M rows x 60 B = ~2.2 GB Bookings: 1M/day = ~12/s average, ~60/s at 5x peak Tickets: 1.6 passengers/booking = 1.6M/day (~19/s avg, ~95/s peak) Searches: 500 x 1M = 500M/day = ~5,800/s average, ~25,000/s peak Annual DB growth: bookings (~110 GB) + tickets (~146 GB) + indexes ≈ 0.5 TB/year Hot-spot scenario: Flash fare sale -> 20,000 buyers chase one 180-seat flight in 60 s Part B: Live Broadcast Flavor Voting Peak write burst: 3,000,000 req/s for 30 s = 90M requests in one burst Unique voters: <= 40M users per poll (remaining requests are repeat taps) Edge bandwidth: 3M req/s x ~500 B (HTTP/2+TLS) = ~1.5 GB/s (~12 Gbps) Stateless API: ~10,000 req/s per 2-vCPU pod -> 300 pods needed; pre-scale to 360 pods Kafka throughput: 3M x ~130 B Protobuf = ~390 MB/s raw; x3 replication = ~1.2 GB/s disk At ~80-100 MB/s replicated writes/broker -> 15 brokers (5 per AZ) 120 partitions (~25,000 records/s per stream-processor task) Deduplication RAM: 40M users x ~60 B = ~2.4 GB total (~20 MB across each of 120 tasks) Scoreboard reads: 10M viewers polling every 2 s = 5,000,000 GET/s at CDN edge; 1-second CDN cache TTL -> < 200 origin fetches/s total!What the math tells us immediately: - In Part A, total data and write rate fit comfortably on one primary PostgreSQL database with read replicas and Redis search caching. The hard engineering problem is row lock contention when 20,000 people try to buy the same flight at once. - In Part B, nothing on the per-vote path can touch a single shared counter. Incrementing 8 keys in Redis at 3,000,000 ops/s would melt a single-threaded Redis shard (~150k ops/s limit), and letting 10,000,000 viewers hit our backend directly would crush it. Votes must be buffered in Kafka, pre-aggregated in parallel stream tasks, and published as a static JSON file behind a CDN (Content Delivery Network—globally distributed edge caches).
Part A: API contract, relational data model, and indexes
API endpoints
GET /v1/flights/search?from=SEA&to=BOS&date=2026-11-18&pax=2 -> 200 [{ itinerary_id, segments: [...], cabin: "Y", price_cents: 24900, seats_left: 7 }] GET /v1/flights/{flight_id}/seatmap?cabin=Y -> 200 { aircraft_type: "B738", taken_seats: ["12C", "12D"] } POST /v1/bookings Header: Idempotency-Key: <client-uuid> { segments: [{ flight_id: 402, cabin: "Y" }], passengers: [...], seats: [{ flight_id: 402, passenger_idx: 0, seat_no: "12A" }] } -> 201 { booking_id, status: "HELD", hold_expires_at, total_price_cents } -> 409 SOLD_OUT | SEAT_TAKEN POST /v1/bookings/{booking_id}/pay Header: Idempotency-Key: <client-uuid> { payment_method_token: "pm_..." } -> 200 { status: "CONFIRMED", tickets: [...] } | 402 PAYMENT_DECLINED | 410 HOLD_EXPIRED POST /v1/bookings/{booking_id}/cancelPostgreSQL schema
flight flight_id BIGSERIAL PK, airline TEXT, flight_no TEXT, origin CHAR(3), dest CHAR(3), dep_time_utc TIMESTAMPTZ, arr_time_utc TIMESTAMPTZ, aircraft_type TEXT, status TEXT flight_inventory -- one counter row per (flight, cabin), e.g., (402, 'Y') PRIMARY KEY (flight_id, cabin), capacity INT, sell_limit INT, base_price_cents INT, sold INT NOT NULL DEFAULT 0, held INT NOT NULL DEFAULT 0, CHECK (sold >= 0 AND held >= 0 AND sold + held <= sell_limit) passenger passenger_id UUID PK, user_id UUID, first_name TEXT, last_name TEXT, dob DATE, encrypted_doc_number BYTEA booking booking_id UUID PK, user_id UUID, status TEXT, -- HELD -> PAYING -> CONFIRMED -> CANCELLED; HELD -> EXPIRED hold_expires_at TIMESTAMPTZ, total_price_cents INT, currency CHAR(3), idempotency_key UUID, created_at TIMESTAMPTZ flight_ticket ticket_id UUID PK, booking_id UUID REFERENCES booking, flight_id BIGINT REFERENCES flight, cabin CHAR(1), passenger_id UUID REFERENCES passenger, ticket_number TEXT, status TEXT seat_assignment -- contains rows ONLY for currently held or sold seats PRIMARY KEY (flight_id, seat_no), ticket_id UUID NOT NULL REFERENCES flight_ticket outbox -- transactional event queue for email & airline ticketing outbox_id BIGSERIAL PK, topic TEXT, payload JSONB, created_at TIMESTAMPTZ, sent_at TIMESTAMPTZWhy this data model works cleanly: - Cabin-level counter + sparse
seat_assignmenttable: Many economy travelers skip seat selection during checkout.flight_inventorychecks cabin capacity in a single row (sold + held <= sell_limit), whileseat_assignment's composite primary key(flight_id, seat_no)guarantees two tickets can never claim12A. - DatabaseCHECKinvariant: Checkingsold >= 0 AND held >= 0 AND sold + held <= sell_limitinside PostgreSQL prevents any buggy release script from drivingheldnegative and accidentally allowing extra sales. - Transactional outbox: Writing anoutboxrow inside the same SQL transaction that marks a bookingCONFIRMEDguarantees a background relay will send confirmation emails—eliminating the bug where a server crashes after committing the DB write but before publishing to Kafka.Indexes to build (and which ones to avoid)
1. flight(origin, dest, dep_time_utc) INCLUDE (flight_id, flight_no, arr_time_utc, aircraft_type) -> Powers route + date search directly from the index without table lookups. 2. booking UNIQUE (user_id, idempotency_key) -> Blocks duplicate bookings when a user double-taps or retries on bad Wi-Fi. 3. booking(user_id, created_at DESC) -> Renders "My Trips" newest-first with zero sorting work. 4. booking(hold_expires_at) WHERE status = 'HELD' -> Partial index containing ONLY active unpaid holds (~thousands of rows, not hundreds of millions) for the background expiry sweeper. 5. flight_ticket(booking_id) and flight_ticket(flight_id) -> Fast lookup of tickets inside a booking, or passenger manifest for a flight. 6. seat_assignment PRIMARY KEY (flight_id, seat_no) -> Already indexes `WHERE flight_id = 402` for the seat map AND enforces seat uniqueness.We deliberately do not index
flight_inventory(sold)or(held)(updated constantly—see why below), nor a full index onbooking(status)(only 5 distinct values, so a full index has terrible selectivity compared to the tiny partial indexWHERE status = 'HELD').Part A deep dive: How B-tree internals shape query design
Relational databases (
PostgreSQL,MySQL/InnoDB) implement standard indexes as B+trees stored in fixed-size disk/memory pages (8 KBin PostgreSQL,16 KBin InnoDB).[ Root Page: ('ORD' | 'SEA') ] (stays in RAM) / \ [ Internal: ... ] [ Internal: ('SEA','ATL') | ('SEA','BOS') ] \ Leaf Pages (sorted & doubly linked sideways): +---------------------------------------------+ | ('SEA','BOS','2026-11-18 15:00') -> row ptr | | ('SEA','BOS','2026-11-18 23:30') -> row ptr | <-> [Next Leaf] | ('SEA','BOS','2026-11-19 15:00') -> row ptr | +---------------------------------------------+- Tree height is tiny: Each 8 KB page fits ~250–300 index entries. Three levels address
300 × 300 × 300 = 27,000,000flights! Internal pages stay warm in RAM, so finding the starting leaf takes ~1 disk read, and scanning a date range simply walks sideways across adjacent leaf pages. - PostgreSQL vs. InnoDB leaves: In PostgreSQL, every index leaf points to a physical row slot (
ctid) in the heap table. In InnoDB, the primary key's leaf pages are the table rows (clustered index), while secondary index leaves store primary-key values (requiring a second lookup if non-indexed columns are needed).
Five query-design rules that follow directly from this B+tree layout:
- Leftmost-prefix rule & equality before range: A composite index on
(origin, dest, dep_time_utc)is one single lexicographically sorted list—like a phone book sorted by State, then City, then Departure Time. Queries specifyingorigin = 'SEA' AND dest = 'BOS' AND dep_time_utc >= ... AND dep_time_utc < ...land on one contiguous slice of leaves. If we instead indexed(origin, dep_time_utc, dest), the time range on column 2 would scatter'BOS'flights across every'SEA'departure that day! - Never wrap indexed columns in functions: Writing
WHERE DATE(dep_time_utc) = '2026-11-18'forces PostgreSQL to ignore the tree because leaves are sorted by raw timestamps, notDATE(...). Always convert the user's origin-airport local date (e.g., SEA isUTC-8in winter) into a half-open UTC range:dep_time_utc >= '2026-11-18 08:00Z' AND dep_time_utc < '2026-11-19 08:00Z'. - Covering indexes (
INCLUDE) eliminate random heap fetches: AppendingINCLUDE (flight_id, flight_no, arr_time_utc, aircraft_type)copies those payload columns into the leaf pages so PostgreSQL can run an index-only scan without jumping to random heap pages for each matching flight (as long as backgroundVACUUMkeeps the visibility map up to date). - Skip indexes on frequently mutated counter columns: Every time
soldorheldchanges inflight_inventory, PostgreSQL writes a new tuple version. Because neithersoldnorheldis indexed, PostgreSQL performs a HOT (Heap-Only Tuple) update on the same 8 KB page (helped by settingfillfactor = 90) with zero index maintenance. - Sequential vs. random primary keys: Random
UUIDv4inserts hit random B+tree leaves across disk, causing frequent 50/50 page splits and cache misses; time-orderedUUIDv7orBIGSERIALkeys append cleanly to the rightmost leaf.
- Tree height is tiny: Each 8 KB page fits ~250–300 index entries. Three levels address
Part A: End-to-end booking flow and exact SQL queries
Web / Mobile Clients | [ API Gateway (Auth, Rate Limit) ] | | v v [ Search Service ] [ Booking Service ] --------> [ Payment Provider (Stripe/Adyen) ] | | | v v v [Redis 60s] [PG Replicas] [PG Primary] --sync--> [Standby PG (AZ 2)] | [Outbox Relay] --> [Kafka] --> Ticketing & Email WorkersStep 1 — Flight search (cached 60 s in Redis, fallback to read replica):
SELECT f.flight_id, f.flight_no, f.dep_time_utc, f.arr_time_utc, i.cabin, i.base_price_cents, (i.sell_limit - i.sold - i.held) AS seats_left FROM flight f JOIN flight_inventory i ON i.flight_id = f.flight_id WHERE f.origin = 'SEA' AND f.dest = 'BOS' AND f.dep_time_utc >= '2026-11-18 08:00:00+00' AND f.dep_time_utc < '2026-11-19 08:00:00+00' AND (i.sell_limit - i.sold - i.held) >= 2 ORDER BY f.dep_time_utc;Step 2 — Hold inventory & seats (one millisecond-fast transaction on PG Primary at
READ COMMITTED):BEGIN; -- 1. Insert booking first so concurrent retries collide on UNIQUE(user_id, idempotency_key) -- BEFORE touching flight inventory. INSERT INTO booking (booking_id, user_id, status, hold_expires_at, total_price_cents, currency, idempotency_key, created_at) VALUES ($1, $2, 'HELD', now() + interval '15 minutes', 49800, 'USD', $3, now()); -- 2. Atomically reserve seats per segment (always sorted by flight_id to prevent deadlocks). UPDATE flight_inventory SET held = held + 2 WHERE flight_id = 402 AND cabin = 'Y' AND sold + held + 2 <= sell_limit; -- If affected_rows == 0 -> ROLLBACK immediately and return 409 SOLD_OUT! -- 3. Create held tickets and claim specific seats (sorted by seat_no). INSERT INTO flight_ticket (ticket_id, booking_id, flight_id, cabin, passenger_id, status) VALUES ($4, $1, 402, 'Y', $5, 'HELD'), ($6, $1, 402, 'Y', $7, 'HELD'); INSERT INTO seat_assignment (flight_id, seat_no, ticket_id) VALUES (402, '12A', $4), (402, '12B', $6); -- If PRIMARY KEY (flight_id, seat_no) conflicts -> ROLLBACK and return 409 SEAT_TAKEN! COMMIT;Step 3 — Authorize, confirm, and capture payment (never hold a DB lock across network calls!): 1. Atomically transition
HELD -> PAYINGso the expiry sweeper cannot steal the seats mid-payment:UPDATE booking SET status = 'PAYING' WHERE booking_id = $1 AND status = 'HELD' AND hold_expires_at > now();(if0rows updated, return410 HOLD_EXPIRED). 2. Call the external payment gateway to authorize (reserve funds) usingbooking_id+ attempt as the idempotency key. If declined, setstatus = 'HELD'so the user can try another card. 3. Once authorized, commit confirmation in a single guarded CTE so even racing retries or background reconcilers moveheld -> soldat most once:WITH confirmed AS ( UPDATE booking SET status = 'CONFIRMED' WHERE booking_id = $1 AND status = 'PAYING' RETURNING booking_id ), moved_inventory AS ( UPDATE flight_inventory SET held = held - 2, sold = sold + 2 WHERE flight_id = 402 AND cabin = 'Y' AND EXISTS (SELECT 1 FROM confirmed) ) INSERT INTO outbox (topic, payload, created_at) SELECT 'booking.confirmed', $2::jsonb, now() FROM confirmed;- Finally, capture the authorized payment. (If cancelling later, a similar guarded transaction decrements
soldand deletes theseat_assignmentrows so12Aand12Breopen.)
Step 4 — Expiry sweeper: Every 30 s, workers run
SELECT booking_id FROM booking WHERE status = 'HELD' AND hold_expires_at < now() LIMIT 500 FOR UPDATE SKIP LOCKED, settingstatus = 'EXPIRED', subtractingheld, and deletingseat_assignmentrows.SKIP LOCKEDlets multiple sweeper workers run in parallel without blocking one another.- Finally, capture the authorized payment. (If cancelling later, a similar guarded transaction decrements
Part A deep dive: Preventing double booking under heavy contention
Why does the naive "count tickets, then insert" pattern fail even inside a transaction?
BROKEN ("read-then-insert" write skew on a 180-seat cabin with 179 sold): Tx 1: SELECT count(*) FROM flight_ticket WHERE flight_id = 402; --> sees 179 (< 180) Tx 2: SELECT count(*) FROM flight_ticket WHERE flight_id = 402; --> ALSO sees 179 (< 180)! Tx 1: INSERT INTO flight_ticket ...; COMMIT; --> 180 tickets Tx 2: INSERT INTO flight_ticket ...; COMMIT; --> 181 tickets (OVERSOLD!)Because both transactions insert brand-new rows, neither locks anything the other reads! Even PostgreSQL's
REPEATABLE READisolation allows this classic write skew anomaly.How our design eliminates double booking and survives a 20,000-buyer flash sale:
- Cabin level — Atomic conditional
UPDATEatREAD COMMITTED: When Tx 1 runsUPDATE flight_inventory SET held = held + 2 WHERE flight_id = 402 AND cabin = 'Y' AND sold + held + 2 <= sell_limit, PostgreSQL acquires a row-level write lock on(402, 'Y'). Concurrent Tx 2 pauses on that lock until Tx 1 commits (~5 ms), then PostgreSQL automatically re-evaluates theWHEREclause against Tx 1's newly committed values. If only 1 seat remains,sold + held + 2 <= sell_limitevaluates tofalse,0rows update, and Tx 2 cleanly returns409 SOLD_OUT. - Seat level — Unique B+tree index: Inserting
(402, '12A')intoseat_assignmentlocks that unique key slot in the B+tree leaf; a simultaneous insert for12Awaits until Tx 1 commits and immediately fails with a unique-constraint error (409 SEAT_TAKEN). - Protecting the database during a 20,000-user flash sale: One hot row can commit ~200 transactions/s (
5 mseach)—plenty to sell all 180 seats in < 1 second, unless 20,000 blocked HTTP threads exhaust PostgreSQL's connection pool first! We place a lightweight Redis admission counter (flight:402:Y:avail, refreshed from PG every 10 s) in front of the DB:DECRBYrejects excess callers #181–#20,000 in sub-millisecond memory with409 SOLD_OUTbefore they ever open a PostgreSQL transaction, while PostgreSQL remains the strict source of truth for the ~180 admitted requests. (Alternative if every flight were constantly hot: pre-create 180 individual seat rows per flight and claim seats viaSELECT ... WHERE status = 'FREE' LIMIT 2 FOR UPDATE SKIP LOCKED, trading ~3.3B database rows/year for lock-free row parallelism.)
- Cabin level — Atomic conditional
Part B: Voting API, high-level architecture, and data flow
API contract
POST /v1/polls/{poll_id}/votes Authorization: Bearer <signed_jwt> { "option_id": "mango-habanero", "vote_id": "9c4f2a..." } -- client UUID reused on retries -> 202 Accepted { "status": "RECORDED" } -- durable in Kafka; tallied async -> 400 UNKNOWN_OPTION | 403 POLL_CLOSED | 429 RATE_LIMITED | 503 TRY_AGAIN (jittered Retry-After) GET /v1/polls/{poll_id}/results -- static JSON served by CDN (1 s TTL) -> 200 { "poll_id": "p4", "status": "OPEN", "as_of": "2026-03-15T01:18:42Z", "options": [{ "id": "mango-habanero", "votes": 1418920 }, ...], "total": 5840112 }End-to-end streaming architecture
Viewer Phones (3M/s burst) Scoreboard Viewers (10M concurrent) | POST /votes | GET /results every 2 s v v [ Edge WAF / Per-IP Rate Limit ] [ Global CDN (TTL = 1 s) ] | ^ (~1 req/s per edge POP) [ Regional ALB ] [ S3 Object: results.json ] | ^ overwritten every 1 s v | [ Vote API Pods on EKS (360 pods) ] [ Board Publisher (leader + standby) ] - Verify JWT locally (cached public key) ^ - Stamp server received_at | reads snapshot - Produce keyless batches (acks=all) | | | v | [ Kafka "votes" (120 partitions, RF=3) ] ---> [ Flink Stream Job (120 parallel tasks) ] | 1. keyBy(poll_id, user_id): keep earliest vote v 2. Pre-aggregate +1/-1 flavor deltas per 1 s [ S3 Raw Archive (audit & exact recount) ] 3. Flush snapshot -> [ Redis ] & [ TSDB ]Why the client app is part of the architecture: On first tap, the mobile app immediately renders the checkmark locally and disables rapid re-tapping; if it receives
503or a network timeout, it retries silently in the background with the samevote_idusing exponential backoff + random jitter so millions of phones never synchronize into retry waves. Votes stamped withreceived_atbefore poll close count even if stream processing lags by a few seconds.Part B deep dive: Kafka internals and durable burst absorption
Kafka acts as our shock absorber: it turns a sudden 3,000,000-vote/s network burst into fast sequential disk writes, decoupling user-facing latency (
< 100 ms) from downstream deduplication speed.- Partitions and sequential segment files: Topic
votesis split into 120 partitions spread across 15 brokers. Each partition is an append-only log stored on disk as 1 GiB segment files with sparse offset and timestamp indexes. Because appending to the end of a file is sequential I/O and consumers tailing live votes read straight from the Linux OS page cache in RAM without disk seeks, 15 brokers easily sustain390 MB/sin (~1.2 GB/sreplicated). - Replication, ISR, and durability (
acks=all): Each partition has 1 leader and 2 followers across 3 Availability Zones (replication.factor = 3). Caught-up replicas form the In-Sync Replica set (ISR). Settingacks=allandmin.insync.replicas=2means the leader acknowledges a vote only after at least 2 zones have written it, andunclean.leader.election.enable=falseforbids an out-of-date broker from becoming leader and losing acknowledged votes. Consumers only read up to the high watermark (the last offset replicated across the ISR). That cross-AZ hop adds ~2–4 ms—well inside our 100 ms budget. - Why we produce without a partition key (sticky partitioner): This is a crucial throughput insight! A Kafka producer groups records waiting up to
linger.ms = 5into compressedLZ4batches per partition:- If we keyed by
option_id(8 promotional flavors): Only 8 of our 120 partitions would ever receive traffic! - If we keyed by
user_id: One API pod handling8,333 req/sspreads~42records per5 msacross 120 partitions = 0.35 records per batch! Brokers would burn CPU on 1-record batch headers and CRC checks with zero compression benefit. - Keyless sticky partitioner (chosen): Each pod packs all
~42records arriving during5 msinto one single batch for one partition before rotating—~40x fewer batches and tightLZ4compression! Flink'skeyBy(poll_id, user_id)then performs a single fast streaming shuffle downstream to co-locate each user's repeat taps.
- If we keyed by
- Producer idempotence vs. user deduplication:
enable.idempotence=trueassigns each producer a sequence number so broker retries never duplicate a batch. However, a phone retrying over cellular creates a new HTTP call—which is why Flink deduplicates by(poll_id, user_id)next.
- Partitions and sequential segment files: Topic
Part B deep dive: Real-time counters and time-series database internals
Why stream pre-aggregation beats shared Redis counters: Calling
INCRon 8 Redis keys 3,000,000 times/s overwhelms a single-threaded Redis shard (~150k ops/s), and even sharded Redis counters still need 3,000,000SET NXcalls/s to deduplicate 40M users! Instead, each of Flink's 120 parallel tasks holds ~20 MB of local RocksDB state (40M users / 120) and flushes aggregated flavor deltas once per second (<= 120 × 8 = 960tiny numbers/s total, regardless of whether traffic is 50k/s or 3M/s!).Because keyless Kafka partitions can deliver two taps from the same user slightly out of order, Flink ranks each user's taps by
(received_at, vote_id)so both live streaming and offline S3 recounts produce the exact same winner:def process_vote(user_state: dict, vote: dict, pending_deltas: dict) -> None: """Keep each user's earliest vote per poll; emit +1/-1 flavor adjustments.""" user_key = (vote["poll_id"], vote["user_id"]) incoming_rank = (vote["received_at"], vote["vote_id"]) previous = user_state.get(user_key) if previous is None: # First time seeing this user in this poll: count +1 for their chosen flavor. user_state[user_key] = (incoming_rank, vote["option_id"]) flavor_key = (vote["poll_id"], vote["option_id"]) pending_deltas[flavor_key] = pending_deltas.get(flavor_key, 0) + 1 return best_rank, counted_option = previous if incoming_rank >= best_rank: # Repeat tap or later timestamp -> ignore completely. return # Earlier tap arrived slightly out of order from another Kafka partition -> swap! user_state[user_key] = (incoming_rank, vote["option_id"]) if vote["option_id"] != counted_option: old_key = (vote["poll_id"], counted_option) new_key = (vote["poll_id"], vote["option_id"]) pending_deltas[old_key] = pending_deltas.get(old_key, 0) - 1 pending_deltas[new_key] = pending_deltas.get(new_key, 0) + 1Crash-safe snapshots: Flink checkpoints its RocksDB map, running totals, and Kafka offsets together to S3 every 10 s. Downstream, Flink overwrites Redis with the entire totals JSON (
SET, neverINCR) tagged with Flink's event-time watermark (as_of—the timestamp up to which all partitions have caught up). The Board Publisher only writesresults.jsonto S3 ifas_ofmoved forward, so a Flink restart pauses the board briefly instead of ever making vote counts jump backward!Time-series modeling & TSDB internals: - Two read shapes: Redis serves the 8 running totals; a Time-Series Database (TSDB) stores per-second velocity (
votes_per_second{poll="p4", option="mango-habanero", region="us-east"})—just8 × 3 = 24series (24 points/s), never tagging high-cardinalityuser_id! - How a TSDB works under the hood: Modern TSDBs indexmetric + tagsin an inverted index (mapping each tag likeoption="mango-habanero"to matching series IDs—which is why millions of uniqueuser_idtags blow up RAM). Incoming points append to a sequential Write-Ahead Log (WAL) and an in-memory chunk compressed with Gorilla encoding: timestamps store delta-of-deltas (~1 bit when spaced 1 s apart) and values store XOR differences (~1–2 bytes per sample total!), flushing immutable 2-hour disk blocks that age out cheaply by dropping whole directories. - Picking the right TSDB: Bucket velocity by event time (received_at), not wall-clock processing time, so temporary Kafka lag doesn't draw a fake dip-and-spike on the TV chart. Because late votes update a prior second's bucket, write business vote rates to InfluxDB or TimescaleDB (which support upserts/overwrites by(series, timestamp)), while keeping Prometheus (whose append-only head rejects overwritten timestamps) for cluster ops metrics like CPU and Kafka lag.Part B: EKS deployment, spike autoscaling, and failure handling
Why reactive Kubernetes autoscaling alone fails a 30-second TV spike: When an announcer yells "Vote now!", traffic jumps from
50k/sto3M/sin 3 seconds. Kubernetes's Horizontal Pod Autoscaler (HPA) polls metrics every15 s, and launching new EC2 nodes via Karpenter takes60–90 s. Relying on reactive autoscaling means dropping the entire commercial!EKS production playbook: - Scheduled pre-scaling + warm overprovisioning: 30 minutes before airtime, a scheduled job sets Vote API
minReplicas = 360across 3 Availability Zones, backed by low-priority "pause" placeholder pods reserving 20% extra node capacity for instant preemption if HPA needs even more pods. - Pre-warm cloud bottlenecks outside Kubernetes: Pre-warm AWS Application Load Balancers (cold ALBs throttle sudden step-jumps), verify EC2 vCPU quotas, and size VPC subnets with enough IP addresses—on EKS, the VPC CNI assigns a real VPC IP to every pod, so small/24subnets run out of IPs long before nodes run out of CPU! - Pod-level load shedding: Cap each Vote API pod at2,000concurrent requests; reject #2,001 immediately with503+ jitteredRetry-Afterso mobile clients retry smoothly with the samevote_id. - Fixed-size stateful tiers + deploy freeze: Pre-provision the 15-broker Kafka cluster (KRaft metadata quorum) and run Flink at fixedparallelism = 120throughout the broadcast—resizing Kafka partitions or Flink parallelism mid-spike copies state or pauses consumption. Freeze code deploys during the event after passing a 4.5M req/s (1.5x) end-to-end load test.Failure mode System impact & automated recovery Part A: Payment gateway times out Booking stays in PAYING; background reconciler queries provider by idempotency key every 60 s to either confirm+capture or revert toHELD/EXPIREDPart A: PG Primary crashes Synchronous standby in AZ 2 promotes with zero lost bookings ( RPO = 0); clients retry503safely usingIdempotency-KeyPart B: One entire AZ fails mid-burst Kafka ( RF=3,min.insync.replicas=2) keeps accepting writes; surviving API pods shed ~20% excess with503(or pre-scale 450 pods to absorb full AZ loss)Part B: Flink task crashes Votes buffer safely in Kafka; Flink restores last 10-s S3 checkpoint and catches up within seconds without double-counting ( SET+as_ofwatermark guard)Part B: Redis or Publisher down CDN serves last good results.jsonviastale-if-error; official winner is verified afterward by batch-recounting the raw S3 vote archive
Intuition & how it works
These two systems teach opposite halves of distributed systems design:
- Part A (Flight Booking) is like assigning physical seats in a theater: only ~60 buyers check out per second globally, yet we can never hand seat
12Ato two people or sell 181 tickets for a 180-seat cabin. Every reservation must serialize cleanly through one authoritative database check without holding locks while a shopper types their credit-card number. - Part B (Live Event Voting) is like measuring a stadium applause surge from 3,000,000 phones during a 30-second commercial: nobody cares if the TV scoreboard trails real life by 1.5 seconds, as long as tapping feels instant (
< 100 ms), zero accepted votes disappear, and 10,000,000 viewers refreshing the board never touch our database.
Naive designs fail both tests in complementary ways. In Part A, running SELECT count(*) and then INSERT lets two simultaneous buyers both read 179 < 180 and both insert—overselling the plane—while keeping a SQL transaction open during card payment locks out every other traveler for minutes. In Part B, calling INCR on 8 flavor keys in Redis 3,000,000 times per second overwhelms a single-threaded Redis shard (~150k ops/s ceiling), and relying on reactive Kubernetes autoscaling misses a 30-second TV spike because new cloud VMs take over a minute to boot.
Trace how both architectures handle contention effortlessly:
- Two travelers chase the last seat (
12A) on Flight 402 (SEA->BOS): Both sendPOST /v1/bookingswith an idempotency key (a client-generated UUID that prevents duplicate bookings on retry). PostgreSQL executesUPDATE flight_inventory SET held = held + 1 WHERE flight_id = 402 AND cabin = 'Y' AND sold + held + 1 <= 180inside a 5-millisecond transaction. Traveler A's update incrementsheldto180and inserts(402, '12A')intoseat_assignmentwith a 15-minutehold_expires_attimestamp; Traveler B'sUPDATEre-evaluatesWHEREafter A commits, matches0rows, and immediately returns409 SOLD_OUT—zero locks held while Traveler A pays! - Viewer U taps
"mango-habanero"twice during a 3M/s spike: Pre-scaled Vote API pods verify U's JWT in memory, stampreceived_at, pack ~42 keyless votes per 5 ms into one compressed Kafka batch (acks=allacross 2+ zones), and return202 Acceptedin ~15 ms. Downstream, 120 parallel Flink tasks shuffle by(poll_id, user_id), keep U's earliest(received_at, vote_id)once, flush net+1flavor counts once per second to Redis and a time-series DB, and write a staticresults.jsonserved to 10M viewers from CDN edge caches (TTL = 1 s).
Key trade-offs
- Per-cabin counter + sparse
seat_assignmentvs. pre-creating one row per physical seat (Part A). A single(flight_id, cabin)counter row makes availability reads cheap and enforcessold + held <= sell_limitin one atomicUPDATE, while inserting only taken seats intoseat_assignmentguarantees seat uniqueness. Pre-creating 180 seat rows per flight withFOR UPDATE SKIP LOCKEDeliminates hot-row serialization during flash sales, at the cost of ~3.3 billion rows per year; a lightweight Redis admission counter in front of the cabin row gets the best of both worlds. - Atomic conditional
UPDATEatREAD COMMITTEDvs.SERIALIZABLEtransactions (Part A).SERIALIZABLEisolation catches multi-row anomalies automatically, but aborts contending transactions and forces client-side retry loops during fare sales. Encodingsold + held + n <= sell_limitinside a singleUPDATEatREAD COMMITTEDlets PostgreSQL queue concurrent updaters briefly and re-evaluate the condition without spurious aborts. - Time-bounded data holds vs. database locks across payment (Part A). Recording
status = 'HELD'andhold_expires_atin tables lets a 15-minute checkout survive server restarts without blocking other buyers, trading away simplicity for a background expiry sweeper, an intermediatePAYINGlock-out state, and a payment reconciler. - Authorize -> DB confirm -> Capture vs. single-step charge (Part A). Splitting card payment into reserve (
authorize) and finalize (capture) adds one extra payment API call, ensuring that if anything crashes mid-checkout, reserved funds simply void rather than charging a customer without issuing a ticket. - Keyless Kafka batches + Flink shuffle vs. keying Kafka by
user_id(Part B). Keying Kafka records byuser_idsends each user's taps to one partition automatically, but scatters each pod's traffic across 120 partitions into tiny ~1-record batches. Using Kafka's sticky partitioner (no key) packs ~40–50 records per batch for high broker throughput andLZ4compression, paying just one internal network shuffle inside Flink. - Stream pre-aggregation vs. shared Redis counters (Part B). Counting locally inside 120 Flink tasks collapses 3,000,000 writes/s into
<= 960per-second delta updates and handles 40M-user deduplication in partitioned RocksDB memory, trading instant sub-millisecond counter visibility for a harmless 1–2 second scoreboard lag. - Static
results.jsonon a CDN vs. WebSockets push (Part B). Pushing live updates over 10,000,000 stateful WebSocket connections creates massive memory and reconnect-storm risk during the exact moment votes spike; a 1-second cached JSON file on a CDN absorbs 5,000,000 polls/s at the network edge with near-zero backend load. - Scheduled pre-scaling vs. purely reactive autoscaling (Part B). Paying for 360 warm API pods for an hour around a scheduled broadcast costs a few hundred dollars of extra cloud compute, buying 100% availability during the first 30 seconds before reactive pod/node autoscalers could ever launch a VM.
Common mistakes
- Using
SELECT count(*)followed byINSERTto check seat inventory, which suffers from write skew (two concurrent transactions both read179 < 180and both insert, overselling the flight even underREPEATABLE READ). - Keeping a database transaction open while calling Stripe/Adyen, tying up database connections and row locks for seconds or minutes.
- Updating
flight_inventoryduring payment confirmation without checking thatbooking.statusactually transitioned fromPAYINGtoCONFIRMED, allowing a racing retry or reconciler to decrementheldand incrementsoldtwice. - Putting range columns before equality columns in a composite B-tree index (e.g.,
(origin, dep_time_utc, dest)), or wrapping indexed columns in functions likeWHERE DATE(dep_time_utc) = ..., which breaks the contiguous B+tree leaf slice and triggers slow scans. - Calling
INCRon one Redis key per promotional flavor, bottlenecking 3,000,000 votes/s onto 8 single-threaded keys, or keying Kafka by flavor so 112 of 120 partitions sit idle. - Assuming Kafka's
enable.idempotence=truededuplicates user votes, when it only deduplicates network retries from the same producer batch—not a mobile phone sending a fresh HTTP retry after a timeout. - Bucketing vote charts by processing time or overwriting late buckets in Prometheus, causing consumer lag to draw fake traffic spikes or failing when Prometheus's append-only storage rejects updated timestamps.
- Putting
user_idorvote_idinto time-series metric tags, creating 40,000,000 distinct series (cardinality explosion) and crashing the TSDB's in-memory inverted index. - Assuming Kubernetes HPA can autoscale from 20 pods to 360 pods during a 30-second spike, or forgetting non-pod cloud limits like cold load balancers and EKS VPC subnet IP exhaustion.
Follow-up questions
- How would Part A accommodate deliberate airline overbooking targets while still guaranteeing two travelers never receive the same physical seat assignment? Our
flight_inventorytable already separates physicalcapacity(say180) fromsell_limit(say186, set by an airline's no-show prediction model). The conditional updateWHERE sold + held + n <= sell_limitenforces186atomically with zero code changes, whileseat_assignment's primary key(flight_id, seat_no)still strictly caps pre-selected seats at180. Those last 6 travelers buy confirmed cabin tickets with"seat": "ASSIGN_AT_GATE"and receive seats at check-in when no-shows open up (or receive volunteer compensation vouchers before boarding). - What changes in the Part B streaming tally if voters are permitted to switch their selected flavor while the poll remains open? In Flink's
process_votefunction, each user's keyed state already stores((received_at, vote_id), option_id)—we simply flip the comparison from keeping the smallest rank (earliest vote) to keeping the largest rank (latestreceived_atbefore poll close, breaking ties withvote_id). Whenever a newer vote picks a different flavor, Flink emits-1for the previous flavor and+1for the new flavor in that second's delta map, keeping running sums exact even if out-of-order Kafka partitions deliver an older tap afterward. Add a per-user change rate limit (e.g., 1 switch every 5 seconds) at the API tier so malicious scripts cannot spam state updates. - How would you audit and certify an exact final vote count for contest regulators once the live broadcast ends? Every vote acknowledged by Kafka is archived raw to immutable S3 Parquet/JSON files alongside the live Flink stream. Once the poll closes and Flink's event-time watermark passes the close timestamp, an offline Spark/SQL batch job reads the raw S3 archive, filters out
received_at > poll_close_atand fraud-flagged accounts, applies the identicalMIN((received_at, vote_id))deduplication rule per(poll_id, user_id), and verifies that the batch totals match the streaming totals before certifying the winning flavor.
Follow-up questions
- How would Part A accommodate deliberate airline overbooking targets while still guaranteeing two travelers never receive the same physical seat assignment?
- What changes in the Part B streaming tally if voters are permitted to switch their selected flavor while the poll remains open?
- How would you audit and certify an exact final vote count for contest regulators once the live broadcast ends?
Similar questions
- Concurrent In-Memory Publish-Subscribe Broker
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency