Build a real-time bidding platform with proxy bids and soft close
System DesignModel answerLast updated
Design a scalable auction system handling 500k live auctions, 5M watchers, proxy bidding, reserve prices, buy-it-now, soft close, and sub-200ms bid latency.
Design a real-time bidding platform where sellers list items for auction and buyers compete by submitting bids. The system must handle high concurrency, guarantee bid consistency, and push live updates to millions of watchers.
Functional Requirements
- Users can create accounts, authenticate, and search or browse active auctions.
- Sellers create auctions specifying item details, start/end timestamps, opening price, optional reserve price (minimum acceptable sale price), bid increment rules, and an optional instant-purchase price.
- Buyers submit bids on live auctions and view the current winning price plus bid history.
- The platform supports proxy bidding: a buyer submits their maximum willingness to pay, and the system automatically raises their visible bid by the minimum increment needed to maintain the lead as competitors bid.
- Soft close prevents last-second sniping: any bid placed within the final X seconds extends the auction end time by Y seconds.
- Watchers receive near-instant notifications when the leading price changes, the end time extends, or the auction concludes.
- When an auction ends, the system unambiguously determines the winner and initiates order fulfillment.
Scale and Performance Targets
- Millions of registered users.
- 500,000 concurrent live auctions with approximately 5 million active watchers across all auctions.
- Popular auctions attract hundreds of thousands of simultaneous watchers; bid activity spikes dramatically in the final seconds.
- p99 latency from bid acceptance to UI update: under 200 ms.
What You Should Cover
- API contracts — define the key endpoints (
CreateAuction,GetAuction,PlaceBid,SubscribeAuctionEvents,CloseAuction) with request/response schemas and error conditions. - Data schema — tables for users, items, auctions, bids, watchlists, and orders, including indexes to support efficient queries.
- System architecture — the services, datastores, caches, message brokers, and push infrastructure needed.
- Bid pricing logic — how reserve prices, tiered increments, proxy maximums, and instant-purchase interact to compute the displayed current price.
- Consistency guarantees — how you ensure exactly one winner per auction, no lost winning bids, and correct ordering even under heavy concurrent load in the final seconds.
- Idempotency and concurrency control for bid placement — compare row-level locks, optimistic versioning, and single-writer-per-auction patterns; justify your choice.
- Real-time update delivery — evaluate polling, long polling, Server-Sent Events, and WebSockets; explain ordering, sequence numbers, and reconnection with backfill.
- Sharding and partitioning strategy (e.g., by auction ID), handling of hot auctions, and ensuring total bid ordering.
- Auction finalization — timer/scheduler design, idempotent close operations, order creation, and recovery after failures or shard leader changes.
- Handling network delays, retries, and clock skew — which clock is authoritative, and how late or duplicate bids are processed.
- Fraud and abuse prevention — shill bidding, rate limits, and sellers bidding on their own listings.
- Payment and escrow workflow for winners, including failed payment capture and fallback offers.
- Security, privacy, and auditability — authentication/authorization, encryption, immutable bid logs, and tamper-evident audit trails.
- Capacity estimation — rough QPS/throughput calculations, and key metrics and alerts you would monitor.
Hints
Hint 1
The hardest challenge is maintaining strict bid ordering per auction under high concurrency in the final seconds, while simultaneously pushing updates to hundreds of thousands of watchers with minimal latency.
Hint 2
Separate the write path (strict ordering, single writer per auction) from the read path (massive fan-out, caching, coalescing updates) to handle the different consistency and scale requirements.
Hint 3
Proxy bidding and soft close both require deterministic state machines; routing all bids and close commands through the same ordered log guarantees reproducibility and exactly-once winner determination.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overview
This problem centers on one critical challenge: maintaining strict, correct bid ordering per auction during a high-concurrency burst in the final seconds, while simultaneously fanning out real-time updates to millions of watchers. Strong designs separate the write path (strict ordering, strong consistency) from the read path (massive scale, eventual consistency, caching).
1. Requirements Clarification and Capacity Estimation
Begin by confirming scale parameters and deriving load estimates.
Givens:
- 500k live auctions, average duration ~7 days.
- Most auctions receive fewer than 20 bids; bid activity is heavily skewed toward the final minute.
- 5M concurrent watchers across all auctions.
Derived estimates:
- Steady-state bid QPS: relatively low, perhaps 1–2k bids/s globally.
- Peak bid QPS: 5–20k bids/s during high-traffic periods. A single viral auction might see 1–5k bids/s in its final 10 seconds.
- Read QPS: with 5M watchers plus general browsing, expect 50–100k
GetAuctionand search queries per second. These should be served from cache, CDN, and search indexes. - Push fan-out: the dominant load. A hot auction with 300k watchers receiving 20 price updates/s would naively generate 6M messages/s. The design must coalesce and batch updates.
Non-functional priorities: strong consistency for bid ordering and winner determination, high availability for reads, p99 bid-to-UI latency under 200 ms.
2. API Contracts
CreateAuction
- Request:
itemId, startTime, endTime, startingPrice, reservePrice?, incrementTable, instantBuyPrice?, softCloseConfig{triggerWindowSec, extensionSec} - Response:
auctionId - Errors:
INVALID_TIME_RANGE,RESERVE_BELOW_STARTING_PRICE,UNAUTHORIZED
GetAuction
- Request:
auctionId - Response:
{status, currentPrice, leadingBidderPseudonym, endTime, sequenceNumber, bidCount, reservePriceMet}
PlaceBid
- Request:
auctionId, maxAmount, idempotencyToken - Response:
{accepted, currentPrice, isLeading, sequenceNumber, endTime} - Errors:
AUCTION_NOT_ACTIVE,BID_TOO_LOW(minRequiredBid),SELF_BIDDING_FORBIDDEN,RATE_LIMIT_EXCEEDED,PAYMENT_METHOD_UNVERIFIED - Retrying with the same token returns the original outcome.
SubscribeAuctionEvents
- Request:
auctionIds[], lastSeenSequence? - Response: stream of
{auctionId, sequenceNumber, eventType: PRICE_CHANGE|TIME_EXTENDED|CLOSED, eventPayload}
CloseAuction (internal/admin only)
- Request:
auctionId, reason - Idempotent operation.
3. Data Schema
| Table | Primary Key / Key Columns | Indexes |
|---|---|---|
| Users | userId, kycVerified, fraudRiskScore | |
| Items | itemId, sellerId, attributes | sellerId |
| Auctions | auctionId, sellerId, status, endTime, currentPrice, leadingBidderId, leaderMaxBid, sequenceNumber, leaseEpoch | (status, endTime) for scheduler; sellerId; full-text search via CDC to Elasticsearch |
| Bids | (auctionId, sequenceNumber) composite PK, bidderId, maxAmount, idempotencyToken, serverTimestamp, previousBidHash, currentBidHash | unique (auctionId, bidderId, idempotencyToken); bidderId for user bid history |
| Watchlists | (userId, auctionId) | auctionId for reverse lookup |
| Orders | orderId, auctionId UNIQUE, winningBidderId, finalAmount, paymentStatus | winningBidderId |
The Bids table is append-only and immutable. Data is sharded by auctionId using a distributed SQL database like Spanner, CockroachDB, or sharded Postgres/MySQL via Vitess.
4. High-Level Architecture
- API Gateway: handles authentication, rate limiting, WAF.
- Auction Service: manages CRUD operations and auction reads, backed by Redis for caching hot auction metadata.
- Bid Service:
- Routes requests by
hash(auctionId)to a partition leader. - Each leader maintains an in-memory state machine (actor) per active auction, backed by a replicated log (Kafka partition or Raft).
- The leader sequences each bid, commits it to the log and database, then publishes an event.
- Routes requests by
- Event Bus (Kafka): feeds downstream consumers:
- Push notification tier
- Search indexer
- Fraud detection
- Email/SMS notifications
- Order and payment services
- Push Tier: stateless WebSocket servers subscribe to per-auction topics via Redis Pub/Sub or NATS, then forward updates to connected clients.
- Scheduler Service: manages auction end timers and triggers the close command.
- Order and Payment Service: uses transactional outbox pattern to ensure exactly-once order creation.
5. Bid Pricing Algorithm
Each auction maintains:
- Leader's maximum bid M1
- Highest competing maximum M2
- Reserve price R
- Increment function
inc(price), e.g., $0.50 below $25, $1 from $25–$100, $2.50 above $100.
Displayed current price = min(M1, M2 + inc(M2))
- If no competitor exists, display the starting price.
- Reserve price enforcement: if
M1 ≥ Rand the computed price is below R, raise the displayed price to R. IfM1 < R, the auction shows "reserve not met." - New bid B arrives:
- If
B > M1, B becomes the new leader, and the price becomesmin(B, M1 + inc(M1)). - Otherwise, the existing leader remains, and the price becomes
min(M1, B + inc(B)).
- If
- Ties: equal maximums are resolved by earlier sequence number (timestamp).
- Instant purchase: available until the first valid bid or until reserve is met (policy choice). An instant-buy request is a command in the same ordered log; it atomically closes the auction at the instant-buy price.
Because pricing is computed deterministically by a single writer from an ordered log, it is fully reproducible and auditable.
6. Concurrency Control and Idempotency
| Approach | Pros | Cons |
|---|---|---|
Row-level locks (SELECT … FOR UPDATE) | Simple, correct | Lock convoy under contention; database round trips dominate latency during final seconds |
Optimistic versioning (UPDATE … WHERE version = ?) | No locks | Retry storms under contention; tail latency explodes when it matters most |
| Single writer per auction via partitioned log + actor | Total ordering, no contention, in-memory state, batch commits | Requires leader election, epoch fencing, replay on failover |
Recommendation: single writer per auction.
- A partition leader holds a lease with an epoch number. All database writes include the epoch as a fencing token, preventing stale leaders from corrupting state.
- A bid is acknowledged only after durable append (quorum replication) and sequence number assignment.
- Idempotency: enforce a unique constraint on
(auctionId, bidderId, idempotencyToken). The actor caches recent tokens in memory; the database constraint is the final guard. Retries return the stored result.
7. Consistency and Winner Determination
- Bids and the
CLOSEcommand flow through the same ordered log per auction. Any bid sequenced afterCLOSEis rejected. - The winner is the leader in the state immediately before
CLOSE, guaranteeing exactly one winner. - Acknowledged bids are already durable in the replicated log, so winning bids cannot be lost.
- Order creation enforces
UNIQUE(auctionId)as a final safeguard. - A reconciliation job periodically recomputes winners from the bid log and alerts on discrepancies.
8. Clocks, Soft Close, and Late Bids
- Authoritative clock: the partition leader's NTP-disciplined clock at bid sequencing time. Client clocks are never trusted.
- Late bids: a bid is valid only if
serverTimestamp < endTime. Network delays that cause a bid to arrive after close result inAUCTION_CLOSEDerror. Retries of already-accepted bids return the original acknowledgment via idempotency. - Soft close: if a bid is sequenced when
endTime − serverTimestamp < triggerWindowSec, the actor setsendTime += extensionSec, publishes aTIME_EXTENDEDevent, and reschedules the close timer. - Clock skew: skew between different leaders is irrelevant since each auction has exactly one leader. On failover, the new leader reads
endTimefrom the log. To avoid accepting bids the previous leader might have rejected, it waits out the lease expiry before processing new bids.
9. Real-Time Push
| Approach | Assessment |
|---|---|
| Polling | Simple, but wasteful bandwidth and latency at 5M watchers |
| Long polling | Better efficiency, but connection churn is high |
| Server-Sent Events (SSE) | Lightweight, one-way, widely supported; good fit |
| WebSockets | Full-duplex, lowest latency, best for interactive bidding |
Recommendation: WebSockets.
- Clients connect to stateless WebSocket gateways, which subscribe to per-auction Redis Pub/Sub or NATS channels.
- Each event carries a sequence number. Clients track the last seen sequence and request backfill on reconnect via
SubscribeAuctionEvents(lastSeenSequence). - Update coalescing: if 10 price changes occur within 100ms, the push tier may coalesce them into a single message to reduce fan-out.
- Ordering: events are totally ordered per auction via sequence numbers.
10. Sharding and Hot Auctions
- Sharding: partition by
hash(auctionId). Each partition is owned by one leader at a time. - Hot auction mitigation:
- Read replicas serve
GetAuctionqueries. - Redis caches auction metadata.
- CDN serves static assets and search results.
- Push tier coalesces and rate-limits updates per client (e.g., max 10 updates/sec).
- Read replicas serve
- Ordering across partitions: not needed; each auction is independent and has total ordering within its partition.
11. Auction Finalization
- Scheduler: maintains a priority queue of
(endTime, auctionId). WhenendTimearrives, it publishes aCLOSEcommand to the auction's partition. - The partition leader sequences the
CLOSEcommand, finalizes the winner, and publishes aCLOSEDevent. - Idempotency: close is idempotent; replaying the
CLOSEcommand yields the same winner. - Failure recovery: on leader failover, the new leader replays the log from the last checkpoint, recomputes state, and reschedules any pending close timers.
12. Fraud and Abuse
- Shill bidding: flag accounts with behavioral patterns (bidding repeatedly on the same seller's items, last-second retractions). Machine learning models score risk.
- Rate limits: per-user bid limits (e.g., 10 bids/minute per auction).
- Self-bidding: enforce
bidderId ≠ sellerIdat API level. - Bid retraction: allow retraction only within a short grace period and penalize frequent retractions.
13. Payment and Escrow
- When an auction closes, the Order service creates an order and initiates payment authorization.
- Funds are held in escrow until the seller ships and the buyer confirms receipt.
- Failed payment capture: notify the winner; if payment fails after retries, offer the item to the second-highest bidder (if their max bid meets the reserve).
14. Security, Privacy, and Auditability
- Authentication: OAuth2 + short-lived JWTs.
- Authorization: sellers can only modify their own auctions; bidders cannot see others' maximum bids.
- Encryption: TLS for all transit; encrypt PII and payment tokens at rest.
- Immutable bid log: each bid includes
previousBidHashandcurrentBidHash, forming a Merkle chain to detect tampering. - Audit trail: all state transitions are logged with timestamps, user IDs, and sequence numbers.
15. Key Metrics and Alerts
- Bid acceptance latency (p50, p95, p99)
- Bid-to-UI push latency (p99 target: 200ms)
- Bid rejection rate and error distribution
- WebSocket connection count and churn rate
- Partition leader election frequency
- Auction close latency (time from scheduled end to winner determination)
- Order creation success rate
- Fraud detection alert volume
Alerts:
- p99 bid latency exceeds 200ms
- Partition leader election storm (>5 elections/minute)
- Bid rejection rate spike
- Order creation failures
Summary
The core insight is to decouple the write path and read path: use a single-writer-per-auction model with a partitioned, replicated log to guarantee strict ordering and consistency, while serving reads from replicas and caches and pushing updates via WebSockets with coalescing. Proxy bidding, soft close, and winner determination all become deterministic state machine transitions in the ordered log, ensuring correctness, auditability, and reproducibility even under extreme load.