Design a Virtual Waiting Room: From Flash-Sale Traffic to Fair Admission Control

Tags:

Illustrative alternative capacity scenario: five-minute sessions permit 100 admissions per minute; the article below uses two-minute sessions. Queue position and ETA shown are illustrative only.

Intermediate · 15-minute learning guide · Prerequisites: HTTP, Redis, queues and basic distributed systems.

Imagine a ticket sale opening at noon. Two hundred thousand fans arrive in one minute, but your checkout can safely handle only 500 active sessions. Adding servers may help the website, but cannot create more seats or remove contention on inventory. A virtual waiting room controls admission before expensive work begins. This is a hypothetical ticketing scenario, not a claim about a particular company’s architecture.

What are we designing?

Functional requirements

Join once and receive a signed queue tokenCheck queue status and receive admissionExpire unused admission passes and prevent replay

Non-functional requirements

Bound origin load even during a surgeFair ordering within a defined policyRecover from failures without double admission

Step 1: Start simple, then break the design

A single server with an in-memory FIFO queue is easy to implement. It loses state on restart and cannot coordinate multiple replicas. Moving the queue into Redis gives shared state, but a naive read-then-remove operation races when two workers admit the same user. Use an atomic transition instead. Finally, put the waiting room at the edge so rejected traffic never reaches checkout.

VersionWhat improvesRemaining riskIn-memory FIFOSimple orderingRestart loses queueShared sorted setCross-replica orderingHot shard and failoverEdge gate + atomic leasesBounded origin loadLease reconciliation and regional fairness

Capacity planning: do the math

Assume 200,000 arrivals in 60 seconds, or about 3,333 joins/s. Polling every 10 seconds creates up to 20,000 status requests/s at peak queue size. If 500 active sessions last 120 seconds on average, steady admission is approximately 4.17 users/s, or 250/minute. At that rate 200,000 users would take roughly 13.3 hours to admit; the product must communicate limited inventory and close the queue when sold out. These are illustrative estimates, not measured production capacity.

QuantityEstimatePeak joins3,333/sStatus polling20,000/sActive session limit500Steady admissions4.17/sQueue metadata at 256 bytes/user51.2 MB raw, excluding datastore overhead

High-level architecture

Edge gateway validates queue and admission tokens before forwarding requests.Join service deduplicates requests using a stable event/user key.Queue store tracks ordered entries and active admission leases.Admission controller observes checkout health and atomically grants available slots.Checkout validates admission and separately performs transactional inventory reservation.

Low-level design and API

EndpointBehaviorPOST /events/{id}/joinIdempotent join; returns signed queue tokenGET /events/{id}/statusReturns state, approximate position and retry intervalPOST /events/{id}/claimExchanges eligible queue token for short-lived admissionPOST /events/{id}/releaseIdempotently releases active lease

Store event ID, opaque user ID, monotonic sequence, state, lease expiry and token nonce. Use server-generated sequence numbers, not client timestamps. Keep queue tokens separate from admission tokens; sign both, bind them to event and session, and never trust a client-provided queue position.

Atomic admission: practical pseudocode

ATOMIC(event):
expire_old_leases(event)
if active_count(event) >= safe_limit(event):
return NONE
user = first_waiting_user(event)
if user is NONE:
return NONE
transition(user, WAITING, ADMITTED)
create_lease(user, expiry=now + 120s)
return user

Implement this with a Redis Lua script on colocated keys or a transactional database. Keep expiration cleanup bounded per invocation. The admission state and lease must commit together; token delivery can be retried idempotently. This pseudocode illustrates the invariant rather than a complete runnable implementation.

Design patterns and trade-offs

PatternWhy use itTrade-offAdmission controlProtect downstream capacityUsers waitLeaseReclaim abandoned sessionsExpiry and clock handlingIdempotencySafe retriesDeduplication storageFeedback controlAdapt to latency and errorsOscillation if poorly tunedCircuit breakerStop admission during outagesLonger queues

Production failure scenarios

Redis unavailable: fail closed for new admissions; define whether existing signed passes remain valid.Worker crashes after granting: recover from durable admission state and retry token delivery.Checkout slows: reduce admissions using latency and error signals with hysteresis.Bots: rate-limit joins, apply risk-based challenges, and avoid IP-only identity.Inventory sells out: stop new admission and notify queued users; a pass never guarantees a ticket.

Testing and observability

TestExpected result10,000 concurrent claimsNo duplicate lease and no capacity overshootRetry join after timeoutSame queue identityWorker crash after commitAdmission recoverableOrigin latency spikeAdmission rate decreasesExpired or replayed tokenRejected at edge

Monitor queue depth, join latency, admission rate, active leases, checkout p95 latency, error rate, abandonment and fairness by cohort. Alert on invariant violations rather than only CPU usage.

Real-world reference

Cloudflare documents a Waiting Room product that protects origins by controlling active users and new users per minute. Its public documentation is a useful comparison point, not evidence that it uses the exact internal architecture proposed here. See Cloudflare Waiting Room documentation.

How to answer in a 45-minute interview

TimeFocus0–5 minClarify fairness, capacity, inventory and geography5–10 minEstimate joins, polling and admission rate10–20 minDraw edge, queue and checkout architecture20–30 minExplain atomic leases and token validation30–40 minDiscuss failure, sharding and feedback control40–45 minSummarize trade-offs and test invariants

Interview pitfalls to avoid

Start by distinguishing a waiting queue from an admission lease. Tell the interviewer which invariant you protect: active sessions must never exceed the safe limit. Avoid promising exact global FIFO or exact waiting times without discussing coordination costs. For advanced designs, explain how failover can invalidate lease assumptions and how fencing or reconciliation protects downstream operations.

Interview questions and answers

Why not just autoscale checkout?

Inventory contention and downstream limits may remain even when compute scales. Admission control bounds the demand.

How do you prevent duplicate admissions?

Use atomic state transitions and idempotent token issuance tied to a durable lease.

Is global FIFO necessary?

Only if the product requires it. Regional queues improve scalability but require a documented fairness policy.

How do you handle abandoned sessions?

Expire leases and reconcile them against checkout state. Release operations must be idempotent.

How do you prevent polling overload?

Use jittered retry intervals, cached status and adaptive backoff; consider push only if connection capacity permits.

Does admission guarantee inventory?

No. Checkout must separately reserve inventory transactionally.

Try it yourself

Design a simulator with 1,000 queued users, 10 active slots and random session durations. Inject duplicate claims and worker crashes. Assert that active leases never exceed 10 and no user holds two leases. Then compare fixed-rate admission with feedback-controlled admission.

Two-minute revision

Edge gate protects origin; queue controls ordering; leases bound concurrency.Atomic transitions and idempotency prevent duplicate admission.Admission rate depends on session duration and downstream health.Fairness, inventory and failure policies are explicit product decisions.

Conclusion

A waiting room is not merely a queue. It is an admission-control system with a user-facing fairness contract. Start with a shared queue and atomic leases, then add edge validation, bounded polling and adaptive control as measured load demands.

For a production rollout, test invariants under concurrency before tuning throughput. Run a small event first, monitor checkout latency and abandonment, and increase capacity only when downstream measurements justify it. For related overload protection, read our cache stampede protection guide.

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *