System Design · Worked case study
Designing a Seat Booking System
Reserve scarce seats safely under contention, expire holds, and reconcile payment outcomes without pretending inventory and a payment provider share one transaction.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Estimate search and checkout load separately, including a high-contention onsale.
- Define one authoritative seat-state transition and safe hold expiration behavior.
- Coordinate payment with inventory using idempotency, durable workflow state, compensation, and reconciliation.
Bound the inventory promise
Design assigned-seat tickets for scheduled events, with a small catalog and a large public onsale. A user can search events, select one or several seats, hold them for up to eight minutes, pay through an external provider, and receive a confirmed ticket or a clear failure. Assume 2 million registered accounts, 100,000 listed events, and 20 million seats across active inventory. Exclude general-admission capacity, resale, seat maps with arbitrary custom geometry, ticket transfer, venue entry scanning, and dynamic pricing in the initial scope. Search availability can be slightly stale, but the act of holding must be authoritative: two buyers cannot receive valid holds for one seat. The hold clock is server-owned and shown to the user as an estimate; clients cannot extend it by changing device time. A purchase can face an ambiguous payment result because a provider may process a charge while its response is lost. We therefore promise a confirmed booking only after the system has evidence of payment success and a valid seat claim. Conversely, an expired hold is not silently resurrected because a late payment webhook arrived. Product policies define whether an ambiguous charge is voided, refunded, or retried, and tell the buyer what happens.
Separate browse load from contention load
Assume 500,000 users visit a popular onsale in a 30-minute window and each makes 12 availability refreshes: 6 million reads over 1,800 seconds, about 3,333 requests/s average, with a 5× burst near 16,700/s. A much smaller fraction checks out: if 3% attempt checkout, 15,000 users make requests; if concentrated into five minutes, that is 50 checkout attempts/s average, but a single hot event with 10,000 buyers competing for 2,000 seats can create thousands of failed compare-and-set attempts. Protect the authoritative write path from read refreshes by serving cached event descriptions and approximate seat maps, while never presenting cached availability as a guaranteed reservation. Suppose one ticket row plus indexes occupies 1.2 KiB; 20 million rows are about 24 GiB before replicas, logs, and indexes. At 2.5× physical overhead, plan roughly 60 GiB for core inventory and test transaction log throughput during a hot onsale. Each successful hold adds a durable workflow record and expiration task. Size queues for webhook bursts and retry traffic; a 10× notification spike must not consume checkout database connections. Include 30% headroom over the load-tested peak, plus a controlled queue or waiting room if demand exceeds safe database concurrency.
Start with a transactional monolith and evolve narrowly
A first system can be a single web application with a managed relational database, a job worker, and an external payment provider. The application owns event validation, seat holds, booking state, and payment orchestration, while the database enforces uniqueness. This monolith avoids distributed transactions within inventory and lets a short database transaction protect the scarce seat. As traffic grows, read-heavy event search moves to a cache or search index, and checkout requests enter a waiting room before the transactional database. A separate worker fleet handles hold expiration and provider webhooks. The seat ledger stays in one authoritative database shard per event until measured write contention justifies partitioning. Splitting payment and booking services too early does not eliminate the consistency problem; it moves it into a network protocol. In the larger design, partition events by eventId so all seats for one event share transaction ownership; route an event to a home region to prevent active-active double holds. Read replicas can serve catalog information but not reservation claims. A globally distributed active-active inventory design would require consensus or disjoint inventory assignment and is not assumed. Migration begins with shadow reads and a single write owner, not two regions writing the same seats.
Searches, requests hold, confirms checkout
Rate limits and admission during onsale
Checks policy and coordinates booking workflow
Authoritative seat rows, holds, bookings, outbox
Expiry, payment request, webhook reconciliation
External authorization or capture; independent failure domain
Confirmation, expiration, and refund status
- Buyer → Edge and waiting room: browse / checkout
- Edge and waiting room → Booking application: admitted request
- Booking application → Inventory database: transactional seat claim
- Inventory database → Workflow workers: outbox workflow event
- Workflow workers → Payment provider: idempotent payment command
- Payment provider → Workflow workers: response or webhook
- Workflow workers → Inventory database: reconcile state transition
- Inventory database → Notification service: committed outcome
Represent seat state and payment intent explicitly
Expose POST /v1/events/{eventId}/holds with sorted seatIds, quantity limits, and an idempotency key. Return holdId, expiresAt, seat-version tokens, and a status; report unavailable seats without exposing another buyer's identity. POST /v1/holds/{holdId}/checkout accepts a payment method token and a stable checkout key. GET /v1/bookings/{bookingId} is the recovery path after a lost response. Webhooks are authenticated, signature-verified, and deduplicated by provider event ID. Model Event(eventId, homeRegion, saleState), Seat(eventId, seatId, state, holdId, holdExpiresAt, version, bookingId), Hold(holdId, buyerId, createdAt, expiresAt, status, idempotencyKey), Booking(bookingId, holdId, status, paymentReference), PaymentAttempt(attemptId, bookingId, providerKey, providerState, amount, currency), and Outbox(eventId, aggregateId, eventType, payload, publishedAt). A seat is available, held, or booked; enforce valid transitions in a transaction and use unique constraints to prevent two active claims. Do not store raw card data. The payment attempt and booking are related but not the same state machine: booking can be payment_pending, confirmed, cancellation_pending, or compensation_pending. Store provider references and amounts to reconcile, with immutable audit events for each transition.
http · Illustrative example; validate before production use
POST /v1/events/e_240/holds
Idempotency-Key: web-session-81:hold-2
{"seatIds":["A-12","A-13"]}
201 {"holdId":"h_92","expiresAt":"2026-11-08T21:00:00Z","status":"held","seatVersions":{"A-12":45,"A-13":19}}Trace the hold and purchase workflow
The buyer sees a cached seat map, selects seats, and asks for a hold. In a short transaction, the application locks selected seat rows in a deterministic order, verifies each is available or safely expired, and changes them to held with a server timestamp, expiration, hold ID, and incremented version. It commits before telling the client the hold succeeded. Checkout first verifies the hold belongs to that buyer and remains valid. The service records a payment attempt and outbox command, then a worker calls the provider with a stable idempotency key. The provider may return success, decline, timeout, or an ambiguous result. A successful response or verified webhook is not enough by itself: a reconciliation worker checks that the hold is still valid and the seat versions still match. If so, one local transaction changes all seats to booked and the booking to confirmed. If the hold expired or was replaced, the workflow must not steal seats back; instead it issues a void or refund according to provider state and records compensation_pending until confirmed. The client polls or receives a notification, but GET booking state remains authoritative. An expiry worker queries due holds and conditionally releases only rows whose hold ID, state, and version still match; a stale expiry task cannot release a newer hold.
Client supplies idempotency key and seat set
Lock rows, assign expiry and fencing versions
Persist booking and payment attempt before external call
Success, decline, timeout, duplicate webhook
Check current hold owner, expiry and versions
Atomically book seats after successful payment evidence
Keep seats released if claim expired; retry and reconcile
- Hold request → Conditional claim: authorized seat IDs
- Conditional claim → Checkout pending: committed hold
- Checkout pending → Provider outcome: idempotent external command
- Provider outcome → Reconcile claim: response or webhook
- Reconcile claim → Confirmed: valid fenced claim
- Reconcile claim → Void or refund: hold no longer valid
- Provider outcome → Reconcile claim: periodic reconciliation
Handle contention, expiry, and late payment honestly
The central invariant is one live owner per seat. Enforce it in storage, not with a prior availability read. A transaction can lock the target rows and verify state; a conditional update such as state=available AND version=expected can also reject stale claims. When several seats are selected, acquire locks in stable sorted order to reduce deadlocks, and fail the whole requested set if any seat cannot be held. Expiry is a transition with a race: a buyer may begin checkout at 7:59, a provider may authorize at 8:00:03, and an expiry worker may release at 8:00. Define the authoritative deadline at the database and require finalization to compare server time and hold generation. Once the hold has expired and another buyer can claim the seat, a late payment cannot confirm the old booking. Void an uncaptured authorization when possible; if captured, issue a refund and keep the booking unconfirmed until the provider confirms the compensation. Retries reuse one provider idempotency key per payment attempt, while a deliberate new attempt gets a new attempt record and key. Webhook delivery is at least once and can be out of order; store provider event IDs and fetch current provider state when transitions conflict. Run a periodic reconciliation for attempts stuck in pending, do not infer success from a browser redirect, and expose an operational queue for unresolved money-versus-inventory mismatches.
- No distributed transaction spans the relational database and a payment provider; use a durable state machine and compensating actions.
- Never let an expired hold regain authority merely because an old payment response arrived late.
Plan for provider, database, and region failures
If the payment provider times out, keep the payment attempt in unknown or pending rather than creating a second charge. Query provider state by idempotency key or payment reference, and reconcile asynchronously. If the provider is unavailable, preserve the hold only until its explicit deadline; extending it requires a product policy and a fresh conditional state transition, not an implicit retry. If the database fails, stop new holds and display a retryable status. An in-memory seat claim is unsafe. During an onsale, admission control can queue buyers fairly and cap concurrent transactions; the queue must not promise a seat. If the home region fails, the event's inventory owner should be fenced before a replica is promoted. With asynchronous replication, acknowledged holds or bookings can be lost; a recovery point objective and buyer remedy must be stated. A simpler design keeps event inventory in one region and restores there, accepting longer outage rather than risking duplicate sales. Cross-region catalog and read replicas are safe only if marked non-authoritative. Backup restoration must include booking rows, payment references, idempotency records, and outbox state, followed by provider reconciliation before reopening checkout. A partial webhook outage is recoverable if raw authenticated events are retained or the provider can replay them. Monitor hold expiry backlog; a delayed expiration worker may reduce sellable inventory but must never release a seat based on stale state.
| Incident | Safe response | Re-entry condition |
|---|---|---|
| Provider timeout | Keep attempt unknown; reuse provider key and query status | Provider state and local booking reconciled |
| Inventory database outage | Disable holds and checkout; preserve read-only catalog | Write owner recovered and invariants checked |
| Region promotion | Fence previous owner; document async replication RPO | Single writer and reconciliation complete |
Protect money, accounts, and fair access
Authenticate checkout and bind every hold to a buyer account or explicitly supported guest token. Verify ownership on hold lookup, cancellation, and booking retrieval; opaque IDs are not access control. Accept only payment tokens from a compliant provider integration and never log secrets or payment credentials. Validate currency and amount on the server from the event price version; do not trust a client-supplied total. Protect webhooks with signature verification, timestamp tolerance, replay deduplication, and secret rotation. Abuse controls include per-account hold counts, per-event velocity limits, bot signals, waiting-room tokens, and device/network risk scoring with appeal paths. Do not let a single IP limit block a school or household unfairly. Prevent seat-hoarding by limiting simultaneous holds and releasing abandoned holds on a clearly stated timer. Audit privileged inventory overrides and provide dual approval for bulk seat changes. Minimize personal data in event analytics, set retention for abandoned checkout attempts, and separate payment-provider data from event-attendance profiles. Avoid exposing exact remaining inventory when that detail enables scraping or scalping; coarse availability can serve browsing while the transactional hold decides truth. Security tests should attempt simultaneous same-seat claims, cross-account hold access, webhook replay, modified price values, cancellation after capture, and a stale expiry task against a newer hold.
- Use step-up verification for risky account or payment changes.
- Document the provider's responsibilities and the service's own payment-data boundaries.
Measure successful outcomes, not just HTTP responses
A hold success indicator is successful authoritative claims divided by valid admitted hold attempts, with conflict responses reported separately from service errors. An initial objective might be 99.95% successful processing of valid hold requests and p99 hold latency under 300 ms outside deliberate waiting-room time. Checkout completion is not the same as API availability: measure time from checkout intent to confirmed, declined, or clearly pending outcome, and the proportion reconciled within five minutes. Track double-booking invariant violations with a target of zero, expired-but-still-held seats, holds released late, provider unknown-state age, refund backlog, webhook signature failures, deadlocks, lock wait time, and queue depth. Measure these by event and region but avoid high-cardinality buyer labels. The system should display known uncertainty rather than converting a pending payment into an error that encourages another charge. Error-budget policy should account for onsale windows: a short event-specific outage can have much higher user impact than the same number of errors spread over a month. Synthetic tests should attempt parallel holds for one seat and verify exactly one succeeds, then simulate payment success after expiry and verify no booking is confirmed. Restore and failover exercises should reconcile against provider sandbox records.
| Indicator | Boundary | Initial target |
|---|---|---|
| Hold claim latency | Admitted request to committed seat claim | p99 < 300 ms excluding queue wait |
| Payment resolution | Checkout intent to terminal or explicitly pending state | 99% resolved or explained within 5 minutes |
| Double booking | Conflicting confirmed seat ownership | Zero detected violations |
Compare costs and migrate without double writers
A hypothetical peak onsale budget might allocate $14,000/month to a relational database with synchronous same-region standby, backups, and enough write IOPS; $5,000 to application and queue workers; $4,000 to broker and scheduled expiration; $6,000 to edge admission, cache, logs, and monitoring; and $3,000 to cross-region replicas and recovery exercises. That is roughly $32,000/month excluding payment processing fees, support staff, taxes, and unexpected traffic. The cost is dominated by keeping authoritative write capacity available, not by storing event descriptions. A managed ticketing platform could be cheaper and safer if its inventory semantics and provider contract match the product; a custom transactional store is justified only by unique requirements. Migration from a single application to partitioned event ownership begins by adding eventId routing metadata and measuring hottest-event transactions. Copy data and shadow-read, then move one event into a new shard while preserving exactly one writer. For payment workflow extraction, write durable outbox commands before the worker calls the provider and ensure old code cannot issue the same attempt. Rollback re-routes reads and new holds to the former owner only after draining active holds or retaining compatible state. Interview alternatives include serializing each event through an actor or queue, which simplifies order but introduces queue latency and a hot key, and pre-allocating disjoint seat ranges to regions, which reduces coordination but can strand inventory.
- Cost per successful booking should include failed contention attempts, provider fees, and reconciliation labor.
- A waiting room controls admission; it does not itself make seat allocation correct.
- Interview follow-ups: define anti-sniping extension policy, behavior when every payment attempt declines, whether inventory may be split across regions, and how to settle disputes about deadline boundaries.
Make operator actions safe during an onsale
A runbook should separate actions that preserve safety from actions that restore throughput. If conflict rates rise, first lower admission concurrency and inspect lock waits, database saturation, and the hottest event; do not weaken the seat uniqueness rule. If expiry processing falls behind, report the inventory as conservatively unavailable until conditional expiration catches up rather than freeing seats from an approximate cache. If provider reconciliation accumulates, stop blind retries and group attempts by provider state and age. Operators need a read-only view of seat owner, hold generation, deadline, booking state, payment reference, webhook history, and last reconciliation, with narrowly scoped audited buttons for retry, void, refund, or manual release. A manual seat release must compare the expected hold version and require a reason; otherwise an operator could undo a buyer's newer claim. During a major incident, product support needs a consistent buyer message for pending charges, delayed confirmations, and refunds. After recovery, review a sample of event histories against provider statements and publish an incident summary that distinguishes confirmed double booking from a delayed status update. Practice this procedure before the first high-demand event, including an operator who did not design the service.
Terms in plain language
- Hold
- A time-limited, exclusive claim on a seat that blocks competing buyers while payment is attempted.
- Fencing generation
- A version that prevents an expired hold owner from later committing a stale seat update.
- Compensation
- A new business action that offsets a completed action, such as refunding a captured payment after a booking cannot be finalized.
- Reconciliation
- A repeated comparison of local booking state with payment-provider records to resolve ambiguous or missed notifications.
Capacity lab
Change the assumptions and inspect the math. This teaching model assumes every request creates one stored record. Real systems separate reads, writes, uploads and background work.
- Average QPS
- 231.48
- daily users × requests per user / 86,400
- Peak QPS
- 1,157.41
- average QPS × peak multiplier
- Peak payload bandwidth (MB/s)
- 1.16
- peak QPS × bytes/request / 1,000,000
- Logical retained storage (GB)
- 600
- requests/day × bytes/request × retention / 1,000,000,000
- Replicated storage (GB)
- 1,800
- logical storage × stored copies
- Serving nodes
- 1
- ceil(peak QPS / (node throughput × utilization))
Decimal MB/GB, not MiB/GiB. Indexes, protocol overhead, compression, retries, backups and failover capacity are excluded. Measure throughput on your workload; this is not a sizing guarantee or a cloud price quote.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Describes database row/table locking mechanisms relevant to the invented seat-claim transaction; it does not verify this workflow.
Documents one provider's idempotency behavior, not a distributed transaction or a guarantee for every payment provider.
Explains saga and compensation concepts used as general references; the seat and payment state machine here is hypothetical.