Live Bidding Engine: Ordering, Contention and Push Updates
System DesignModel answerLast updated
Design a live bidding service that handles bursts of bids on popular items, keeps a strict per-item order, never loses accepted bids, and streams the leading bid to viewers.
You are asked to design the backend for an online bidding service where sellers list items and buyers compete to win them before a deadline.
What users can do
- Open a listing and see its details, the current leading bid, and the history of bids.
- Place a bid.
- Watch the leading bid and new bids change live, without refreshing.
Load and correctness expectations
- Some listings become extremely popular. In the last 30 seconds before the deadline, one listing may see a flood of bid attempts and a very large audience watching it.
- Bids for a single listing must be applied in a well-defined order.
- Invalid or stale bids (too low, late, or for a closed listing) must be rejected.
- Every accepted bid and every change in listing state must be stored durably.
- When the deadline passes, the system must close the listing and declare the winning bid.
What to cover in your answer
- The client-facing APIs: reading a listing, placing a bid, and subscribing to live updates.
- The bid write path when many people compete for the same listing at once.
- The mechanism for pushing live updates (for example SSE or WebSocket).
- Storage choices for listing metadata, bid history, the current leading bid, and event delivery.
- Consistency, idempotency, ordering, failure handling, and how you scale for a very hot listing.
State your assumptions about traffic (concurrent viewers, bid rate, peak per-listing rate) before designing.
Hints
Hint 1
Find the real hot spot first: a single listing's leading-bid record is written by thousands of bidders and watched by a huge audience. Reads and fan-out dwarf accepted writes.
Hint 2
Give every listing its own monotonically increasing sequence number. It solves ordering, gap detection on the client, resume after reconnect, and gives you a natural fencing/versioning field.
Hint 3
Start with a conditional, transactional write (accept only if the amount beats the current leader by the increment and the listing is open), then ask what breaks under heavy contention and consider a single owner per listing that pre-filters stale bids and batches commits.
Hint 4
Separate the durable write from delivery: commit the bid and an outbox event in one transaction, publish through a log partitioned by listing, and coalesce updates to viewers at a bounded rate.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
CRUD is easy here. The hard part is one listing's leading-bid record: thousands of bidders write to it in the final seconds while hundreds of thousands of people watch it. A good design finds that hot spot early and builds around it.
Requirements and assumptions
Functional: view a listing; place a bid (accepted only if the listing is open and the amount is at least current leader + minimum increment); live updates; close at the deadline and finalize the winner.
Non-functional:
- Strict per-listing ordering, no lost accepted bids. Durable before acknowledged.
- An acknowledgment is authoritative: "you lead" must be true at that moment.
- Bid p99 under ~200 ms; push latency under ~1 s.
- Reads and watchers vastly outnumber writes.
Assumed numbers: 10M daily users, 1M live listings, 2M concurrent watchers. Global bid rate averages ~5k/s, peaks ~50k/s. A hot listing: 500k watchers and 5-20k bid attempts/s in the last 30 s, mostly stale. Naive fan-out of 10 updates/s to 500k watchers is 5M messages/s, so fan-out, not bid writes, is the bandwidth problem.
Clarify: does a late bid extend the deadline (soft close)? Are proxy/max bids needed (treat as an extension)? Is payment in scope (assume no)?
APIs
GET /listings/{id} -> details, status, end_time, leader {amount, bidder, seq}
GET /listings/{id}/bids?after_seq=&limit= -> paginated history
POST /listings/{id}/bids {amount, idempotency_key, expected_seq?}
-> 200 {accepted, seq, leader} | 409 {reason: OUTBID|STALE|CLOSED, leader}
GET /listings/{id}/stream?from_seq= (SSE) or WebSocket subscribe
events: BID_ACCEPTED | EXTENDED | CLOSED, each with seq, amount, end_time, server_ts
seqis a per-listing counter. Clients use it to order events, detect gaps, and resume.idempotency_keymakes retries safe.expected_seqis optional. Validation is on the amount, so a higher bid can still win with a stale seq.
SSE vs WebSocket: viewing is server-to-client only, so SSE is simplest (plain HTTP, automatic reconnect with Last-Event-ID, proxy friendly). Bids go through ordinary POSTs. Choose WebSocket only if you also need chat or other bidirectional traffic. On reconnect the client sends from_seq to recover missed events.
Data model
| Data | Store | Reason |
|---|---|---|
| Listing metadata and state | Relational DB sharded by listing_id | Transactional state transitions |
| Current leader + seq + status | Same row (source of truth), cached in Redis | Updated atomically with acceptance |
| Bid history | Append-only table, PK (listing_id, seq), same shard; archive later | Ordered range scans |
| Idempotency | Unique (listing_id, bidder_id, idempotency_key) | Dedup inside the same transaction |
| Events | Transactional outbox, then a log (Kafka) partitioned by listing_id | Ordered, replayable |
State machine: SCHEDULED -> OPEN -> CLOSING -> CLOSED -> SETTLED. Each transition is a conditional update (WHERE status='OPEN') and emits an event.
Write path
Baseline (fine for ordinary listings): one transaction that
- inserts the idempotency record (on duplicate, return the original result);
- runs
UPDATE listings SET leader=:amt, bidder=:u, seq=seq+1 WHERE id=:l AND status='OPEN' AND now()<end_time AND leader+increment<=:amt; - if one row changed, inserts the bid row and an outbox row, then commits;
- if zero rows changed, rolls back and returns
OUTBIDwith the current leader.
This is correct, but on a hot listing row locks serialize everything at the database.
Hot listings: a single writer per listing.
- Route all bids for a listing by consistent hashing to one owner process that keeps the state in memory behind a queue.
- Pre-filter: reject anything below leader + increment without touching the DB. In the final seconds roughly 90% of attempts are stale, so most load vanishes here.
- Group commit: apply surviving bids sequentially in a 5-10 ms window (only the strictly increasing chain is valid), write them in one transaction (bid rows, new leader, outbox), then acknowledge. Never ack before commit.
- Ownership safety: the owner holds a lease (etcd/ZooKeeper) with a fencing token; DB writes include
WHERE owner_epoch=:epochso a zombie owner cannot write after failover. - Failover: the new owner reloads from the DB. Memory is only a cache, so no accepted bid is lost.
- Add per-user rate limiting and dedup at the gateway.
Real-time fan-out
- An outbox relay (or CDC) publishes committed events to Kafka partitioned by listing_id, preserving order.
- Fan-out workers forward to push gateways. Each gateway subscribes only to listings its connected clients watch (Redis pub/sub or a routing table).
- Coalescing: viewers need the latest leader, not every intermediate bid. Send at most every 100-200 ms with the newest state plus a count of bids since the last send. History is fetched on demand. This bounds fan-out.
- Gap recovery: the client tracks
seq; on a gap or reconnect it sendsfrom_seq. The gateway replays from a ring buffer or the log, or the client refetches a snapshot. - Sizing: ~100k connections per gateway node, so 2M watchers needs roughly 20-30 nodes, scaled horizontally. Serve the listing page and snapshot from CDN/cache with short TTLs.
Closing the listing
- Use server time only; never trust client clocks.
- A scheduler (delay queue or timer wheel keyed by end_time) triggers the close service. It performs a conditional
OPEN -> CLOSING -> CLOSEDtransition so only one closer wins. Bids arriving after the transition are rejected by thestatus='OPEN'predicate, which gives a clean cutoff. - With soft close, an accepted bid in the final window updates
end_timein the same transaction and emitsEXTENDED. The scheduler must re-arm; on firing it re-checks the stored end_time. - Finalization reads the leader row, checks the reserve, records the winner, and emits
CLOSED. Settlement (payment) is downstream and idempotent. - A periodic sweeper closes anything the timer missed, so a crashed scheduler cannot leave a listing open.
Failure handling and trade-offs
- Client timeout on POST: retry with the same idempotency key to get the original outcome.
- Duplicate or reordered events: clients ignore
seq<= last seen. - Kafka lag: viewers see slightly stale data; correctness is unaffected because the DB decides acceptance.
- Cache staleness: cache is only for display, never for the accept decision.
- Consistency vs availability: bidding favors consistency per listing. Reject or retry during failover instead of accepting unsafely. Listings are independent, so a failure affects only the shard owner's listings.
- Scaling: shard by listing_id; hot listings get dedicated owner capacity and gateway coalescing; cold ones use the simple baseline.
Common mistakes
- Treating this as plain CRUD and ignoring the hot row.
- Acknowledging before the durable commit.
- Fanning out every bid to every viewer instead of coalescing.
- Using client time for the deadline, or having no fencing for the single owner.
- Making the cache the authority for accepting bids.
- No resume/gap protocol, so reconnecting clients show wrong state.