Imagine a fictional concert platform releasing 50,000 numbered seats. Two fans select A12 at the same moment. Both see an available seat on their screens, but only one can receive a confirmed ticket. A production booking system must reconcile fast browsing with strict ownership, temporary holds and asynchronous payment. Unlike fungible inventory, numbered seats have individual identities and customers often want adjacent seats. This tutorial builds the system from a relational transaction to a scalable event-oriented architecture.
Illustrative booking flow: the transactional database determines ownership; hold duration is configurable (five minutes in the worked example). Availability goals are design targets, not measured results.
Requirements and invariants
Support event discovery, seat-map browsing, holding one or more specific seats, payment confirmation, cancellation and ticket retrieval. Each event-seat pair can have at most one active owner. A group booking should either hold all requested seats or none. An expired hold cannot be confirmed by a late payment callback. Browsing may tolerate stale data, but a successful hold must be based on authoritative state. Define cancellation and refund policy separately from technical expiry.
RequirementMechanismExclusive seat ownershipConditional transactional writesAdjacent seatsAtomic group holdFast browsingCached seat mapPayment retriesIdempotent confirmationAbandoned checkoutExpiry and reconciliation
Capacity planning
Assume 200,000 visitors arrive in five minutes, averaging 667 arrivals per second. If each fetches the map three times, that is about 2,000 map reads per second. If 20% attempt a booking of three seats, the average write demand is 133 group holds per second or 400 seat updates per second. Actual bursts can be much higher. With a five-minute hold, 40,000 attempts could request 120,000 seats, exceeding the 50,000-seat supply. Admission control is therefore a business and correctness-adjacent concern, not just an infrastructure optimization. These figures are hypothetical planning assumptions.
Architecture evolution
Start with a single API and relational database. A transaction locks the selected seats, checks availability and records a hold. This handles modest traffic and provides a clear correctness boundary. Next separate read-heavy seat maps from transactional booking writes. A cache or CDN serves static geometry and a versioned availability snapshot. Add stateless booking replicas, a payment integration and an expiry worker. Finally partition by event when aggregate load demands it. A single blockbuster event may still require admission control because partitioning by event does not remove contention inside that event.
High-level design
ComponentResponsibilitySeat map serviceGeometry and approximate availabilityAdmission serviceBound concurrent checkout attemptsBooking APIAuthorize and allocate seatsBooking databaseAuthoritative holds and seat ownershipPayment serviceAuthorize, capture or refundExpiry workerRelease abandoned holdsOutbox relayPublish committed seat and ticket events
A client reads the seat map, selects seats and submits a stable request identifier. The booking API creates a hold and returns its expiry. The payment service processes the checkout outside the database transaction. A trusted callback triggers confirmation. An outbox event updates the cached map and ticket delivery service. If the map is stale, the booking API returns a conflict and the client refreshes availability. Never let a cache response authorize ownership.
API and low-level design
EndpointBehaviorGET /events/{id}/seatsVersioned seat mapPOST /holdsCreate atomic group holdGET /holds/{id}Return authoritative statusPOST /holds/{id}/confirmTrusted payment confirmationDELETE /holds/{id}Cancel active hold
POST /holds
Idempotency-Key: checkout-9001
{“event_id”:”concert-1″,”seats”:[“A12″,”A13”]}
201 Created
{“hold_id”:”h9001″,”state”:”HELD”,”expires_in”:300}
Scope idempotency keys to the authenticated customer or tenant. Persist a request hash so a reused key with different seats is rejected. A successful retry returns the original hold, not a new expiry window. Use server time for expiry; the client countdown is only a display. Return 409 when any requested seat is unavailable and 429 when admission limits are reached. Do not reveal another customer’s identity in conflict responses.
Database schema
CREATE TABLE holds (
id uuid PRIMARY KEY,
customer_id text NOT NULL,
request_key text NOT NULL,
request_hash text NOT NULL,
state text NOT NULL,
expires_at timestamptz NOT NULL,
UNIQUE(customer_id, request_key)
);
CREATE TABLE event_seats (
event_id text NOT NULL,
seat_id text NOT NULL,
state text NOT NULL CHECK(state IN (‘FREE’,’HELD’,’BOOKED’)),
hold_id uuid REFERENCES holds(id),
PRIMARY KEY(event_id, seat_id),
CHECK ((state=’FREE’) = (hold_id IS NULL))
);
CREATE INDEX overdue_holds ON holds(expires_at)
WHERE state=’HELD’;
Store immutable hold-seat history in a separate table if audit and customer support require it. The current seat row points to the owning hold. Keep payment transaction IDs unique and store payment status independently. For a confirmed booking, create ticket records with a unique event-seat constraint as a second line of defense. Use a separate explicit cancellation transaction if resale is permitted; do not silently overwrite historical tickets.
Atomic group booking
BEGIN;
— Insert hold with unique request key.
SELECT seat_id, state FROM event_seats
WHERE event_id = :event
AND seat_id = ANY(:seats)
ORDER BY seat_id FOR UPDATE;
— Validate exact count and all FREE; otherwise rollback.
UPDATE event_seats SET state=’HELD’, hold_id=:hold
WHERE event_id=:event AND seat_id=ANY(:seats);
— Insert hold history and outbox event.
COMMIT;
The placeholders represent bound parameters. Deduplicate the requested seat list before validation. Acquire locks in a consistent order to reduce deadlocks. If any seat is missing or unavailable, roll back the entire transaction. Never call the payment gateway while holding row locks. A duplicate request-key conflict must roll back and read the original hold in a fresh transaction. For expired holds, the simple design waits for the expiry worker to release seats; it may temporarily underutilize capacity but avoids unsafe ownership transfers.
Payment versus expiry
Use a state machine: HELD can become CONFIRMED, EXPIRED or CANCELLED. Confirmation and expiry both lock the hold row first, then its seat rows in deterministic order. After acquiring the hold lock, check the current database clock and verify the expected state. Confirmation changes seats to BOOKED and creates tickets atomically. Expiry changes only seats still owned by that hold to FREE. A repeated callback sees a terminal state and cannot allocate seats again.
Payment providers are external systems. A payment may succeed after expiry, or a capture response may be lost. Use provider idempotency keys and reconcile ambiguous payment results. Where possible authorize first, confirm the booking, then capture through a durable workflow. If capture ultimately fails, apply an explicit cancellation policy. If payment arrives after expiry, void or refund rather than taking seats from another customer. The precise compensation policy depends on the payment provider and business rules.
Scaling and technology tradeoffs
ApproachBenefitTradeoffRelational row locksSimple strict ownershipHot-row contentionConditional key-value writesHigh partition throughputGroup transaction constraintsPer-event queueControlled write pressureQueue latency and recoveryCached seat mapCheap high-volume readsStale availability
Partition by event to keep group transactions local. Very large events may be divided into seating sections, but cross-section group holds then require coordination or a restricted booking policy. A waiting room limits active checkouts and protects the database. Issue short-lived admission tokens tied to customers and events; prevent replay and avoid promising a specific seat before the hold commits. For accessibility and fairness, define how admission order and time limits work and communicate them clearly.
Failure recovery
FailureRecoveryHold response lostRetry same idempotency keyExpiry worker crashesScan overdue active holdsPayment callback duplicatedConditional state transitionCache update lostReplay outbox or rebuild snapshotTicket delivery failsRetry delivery without issuing another ticketDatabase unavailableFail closed for new holds
Use bounded expiry batches and SKIP LOCKED where appropriate. Monitor oldest overdue hold age rather than assuming a worker heartbeat means cleanup is healthy. Store outbox events in the same transaction as state changes. Consumers deduplicate by event identifier and apply seat-map updates only if their version is newer. A periodic reconciliation compares cached availability with authoritative seat rows and verifies that confirmed tickets match booked seats.
Security, observability and testing
Authenticate every hold request and enforce customer ownership. Rate-limit hold creation, cap seats per customer and prevent repeated expiry abuse. Verify payment webhook signatures and transaction references. Do not store raw payment card details. Monitor lock wait, conflict rate, hold conversion, expiry lag, payment reconciliation backlog and ticket delivery latency. Alert on any confirmed ticket duplication or mismatched ownership.
Test 100 simultaneous requests for one seat and assert exactly one successful hold. Test overlapping groups A12/A13 and A13/A14 and assert no partial allocation. Replay an idempotency key after a lost response. Race confirmation against expiry and assert one terminal state. Simulate a payment success after expiry and verify compensation. Stop the outbox relay and confirm the authoritative booking remains correct while the map catches up. Load-test a single popular event separately from evenly distributed traffic.
Interview FAQs
Why not use Redis locks alone?
A lock is not the durable ownership record. Lease expiry and failover can allow overlapping actors unless the authoritative write enforces ownership.
How do you prevent double booking?
Use a unique event-seat row and transactional conditional ownership changes, plus a unique confirmed ticket constraint.
How do you book adjacent seats?
Validate and lock the complete requested group in one transaction, rolling back if any seat is unavailable.
What if the seat map is stale?
Treat it as a browsing hint. Return a conflict from the authoritative hold API and refresh the map.
How do you handle late payments?
Check the durable hold state and compensate through void or refund if the hold is no longer valid.
Worked example: two customers, one seat
At checkout, Alice requests A12 and A13 while Bob requests A13 and A14. Alice obtains the locks first and commits her hold. Bob waits on A13, then observes its HELD state and rolls back. A14 remains free. If Alice abandons checkout, the expiry worker releases both seats together. Bob can then submit a new request key and attempt the group again. The database commit, not the time at which a browser clicked a button, determines ownership.
Suppose Alice’s payment authorization arrives after her hold expires. The confirmation transaction must reject the expired hold even if no other customer has yet claimed the seats. Otherwise the system would violate its advertised checkout deadline. The payment workflow records a void or refund request and retries it independently until the provider confirms the result.
Production deep dive: consistency and recovery
Use the primary database for ownership decisions. Read replicas may lag and are suitable for browsing, not for deciding whether a seat can be sold. In a multi-region deployment, route writes for each event to a designated leader. During failover, fence the old leader before accepting writes on the replacement. If the system cannot establish a single authoritative writer, reject new holds rather than risk selling a seat twice. This deliberately prioritizes consistency over availability for booking writes.
Define separate recovery objectives for booking records and cached seat maps. A cache can be reconstructed from committed rows, whereas losing a confirmed booking can create financial and customer support problems. Test restoration from backups and transaction logs, reconcile provider payment records after recovery, and suspend sales if ownership cannot be established. Synchronous replication can reduce data loss but increases write latency; asynchronous replication needs an explicitly accepted recovery point objective.
Interview walkthrough and follow-up questions
In a 45-minute interview, spend the first five minutes clarifying numbered versus general-admission seats, group atomicity and payment policy. Spend another five estimating peak traffic, ten on the architecture, fifteen on transactional ownership and payment races, and the remaining time on scaling and failure recovery. The strongest answer explains why the cached map is not authoritative and why a distributed lock alone cannot replace durable conditional writes.
A senior follow-up is how to handle a venue with 100,000 seats and millions of simultaneous visitors. Start with admission control and static geometry caching, measure contention per section, and only then introduce section partitioning. Another follow-up is how to handle cancellation and resale: retain immutable ticket history while enforcing uniqueness for active tickets, for example with a partial unique index. A third is how to support accessible seating: model eligibility and adjacent companion seats as explicit business constraints checked within the same allocation transaction.
Exercise: implement concurrent overlapping group holds against PostgreSQL.Inject a crash after payment authorization and before confirmation.Measure conflict rate, lock wait and expiry lag under burst traffic.
Conclusion
The key design decision is to separate fast approximate browsing from strict transactional seat ownership. Start with atomic group holds and explicit payment and expiry states. Add caching, admission control and event partitioning as traffic demands. Further reading: PostgreSQL explicit locking. Related tutorial: distributed inventory reservation.
No Responses