Skip to content

Design an Online Auction (eBay)

Advanced 55 min read Part 17 of 18

Design eBay-style auctions: strongly consistent bids, proxy bidding, real-time price updates, precise auction close, fairness and 10M live auctions.

The Problem#

An online auction service such as eBay lets a seller list an item with a starting price and an end time. Buyers then compete by placing bids. Each new bid must beat the current highest bid. When the clock runs out, the highest bidder wins and pays.

On the surface, this is a catalogue with a "bid" button. Underneath, it is a precise concurrency problem:

  • many people bid on the same item at nearly the same moment, especially in the final seconds;
  • the system must decide, without ambiguity, which bid is highest and which came first;
  • it must never lose an accepted bid;
  • everyone watching must see the price change live;
  • the auction must close at exactly the advertised time, even across millions of simultaneous auctions.

Analogy. Imagine a traditional auction room.

  • The auctioneer stands at the front with a ledger showing the current highest bid. That is the auction's state.
  • Bidders raise their paddles. The auctioneer hears only one at a time, and accepts a bid only if it beats the ledger. That is the serialisation point that makes bids consistent.
  • A clerk writes every accepted bid into a bound book that is never erased: the durable bid log.
  • The auctioneer calls the new price aloud so everyone in the room hears it at once: real-time updates.
  • A clock on the wall decides when bidding stops, and the auctioneer's gavel falls exactly then: auction end timing.
  • Some bidders leave a sealed note with the clerk: "bid for me, up to £500". The clerk raises their paddle automatically, by the minimum increment, whenever someone outbids them. That is proxy bidding.

Our system is a few million such rooms, all open at once. Each has its own auctioneer, ledger and clock.

This problem tests whether a candidate can:

  • enforce an invariant ("each accepted bid is higher than all earlier accepted bids") under concurrency, using row locks, optimistic concurrency control (OCC), atomic compare-and-set or single-writer serialisation;
  • make the bid path durable, so an acknowledged bid is never lost;
  • push real-time updates to many watchers efficiently;
  • handle time correctly: closing auctions precisely, and deciding which bids arrived in time;
  • reason about fairness and ordering in a distributed system where client clocks cannot be trusted;
  • scale to millions of concurrent auctions, with a few extremely hot ones.

Clarifying Questions#

QuestionAssumed answerWhy it matters
Which auction format?Ascending ("English") auctions with proxy bidding, like eBay; others as variantsDetermines the bid acceptance rule and the price calculation
Is there a minimum bid increment?Yes, a small increment table based on the current priceA bid must exceed the current price by at least the increment
Do sellers set reserve prices or buy-it-now prices?Reserve price yes (hidden minimum to sell); buy-it-now as an extensionChanges who wins, and adds an instant-purchase path
How many concurrent auctions?~10 million live at any timeDrives sharding and the closing scheduler
Bid volume?~15M bids/day on average; peaks 10 to 50 times higher; a hot auction may receive hundreds of bids per second near its endShapes the bid path's contention handling
How live must the displayed price be?Updates within ~1 second for watchersCalls for push (SSE or WebSockets) rather than slow polling
Hard close or soft close?Hard close at the end time (eBay style); soft close discussed as an optionChanges the end-time logic and the sniping dynamics
What happens after the auction ends?The winner is notified and pays through checkout; payments are out of scope beyond the hand-offClose must reliably trigger winner processing
Can bids be retracted?Rarely, with strict rules, handled by support toolsThe bid log must allow auditable corrections
Search and categories?Out of scope beyond a note: CDC into a search indexKeeps focus on bidding
Bid history visible?Yes, with bidder identities maskedBids must be stored permanently and ordered
Global users?Yes; each auction has one home regionAvoids cross-region consensus per bid

Requirements#

Functional#

  1. Users should be able to post an item for auction with a starting price, optional reserve price, and an end date.
  2. Users should be able to bid on an item. A bid is accepted only if it is higher than the current highest bid (by at least the minimum increment), and only before the auction ends.
  3. Users should be able to view an auction, including the current highest bid, and see it update in real time.
  4. The auction should close at its end time, determine the winner, and notify the participants.

Out of scope:

  • search, filtering and sorting of items;
  • full checkout and payment processing;
  • shipping and feedback;
  • seller tools.

Non-Functional#

  • Strong consistency for bids. All users must agree on the current highest bid. A bid that is accepted must really have been the highest at the moment it was accepted, and no two bids can both "win" the same position. This is the core invariant.
  • Fault tolerance and durability. An acknowledged bid must never be lost, even if a server or database node fails immediately afterwards. The auction must still close correctly after failures.
  • Real-time display. Watchers see new highest bids within about one second.
  • Scale.
    • 10 million concurrent auctions.
    • Bids averaging hundreds per second, peaking at tens of thousands per second overall, and hundreds per second on a single hot auction.
    • Views roughly 100 times bids.
  • Latency. Bid acceptance p99 under 200 ms. Auction page p99 under 200 ms from cache.
  • Timeliness of close. Auctions close within about one second of their end time. No bid placed after the end time may be accepted.
  • Fairness. Ordering decisions are made by the server, consistently, without trusting client clocks.

When these conflict, consistency and durability of bids come first, then correct close timing, then real-time freshness, then raw latency.

Capacity Estimation#

Auctions.

  • 10 million live auctions at any time. With an average duration of 7 days, about 10M / 7 ≈ 1.4 million auctions start and end per day, about 16 per second on average. Ends are clustered around popular end times (evenings), so plan for 100+ closes per second at peaks.
  • An auction record (title, seller, prices, times, status, current-bid summary) is about 1 KB, so 10M live auctions take ~10 GB. Item descriptions and image references take a few KB more per auction; images live in object storage. All live auction state fits comfortably in memory caches.

Bids.

  • If each auction receives ~10 bids on average, that is 1.4M auctions × 10 = 14 million bids per day, about 160 bids per second on average.
  • Bids are bursty. They cluster in the final minutes of each auction ("sniping"), and popular end times concentrate those finales. A peak of 5,000 to 20,000 bids per second overall is a reasonable planning number.
  • Hot auctions (a rare collectible, a charity lot) can receive hundreds of bids per second in their last minute, all on one row. That is the real contention challenge.
  • Each bid record is ~100 to 200 bytes. 14M per day × 150 B ≈ 2 GB per day, ~750 GB per year. Bids are kept permanently for audit and history, but that is a modest storage load.

Views and real-time watchers.

  • At ~100 views per bid: ~1.4 billion page views per day, ~16,000 per second on average, perhaps 100,000 per second at peak.
  • Watchers holding live connections: suppose 2 percent of live auctions have someone watching at any moment, with an average of 5 watchers each. That is 10M × 0.02 × 5 = 1 million concurrent connections. A hot auction may have 100,000 watchers.
  • Each new highest bid fans out to all watchers. At 5,000 accepted bids per second, × an average of 5 watchers, plus hot-auction spikes, that is 25,000 to several hundred thousand push messages per second.

What these numbers imply:

  • The total bid rate is modest; a sharded relational database or a log-based design handles it easily. The difficulty is per-auction contention and ordering, not aggregate throughput.
  • The read path, auction pages and watchers, dominates traffic. It needs caching and a push tier sized like a chat system.
  • The closing mechanism must handle ~1.4M deadlines per day, precisely, including bursts at popular end times.

Core Entities#

  • Auction: one listing being sold: seller, item reference, starting price, reserve price, start and end times, status (scheduled, live, ended, cancelled), and the denormalised current-bid summary (highest amount, highest bidder, bid count, version).
  • Item: what is being sold: title, description, category, condition, images. Separate from Auction so that an unsold item can be relisted.
  • Bid: one bid attempt: auction, bidder, amount (or proxy maximum), server timestamp, sequence number, and status (accepted, rejected, outbid, retracted). Rejected bids are worth recording too, for audit and abuse detection.
  • User: buyers and sellers, from the identity system.
  • Watch: a user's interest in an auction, used for notifications ("you've been outbid", "ending soon").

API Design#

POST /v1/auctions
  Body: { item: { title, description, category, imageIds[] }, startingPrice, reservePrice?,
          startsAt?, endsAt }
  -> 201 { auctionId }
 
GET  /v1/auctions/{auctionId}
  -> 200 { auction, item, currentPrice, highBidderMasked, bidCount, endsAt, status, version }
 
POST /v1/auctions/{auctionId}/bids
  Headers: Authorization, Idempotency-Key
  Body:    { maxAmount }                      # proxy bid: "bid for me up to this amount"
  -> 201 { bidId, status: "ACCEPTED", currentPrice, youAreHighBidder: true }
  -> 200 { bidId, status: "OUTBID", currentPrice }   # accepted as a bid but already beaten by a proxy
  -> 409 { reason: "TOO_LOW" | "AUCTION_ENDED", currentPrice, minNextBid }
 
GET  /v1/auctions/{auctionId}/bids?cursor=...  # bid history, bidder names masked
GET  /v1/auctions/{auctionId}/stream           # SSE: price updates, ending-soon, ended
POST /v1/auctions/{auctionId}/watch            # follow for notifications

Notes on the API:

  • The bidder's identity comes from the auth token, never from the body.
  • The server decides the time of every bid. Clients cannot pass timestamps.
  • Idempotency-Key on bids is important: a mobile user who retries on a timeout must not place two bids. The retry returns the original result (see Idempotency and Safe Retries).
  • The response tells the bidder where they stand. A bid can be accepted and immediately outbid, when an existing proxy maximum is higher. The new bid is valid and recorded, but it raises the price without taking the lead. The API distinguishes this case clearly.
  • version on the auction lets clients discard out-of-order updates (Deep Dive 5).
  • Images are uploaded first, via pre-signed URLs to object storage, and only their ids are sent with the listing (see Pattern: Handling Large Files and Blobs).

High-Level Design#

1) Users can post an item for auction#

A seller fills in a listing form and uploads photos. The Auction Service validates the listing (end time in the future and within allowed durations, sensible prices) and writes an Item row and an Auction row in a relational database. The auction's status is LIVE, or SCHEDULED if it starts later.

  • Images go straight from the client to object storage via pre-signed URLs, and are served through a CDN. The listing stores only their keys.
  • The new auction's end time is registered with a closing scheduler, which will fire when the auction should close (Deep Dive 6).
  • Change data capture feeds the listing to a search index, which is out of scope, but it shows where search would plug in.

2) Users can bid on an item#

This is the core of the problem. A Bid Service receives POST /bids, and must:

  1. check that the auction is live, and that the server's current time is before its end;
  2. check that the bid exceeds the current highest bid by at least the increment;
  3. record the bid and update the auction's current-bid summary, atomically with respect to other bids on the same auction.

The naive version is a read-then-write race:

current = SELECT max_bid FROM auctions WHERE id = 7      -- both A and B read 100
if bid > current: INSERT bid; UPDATE auctions SET max_bid = bid

Bidders A (110) and B (105) both read 100, both pass the check, and both are "accepted". If B's update lands last, the displayed price is now 105, even though A bid 110. Or two bids of 110 are both accepted. Deep Dive 1 fixes this with a conditional update (compare-and-set) on the auction row:

UPDATE auctions
SET max_bid = :amount, max_bidder = :user, bid_count = bid_count + 1, version = version + 1
WHERE id = :auction_id
  AND status = 'LIVE' AND now() < ends_at
  AND max_bid + :min_increment <= :amount;       -- 1 row: accepted; 0 rows: rejected

Together with the insert into a bids table, in the same transaction, this makes acceptance atomic. The database becomes the auctioneer who hears one paddle at a time.

3) Users can view an auction with the current highest bid, live#

The auction page shows item details (static, cacheable) and the current price (dynamic):

  • The Auction Service serves details from a cache in front of read replicas. Images come from the CDN.
  • The current price is read from the auction row's summary, cached in Redis, and invalidated on every accepted bid.
  • For live updates, clients open a Server-Sent Events stream for the auction. Every accepted bid publishes an event (via Kafka, then a pub/sub channel per auction) to the Realtime Gateway nodes. Those push the new price to each connected watcher (Deep Dive 4).

4) Auctions close at their end time#

At the end time:

  1. The auction stops accepting bids. This is enforced by the bid path's now() < ends_at check, so correctness does not depend on a job running on time.
  2. The status is set to ENDED.
  3. The winner is determined (the highest bidder, if the reserve is met).
  4. Notifications and checkout are triggered.

A closing scheduler fires at each end time and runs a Close Worker, which performs steps 2 to 4 idempotently (Deep Dive 6).

The full high-level design#

The design separates a consistency-first bid path (Bid Service, the auction row as the serialisation point, a durable bid log) from an availability-first read path (caches, replicas, CDN) and a push path (Kafka, pub/sub, SSE gateways). A closing path runs alongside them.

Components:

  • API Gateway: authentication, per-user rate limits (especially on bids), routing (see API Gateway and Backend-for-Frontend).
  • Auction Service: creates listings, serves auction details, registers end times with the scheduler.
  • Bid Service: validates bids and applies them atomically to the auction row (compare-and-set, or a single writer per auction), records them in the bid log, and returns the bidder's standing.
  • Auction DB (PostgreSQL): the source of truth for auctions and bids, sharded by auction id. Each shard has a primary with a synchronous standby, plus read replicas.
  • Kafka: the durable event stream of accepted bids and auction state changes, published through a transactional outbox or CDC. It drives cache invalidation, real-time fan-out, notifications and analytics.
  • Redis summary cache: the current price, bid count and end time per auction, for fast page loads.
  • Fan-out workers and pub/sub: turn bid events into messages on per-auction channels.
  • Realtime Gateway: holds SSE connections and pushes updates to the watchers of each auction (see Polling, Long Polling, SSE, WebSockets and Webhooks).
  • Closing scheduler and Close Worker: fire at each auction's end time, mark it ended, determine the winner and emit an AuctionEnded event.
  • Notification Service: "you've been outbid", "ending in 10 minutes" and "you won" messages via push and email.
  • Object storage and CDN: item images.

Key Flows#

Flow 1: Place a bid#

  1. The Bid Service opens a short transaction on the auction's shard and locks the auction row, or uses a compare-and-set (Deep Dive 1).
  2. It checks status and time using the database clock, so every bid on this auction is judged by one clock.
  3. It applies the proxy bidding rules (Deep Dive 2) to compute the new current price and leader.
  4. It inserts the bid, updates the summary, and writes an outbox row, all in one commit. With a synchronous standby, the commit survives the primary's failure.
  5. The bidder gets an answer as soon as the transaction commits. Fan-out to watchers is asynchronous, usually within a few hundred milliseconds.

Flow 2: Close an auction#

  1. The scheduler fires at, or shortly after, the end time (Deep Dive 6).
  2. The Close Worker flips the status with a conditional update, so a duplicate trigger is harmless.
  3. Bids racing with the close are decided by the same row. Either a bid's transaction commits before the close (with now() < ends_at), or it sees ENDED, or its own time check fails. There is no window in which a late bid can slip in.
  4. The outcome event drives notifications and checkout. Payment itself is handed off (see the payment-system problem).

Data Model#

CREATE TABLE auctions (
  id                  BIGINT PRIMARY KEY,
  item_id             BIGINT NOT NULL,
  seller_id           BIGINT NOT NULL,
  start_price_cents   INT NOT NULL,
  reserve_cents       INT,
  ends_at             TIMESTAMPTZ NOT NULL,
  status              TEXT NOT NULL,            -- SCHEDULED | LIVE | ENDED | CANCELLED
  current_price_cents INT NOT NULL,
  leader_id           BIGINT,                   -- current high bidder
  leader_max_cents    INT,                      -- their secret proxy maximum
  bid_count           INT NOT NULL DEFAULT 0,
  version             BIGINT NOT NULL DEFAULT 0 -- increments on every accepted bid
);
CREATE INDEX auctions_live_ending ON auctions (ends_at) WHERE status = 'LIVE';
 
CREATE TABLE bids (
  auction_id        BIGINT NOT NULL,
  seq               BIGINT NOT NULL,            -- = auctions.version after this bid
  bidder_id         BIGINT NOT NULL,
  max_cents         INT NOT NULL,
  price_after_cents INT NOT NULL,
  result            TEXT NOT NULL,              -- LEADING | OUTBID_BY_PROXY | REJECTED
  server_ts         TIMESTAMPTZ NOT NULL DEFAULT now(),
  idempotency_key   TEXT NOT NULL,
  PRIMARY KEY (auction_id, seq),
  UNIQUE (auction_id, bidder_id, idempotency_key)
);

Design notes:

  • The auction row is the serialisation point. It holds a denormalised summary: current price, leader, leader's maximum, bid count and version. Every bid reads and updates only this one row (plus an insert into bids). Contention is therefore on one small row, and no query ever needs SELECT max(amount) FROM bids. That query would also be subject to phantoms: rows inserted concurrently that a lock on existing rows cannot cover.
  • bids is append-only, keyed by (auction_id, seq). The sequence number is the auction's version at acceptance, which gives a total order of bids per auction, decided by the serialisation point rather than by clocks. Bid history pages read this table by primary-key range.
  • The leader's proxy maximum is secret. It lives on the auction row for the proxy calculation, and must never appear in APIs or caches visible to other users.
  • The partial index on ends_at for live auctions supports the closing scheduler's "what ends next" queries and a safety sweep.
  • Rejected bids are recorded (in bids or a separate table) for audit and abuse detection. They do not advance version. A separate monotonic id can order them, if needed.
  • The shard key is auction_id for both tables, so every bid transaction is single-shard. "My bids" for a user is served by a secondary table keyed by bidder_id, maintained via CDC.

Database choice. A relational database with row-level locking and transactions makes the bid invariant simple to enforce, and PostgreSQL is a strong default. DynamoDB also works well: a conditional UpdateItem on the auction item (ConditionExpression: version = :v, or current_price < :amount), with TransactWriteItems to insert the bid atomically. Cassandra is a weaker fit for the serialisation point. Its lightweight transactions work, but at higher latency, and its strength, high write volume without coordination, is not what this path needs. See Choosing a Database: A Decision Guide.

DataStoreWhy
Auctions and current-bid summaryPostgreSQL, sharded by auction idRow-level atomicity for the bid invariant
Bids (history)PostgreSQL, same shard; archived to object storage laterSame-transaction insert, total order per auction
Bid and auction eventsKafka, partitioned by auction idDurable, ordered stream for fan-out and consumers
Summary cacheRedisFast page loads, invalidated or updated per bid
Live connections and channelsRealtime gateways plus Redis pub/subPush to watchers
End-time scheduleScheduler store (time-bucketed table or Redis sorted set) plus DB indexPrecise, scalable closing
ImagesObject storage plus CDNLarge, static

Deep Dives#

1. How do we make bids strongly consistent?#

The invariant: the sequence of accepted bids on an auction is strictly increasing, and the displayed highest bid is the true maximum. Equivalently, all participants must agree on one order of bids, and every bid is judged against the state left by all bids before it. This is a serialisability requirement on a single object, the auction. Fortunately, a single object is the easiest case.

Bad: read, check, write, without coordination

As shown in the high-level design, two concurrent requests can both read the old maximum, both pass the check, and both write. The result is two "accepted" bids, or a lower bid overwriting a higher one. This is the lost update anomaly. It happens under the default isolation level of most databases (Read Committed), because the read and the write are separate statements with no lock connecting them.

Bad: lock the bid rows and compute the maximum

A tempting fix is SELECT max(amount) FROM bids WHERE auction_id = 7 FOR UPDATE, then insert the new bid. It does not work:

  • FOR UPDATE locks existing rows. It cannot lock rows that do not exist yet. Two transactions can both lock the same old rows sequentially, compute the same max, and each insert a new bid. The new rows are phantoms that neither lock covered.
  • PostgreSQL does not even allow FOR UPDATE with aggregate functions. You would have to lock all bid rows individually, which is ever more expensive as bids accumulate.

The lesson: lock something that exists and represents the whole auction, which is the auction row.

Good: pessimistic lock on the auction row

BEGIN;
SELECT current_price_cents, leader_id, leader_max_cents, ends_at, status, version
FROM auctions WHERE id = :id FOR UPDATE;          -- serialises all bids on this auction
-- app: check LIVE and now() < ends_at; apply increment and proxy rules
INSERT INTO bids (...) VALUES (...);
UPDATE auctions SET current_price_cents = :p, leader_id = :l, leader_max_cents = :m,
                    bid_count = bid_count + 1, version = version + 1
WHERE id = :id;
COMMIT;
  • Why it works: only one transaction at a time can hold the row lock, so bids on one auction are serialised, exactly like the auctioneer hearing one paddle at a time. Each sees the state left by the previous one.
  • Cost: the lock is held for the transaction's duration, a few milliseconds if the transaction is short and the commit is fast. With a 3 ms critical section, one auction sustains roughly 300 bids per second before requests start queueing. That is enough for nearly all auctions, but a viral one at the last second can exceed it (Deep Dive 7 discusses alternatives).
  • Keep it short: no network calls (fraud checks, notifications) inside the transaction. Do those before or after.

Good: optimistic concurrency control (OCC) with a version

Read the auction without locking, compute the outcome, and then write only if nothing has changed:

UPDATE auctions
SET current_price_cents = :p, leader_id = :l, leader_max_cents = :m,
    bid_count = bid_count + 1, version = version + 1
WHERE id = :id AND version = :version_read
  AND status = 'LIVE' AND now() < ends_at;       -- 0 rows: someone else bid first, so retry

Insert the bid in the same transaction, after the update succeeds. If zero rows were updated, re-read and retry: the new state may make this bid too low, or still valid.

  • Why it works: the version check is a compare-and-set. Among concurrent writers who read version 41, exactly one can move it to 42.
  • When it shines: low to moderate contention, which describes most auctions. There is no lock wait, and the database does less work per conflict.
  • When it struggles: at very high contention, most attempts fail and retry, wasting work ("retry storms"). Cap retries (2 or 3), add jitter, and fall back to the locked path, or to the single-writer design, for hot auctions.

A simpler compare-and-set for plain bids. If there were no proxy bidding, the condition could compare amounts directly:

UPDATE auctions SET current_price_cents = :amt, leader_id = :u, version = version + 1
WHERE id = :id AND current_price_cents + :inc <= :amt AND now() < ends_at;

A higher bid succeeds even if other bids happened in between, as long as it still beats the latest price, so there are fewer spurious retries than with version-based OCC. Proxy bidding needs the leader's maximum too, so the version form (or a lock) is the general solution.

Great: serialise per auction in a single writer (optional for hot auctions)

Instead of coordinating many writers on one row, route all bids for an auction to one place that processes them in order:

  • Kafka partitioned by auction id: the Bid Service appends the bid request to the partition for that auction. Exactly one consumer in the group owns that partition at a time, and applies bids sequentially to the auction state (in memory, checkpointed to the database). Each request gets its result through a reply channel, or by waiting on a response keyed by request id.
  • An actor per auction: frameworks such as Akka, Orleans or a homegrown sharded actor system keep each auction's state in one actor that processes its mailbox in order.

Why it is attractive: there is no lock contention at all. Throughput per auction is limited only by the single writer's speed: thousands to tens of thousands of bids per second in memory, far more than any real auction needs. Ordering is explicit: the log order is the bid order. And the log is a durable audit trail.

Costs:

  • Latency: an extra hop through the log, plus waiting for the result. Typically 10 to 50 ms more.
  • Complexity: a request/response protocol over an asynchronous log, and partition rebalancing (during which a partition's bids pause for seconds).
  • Correctness in failover: the new consumer must rebuild exact state from a checkpoint plus the log, and must not apply a bid twice.

Use it when hot auctions genuinely exceed what a row lock can serve, or when you want the event-sourced design of Deep Dive 11. For most systems, the database row lock or OCC is enough, and simpler.

Great: an atomic script in Redis, with a durable log behind it

Another way to get a fast serialisation point: keep each live auction's summary in Redis, and apply bids with a Lua script, which Redis runs atomically. The script checks the end time, applies the increment and proxy rules, updates the summary and returns the result. Throughput per auction reaches tens of thousands of operations per second.

But Redis acknowledges writes before replicating them. A failover can lose the last few accepted bids, which violates durability. So the script must be paired with a durable record:

  • write the bid to a durable log first (Kafka with acks=all), and apply it to Redis as the consumer; or
  • use Redis only as a cache of the database's authoritative state.

On its own, this option is a performance optimisation, not a source of truth.

Comparison:

ApproachMax bids per second on one auctionLatencyComplexityTypical use
Row lock (FOR UPDATE)~hundredsLowLowDefault
OCC with version~hundreds, degrading under heavy conflictLowLowDefault when contention is usually low
Single writer via Kafka or actorThousands or moreMediumHighHot auctions, event sourcing
Redis Lua plus durable logThousands or moreLowMedium to highVery hot items, with care for durability

See Concurrency Control and Database Locking and Pattern: Dealing with Contention.

Isolation levels, precisely.

  • In PostgreSQL, Read Committed with an explicit FOR UPDATE on the auction row, or with the conditional UPDATE, is correct and cheapest.
  • Repeatable Read turns a conflicting concurrent update into a serialisation error, which is also correct, with retries.
  • Serializable (SSI) would make even the naive read-then-write safe, by aborting one of the conflicting transactions. It is a valid answer, but it moves the retry logic into the application, and under heavy contention it aborts frequently.

Whichever you choose, explain why the lost update cannot happen. That explanation is what interviewers listen for (see Consistency Models).

2. How does proxy (automatic) bidding work, and why does it matter?#

Most eBay-style auctions do not ask bidders to keep coming back to raise their bid by small steps. Instead, a bidder enters the maximum they are willing to pay. The system then bids on their behalf, by the minimum increment, only as much as needed to keep them in the lead, up to that maximum. eBay calls this automatic bidding.

The rule. Let the leader's secret maximum be M₁ and the second-highest maximum be M₂. The displayed price is:

price = min(M₁, M₂ + increment)

(or the starting price if there is only one bidder). Think of it as the leader paying just enough to beat everyone else.

Processing a new bid with maximum X, given the current leader L with maximum M and current price P:

  1. If X < P + increment: reject, because the bid is too low.
  2. If X ≤ M: the leader stays. The new price is min(M, X + increment), and the new bidder is immediately outbid by proxy. Ties go to the earlier bidder: if X equals M, the leader keeps the lead and the price becomes M.
  3. If X > M: the new bidder becomes the leader. The new price is min(X, M + increment), and the old leader is notified that they have been outbid.

Worked example (increment £1, starting price £10):

StepBidLeader (secret max)Displayed priceOutcome
1Alice max £50Alice (50)£10Alice leads at the start price
2Bob max £30Alice (50)£31Bob outbid instantly by Alice's proxy
3Carol max £45Alice (50)£46Carol outbid instantly
4Dan max £80Dan (80)£51Dan leads; Alice notified
5Alice max £80Dan (80)£80Tie at max: earlier bidder Dan keeps the lead

Why this matters for the system design:

  • The state is more than one number. The serialisation point must hold the leader, the leader's maximum and the current price. A bid's effect depends on all three, which is why the version-based CAS or a row lock is needed, rather than a simple "amount greater than current" condition.
  • One request can produce two logical bids. A new bid that loses to a proxy raises the displayed price on the leader's behalf. Bid history shows both: the new bidder's bid, and the proxy's automatic response.
  • Fewer, larger bids. Proxy bidding reduces the number of incremental bids. But sniping still happens, because bidders reveal their maximum as late as possible (Deep Dive 6).
  • The secret maximum is sensitive. Leaking it, through an API, a cache or logs, would let competitors and sellers exploit the leader. Store it only at the serialisation point, and redact it everywhere else.

The economics, briefly. With proxy bidding, the winner pays about the second-highest maximum plus one increment. This resembles a second-price auction, analysed by William Vickrey in "Counterspeculation, Auctions, and Competitive Sealed Tenders" (Journal of Finance, 1961). In a sealed second-price auction, bidding your true value is a dominant strategy. Online ascending auctions with proxies are not exactly sealed-bid, because bidders see prices and can react, so late bidding persists. But the design intent is similar: let people state their true maximum once, and let the system do the rest.

3. How do we make bidding fault tolerant and durable?#

"Your bid was accepted" is a promise. If we acknowledge a bid and then lose it in a crash, we may award the item to the wrong person. That is a serious trust and legal problem. So durability before acknowledgement is non-negotiable.

What can fail:

  • the Bid Service instance, before or after committing;
  • the database primary, right after commit, before replication;
  • the network, between the client and us, after we committed but before the client saw the answer;
  • the fan-out path, so the bid is saved but watchers never hear of it.

Durable commit.

  • Commit the bid transaction to a database primary with synchronous replication to at least one standby, in another availability zone. In PostgreSQL that means setting synchronous_standby_names and synchronous_commit = on (or remote_apply if reads from that standby must see it).
  • Only after the commit returns do we answer the client. If the primary dies a millisecond later, the standby has the bid and is promoted.
  • The cost is a few milliseconds of cross-zone round trip per commit. That is acceptable at a 200 ms latency budget (see Database Replication).

Asynchronous replication is not enough on its own. With async replicas, a failover can lose the last second of commits: bids that bidders were told were accepted. Some teams accept this trade-off for other data, but it is not acceptable for bids.

A log-first alternative. Write each bid request to Kafka with acks=all and min.insync.replicas=2: the broker acknowledges only once it is on at least two replicas' disks or page caches. A consumer then applies the bids in order, the single-writer design of Deep Dive 1.

  • The log is the durable record. Even if the consumer or database crashes, the bids remain and are re-applied.
  • The client is told "received" when the log write succeeds, and "accepted" or "outbid" when the consumer has processed it. Usually this is milliseconds later, delivered via the response, or via push if the request returned early.
  • This splits durability (log append) from decision (processing). Both must be robust.

See Apache Kafka in Practice.

Idempotent bids. Network failures leave the client unsure whether its bid landed. The client sends an Idempotency-Key (a UUID per bid attempt). The UNIQUE (auction_id, bidder_id, idempotency_key) constraint turns a retry into a lookup of the original result, so a retried bid can never become a second bid. With the log-first design, deduplicate in the consumer using the same key.

Never lose the event to watchers.

  • Use a transactional outbox: an outbox row written in the same transaction as the bid. A relay (or CDC with Debezium) publishes it to Kafka.
  • If the Bid Service crashes after commit, the outbox row is still there, and it will be published.
  • Consumers (fan-out, notifications, analytics) are idempotent, keyed by (auction_id, version), so redelivery is harmless (see Change Data Capture and the Outbox Pattern).

The bid log as audit trail.

  • The bids table (or Kafka topic, retained and archived) is an append-only history.
  • Disputes, such as "I bid £100 at 20:59:58", are resolved from server timestamps and sequence numbers.
  • Corrections (support-approved retractions) are new events, not edits, so history is never silently rewritten.

Disaster recovery. Regular backups with point-in-time recovery for each shard, plus cross-region replicas for regional disasters (see Disaster Recovery and Backups). During a regional failover, live auctions near their end may need their end times extended by the outage duration, a business rule the close logic must support. Bidders should not lose an auction because the site was down.

Graceful degradation.

  • If the real-time path fails, bidding continues, and watchers fall back to polling.
  • If the notification service fails, bids are unaffected, and notifications catch up from Kafka.
  • If the bid path for a shard fails, those auctions are paused and extended. Do not accept bids into a non-durable buffer.

4. How do watchers see the current highest bid in real time?#

When a new bid is accepted, everyone looking at that auction should see the new price within about a second. Our numbers: up to ~1 million concurrent watchers in total, and ~100,000 on a hot auction.

Client-to-server protocol options:

  • Basic: short polling. The page calls GET /auctions/7 every few seconds.
    • Simple, stateless, cache-friendly. A 1-second micro-cache at the edge collapses many watchers' polls into one origin request.
    • But the delay is up to the polling interval, and most polls return "no change". With 1M watchers polling every 2 seconds, that is 500,000 requests per second, mostly wasted. Acceptable as a fallback, not as the main mechanism.
  • Better: long polling. The client asks "anything newer than version 41?", and the server holds the request open until something changes or a timeout (for example 30 seconds) passes.
    • Near-instant updates, using plain HTTP.
    • Each update requires a new request, with its headers and connection overhead. Under rapid bid sequences, clients spend time reconnecting.
  • Great: Server-Sent Events (SSE). One long-lived HTTP response, over which the server streams events (data: {...}) whenever bids happen.
    • One-directional, which is all we need here: bids go through the normal POST API, and updates come back over SSE.
    • It works through most proxies, reconnects automatically, and supports Last-Event-ID, so a reconnecting client resumes from the last version it saw.
    • Over HTTP/2, many streams share one connection, which avoids the HTTP/1.1 browser limit of about six connections per domain.
  • Also great: WebSockets. A full-duplex connection. It is useful if the same channel also carries chat, or client actions at high frequency. For a price ticker, it adds complexity (a custom protocol, proxies, load balancer settings) without much benefit over SSE.

Server-side fan-out: getting the event to the right gateway. Watchers of auction 7 are spread across many Realtime Gateway nodes. When a bid is accepted, how does each node learn about it?

  • Pub/sub per auction. Each gateway subscribes to the channels for the auctions its clients watch, for example Redis Pub/Sub channel auction:7. Fan-out workers consume bid events from Kafka and publish to the channel. Redis delivers to every subscribed gateway, which writes to each local connection.
    • Simple, and gateways remain stateless with respect to routing.
    • Redis Pub/Sub is fire-and-forget: a gateway that is disconnected misses messages. Clients must therefore resync on reconnect, using the version number (Deep Dive 5).
    • At very high channel counts, sharded pub/sub (SSUBSCRIBE in Redis 7 Cluster) or Kafka-based fan-out spreads the load.
  • Consistent hashing of auctions to gateways. Route all watchers of auction 7 to the same gateway node, chosen by hashing the auction id (see Consistent Hashing). Fan-out workers then send each event to exactly one node.
    • Efficient: one message per auction, not one per subscribed node.
    • Hot auctions concentrate on one node, and rebalancing on node changes moves connections. Users watching several auctions need connections to several nodes.
    • It works well when the number of watchers per auction is bounded.
  • Hybrid. Pub/sub for normal auctions. For hot auctions (above, say, 10,000 watchers), use a two-level tree: a few relay nodes subscribe to the channel, and each feeds many edge gateways. The same pattern shows up in live-comment systems (see the live-comments problem).

Coalescing for hot auctions. In the final seconds, a hot auction may accept 50 bids per second. Watchers do not need 50 messages per second. Each gateway can coalesce per auction, and send the latest state at most every 200 to 500 ms. Since each message carries the full current state (price, leader indicator, bid count, version), dropping intermediate messages loses nothing. Bidders who need precise feedback get it from their own POST response.

Message content.

  • Send {auctionId, version, currentPrice, bidCount, endsAt, leaderMasked}.
  • Never send the leader's maximum.
  • Send per-user facts ("you are winning", "you've been outbid") on a user-specific channel, or compute them on the client by comparing the update with the user's own last bid result.
  • endsAt matters because soft-close extensions change it (Deep Dive 6).

Capacity. One million SSE connections, at ~50,000 to 100,000 connections per gateway node with tuned kernels and async I/O, means 10 to 20 nodes, plus headroom. At 5,000 accepted bids per second × the average fan-out, plus coalesced hot auctions, the outbound message rate is in the hundreds of thousands per second. That is manageable across that fleet.

Reconnect storms. When a gateway restarts, its clients reconnect to other nodes at once. Add jittered backoff on the client. On reconnect, send the current snapshot first (from the Redis summary cache), then resume streaming.

See Pattern: Pushing Realtime Updates and Pub/Sub and Event Streaming.

5. How do we guarantee fairness and a consistent order of bids?#

"Fair" in an auction means at least three things:

  1. One order: everyone agrees which bid came first and which is highest.
  2. The rules apply equally: the same increment, tie-break and deadline for everyone.
  3. No hidden advantage: nobody profits from seeing information early or from their clock being fast.

Who decides order? Not the client. Client clocks are wrong by seconds, or by minutes, or are deliberately falsified. Network latency also varies. A bid "sent first" from a phone on a slow network may arrive later than one sent second from a fibre connection. The only workable definition is: the order in which bids reach the serialisation point. That is the row lock, the CAS or the single writer for that auction. The version or sequence number assigned there is the canonical order. The server timestamp, taken from the database clock in the same transaction, is recorded for display and disputes, but the sequence decides.

Ties. Two bids of the same amount: the earlier one in sequence wins. With proxy bidding, an existing leader whose maximum equals a new bid keeps the lead. The rule is simple, deterministic and published in advance.

Monotonic display. Clients receive updates over SSE, but also from their own POST responses and from page reloads (cache), so messages can arrive out of order. A client that receives version 43 and then a delayed version 42 must ignore 42. Every message carries the version, and the client only moves forward. This guarantees that no watcher ever sees the price go down, which would be a confusing and trust-destroying glitch.

Caches must not go backwards either. When the fan-out worker updates the Redis summary, it should write only if the incoming version is newer, using a small Lua script: if new.version > stored.version then set. Otherwise a delayed event could overwrite a newer one. The same applies to CDN micro-caches: keep their TTL short (1 second), and let the version in the payload tell clients whether it is newer than what they have.

Read-your-writes for the bidder. After bidding, the bidder must see their own bid's effect immediately, even if their page then reads from a lagging replica or a stale cache. Options:

  • return the full new state in the POST response, and have the client hold onto that version as a floor;
  • route that user's reads to the primary for a few seconds after a bid.

Equal information. Everyone receives the same public updates. Coalescing must not create systematic advantages: every gateway coalesces with the same interval, and it is the bid submission time at the serialisation point that counts, not who saw the price first.

Latency fairness near the deadline. A bidder far from the auction's home region has 100 to 200 ms more latency, so their last-second bids arrive later. Truly equalising this is impossible. The mitigations are product rules:

  • soft close (Deep Dive 6) removes the advantage of last-millisecond timing;
  • proxy bidding lets everyone state their maximum early.

Some platforms display "your bid must be received before the end time" explicitly, to set expectations.

Fairness against manipulation (shill bidding, collusion, bots) is covered in Deep Dive 12.

6. How do we end auctions exactly on time?#

Every auction has a deadline, and there are ~1.4 million deadlines a day, clustered at popular times. Two separate concerns hide here:

  • Correctness: no bid after the end time is ever accepted.
  • Timeliness: the auction is marked ended, the winner determined and notified, promptly.

Make correctness independent of the scheduler. The bid transaction itself checks now() < ends_at, using the database's clock, at the serialisation point. A bid arriving one millisecond late is rejected, even if no job has yet marked the auction as ended. The closing scheduler can therefore be seconds late without any correctness impact. Its only job is to make the auction look ended and to start post-auction processing. This is the same principle as the implicit-expiry hold in the ticket-booking problem: never let a background job be on the correctness path.

Basic: a cron job that scans for ended auctions. Every minute, run SELECT id FROM auctions WHERE status = 'LIVE' AND ends_at <= now(), and close each one.

  • Simple. With the partial index on ends_at, the query is cheap.
  • Lag of up to a minute before winners are notified and pages show "ended". Large batches at popular end times then cause bursty load.
  • If the cron host dies, nothing closes until someone notices.

Better: frequent polling with work distribution. Every second, each Close Worker claims a small batch of due auctions:

SELECT id FROM auctions
WHERE status = 'LIVE' AND ends_at <= now()
ORDER BY ends_at
LIMIT 100
FOR UPDATE SKIP LOCKED;     -- many workers share the work without double-processing
  • Lag of about a second. Workers scale horizontally. A dead worker's rows are simply picked up by others, because nothing was committed.
  • The cost is a steady stream of polling queries on every shard: one per second per worker. That is cheap with the index, but it is wasted work when nothing is due.

Great: a timer service (time-bucketed schedule) that fires at the deadline. Index deadlines by time bucket, so the scheduler only touches what is due:

  • Redis sorted set scored by end time: ZADD closes <endsAtMs> <auctionId>. A scheduler loop runs ZRANGEBYSCORE closes -inf <now> LIMIT 0 500, enqueues those auctions for closing, and removes them. Partition the set by auction-id hash across Redis shards, each with its own loop.
  • Bucketed table: close_schedule(bucket_minute, auction_id). A worker reads the current minute's bucket at the start of each minute, and loads it into an in-memory timing wheel, the data structure described by Varghese and Lauck in "Hashed and Hierarchical Timing Wheels" (SOSP 1987). It fires each timer at its exact second. Timing wheels give constant-time insert and expiry for huge numbers of timers.
  • Delay queues: many message queues support delayed delivery, but often with a short maximum delay (for example 15 minutes in Amazon SQS). Use them as the last stage: a coarse scheduler moves auctions due in the next few minutes into the delay queue, which delivers each close message at the right second.
  • Workflow engines: a durable timer per auction in Temporal ("sleep until ends_at, then close") is elegant for moderate volumes. At 1.4M timers per day it is feasible, but needs capacity planning (see Temporal and Workflow Engines).

In all cases, keep a safety sweep: the polling query above, run every minute, catches anything the timer path missed. And make closing idempotent: UPDATE ... SET status = 'ENDED' WHERE id = ? AND status = 'LIVE'. Duplicate triggers are then harmless. For the general problem of firing millions of timed tasks reliably, see the job-scheduler problem.

Hard close versus soft close.

  • Hard close (eBay style): the auction ends at exactly the published time. This encourages sniping: bidding in the final seconds so others cannot respond. Many bidders use sniping tools that submit at T minus a few seconds. Technically, this means huge last-second bursts on hot auctions, so the bid path's per-auction capacity must handle the spike.
  • Soft close (anti-sniping): if a bid is accepted within the last N minutes (say 2), the end time extends by N minutes from that bid. The auction ends only after N quiet minutes. Many auction houses and charity platforms use it. It is fairer to slower or distant bidders, and it spreads load out.

Implementing soft close correctly. The extension must happen inside the bid transaction, at the serialisation point: ends_at = greatest(ends_at, now() + interval '2 minutes') when the bid is accepted near the end. Otherwise a concurrent close could end the auction just as a valid bid extended it. Then:

  • reschedule the timer: add the new deadline to the sorted set or bucket. The old timer still fires, but the close's now() >= ends_at check makes it a no-op;
  • push the new endsAt to all watchers, so their countdowns update.

Clocks. All deadline decisions for one auction use one clock: that of the database primary holding it. App-server clocks are used only for scheduling hints, never for acceptance. Keep servers synchronised with NTP or a cloud time service, and accept that a few milliseconds of skew between shards is irrelevant, because each auction lives on one shard. During a primary failover, the new primary's clock takes over. Small skew there could shift the effective end by milliseconds, which is acceptable. If an outage lasts longer, the extension policy from Deep Dive 3 applies.

"Ending soon" notifications are just more timers: at T minus 1 hour and T minus 10 minutes, notify watchers. They use the same scheduler, at lower priority.

7. How do we scale to 10 million concurrent auctions?#

The good news: auctions are independent. Bids on auction 7 never interact with bids on auction 8, so the system shards cleanly by auction id.

Storage and write path.

  • 10M live auctions at ~1 KB, plus a growing bid history, fit in a handful of shards. Even a single large PostgreSQL primary could hold the live set. Sharding is about write throughput and blast radius, not size.
  • A peak of 20,000 bids per second overall, at maybe 3,000 to 5,000 short write transactions per second per primary (with synchronous commit to a standby), suggests 5 to 10 shards, plus headroom. Use more, smaller shards, for example 32 logical shards mapped onto fewer physical clusters, so they can be split later without re-hashing.
  • Route by hash(auction_id), or by a directory, so hot sellers' auctions do not cluster (see Partitioning and Sharding).
  • Stateless Bid Services scale horizontally behind the load balancer. Each request goes to the shard owning its auction.

Hot auctions. One auction gets hundreds of bids per second in its final minute. That is a single-row hotspot, and sharding cannot split a single row. Options, in order:

  1. Make the critical section short. One row lock, one insert, one update, a synchronous commit: perhaps 2 to 5 ms. That yields 200 to 500 bids per second per auction, which handles all but the most extreme cases.
  2. Reject early. Many incoming bids are already too low by the time they are processed. Check the cached current price before taking the lock, and reject obviously losing bids immediately. That bypasses the lock for most of the storm. The authoritative check still happens under the lock.
  3. A single writer per auction (Deep Dive 1): processing in memory, in order, raises the per-auction ceiling to thousands per second.
  4. Product levers: soft close spreads the burst. Rate limits per bidder per auction (for example 1 bid per second) cut bot floods.

Read path.

  • Auction pages at ~100,000 per second are served from the CDN (static content), the Redis summary cache (price) and read replicas (details).
  • Cache hit rates above 95 percent mean the shard primaries see almost no read traffic (see Pattern: Scaling Reads).

Event path. Kafka with, say, 64 to 256 partitions, keyed by auction id, keeps per-auction order, and handles tens of thousands of events per second easily. Fan-out workers scale with partitions.

Real-time tier. 1 million connections across 10 to 20 gateways. Redis pub/sub sharded by channel. Hot auctions use relay trees.

Scheduler. 1.4 million closes per day, peaking at perhaps 100 to 500 per second at popular end times. The timer store is partitioned, and Close Workers scale horizontally. Closing is a few rows per auction, so this is light.

Sizing summary:

TierPeak loadRough size
Bid Service20k bids/s10 to 20 instances
Auction DB20k write tx/s, plus close traffic8 to 16 shard primaries, each with a sync standby and replicas
Kafka~30k events/s6 brokers, ~128 partitions
Redis summary cache~100k reads/s, ~10 GB3 to 6 primaries with replicas
Realtime gateways1M connections, ~300k messages/s15 to 25 nodes
Scheduler~500 closes/s at peakA few workers per partition

These are planning estimates; validate them with load tests (see Capacity Planning and Load Testing).

8. How do we serve the auction page fast to millions of viewers?#

An auction page combines three kinds of data, each changing at a different rate:

DataChangesServed fromFreshness
Item title, description, photos, seller infoRarely (edits locked once bids exist)CDN plus a details cacheMinutes
Current price, bid count, high bidder, end timeOn every bidRedis summary cache plus the SSE streamUnder a second
Bid history (amounts, masked bidder names)On every bidA read replica or a history store, paginatedSeconds

Split the page along these lines. The static shell and photos come from the CDN. The summary comes from a small JSON endpoint backed by Redis. History loads lazily on demand. This keeps the expensive, fast-changing part tiny: a summary is ~200 bytes.

The summary cache, kept fresh by events rather than TTLs.

  • The Bid Service commits the bid, then the event (via the outbox) reaches a Cache Updater. It writes HSET auction:{id} price ... version ... with a version guard (Deep Dive 5): the update applies only if its version is higher than the stored one, so out-of-order events never regress the price.
  • A TTL of, say, one hour is just a backstop. On a miss, read from a replica and repopulate, using request collapsing so a cold hot-auction does not stampede the database (see Cache Failure Modes: Stampedes, Hot Keys and Penetration).
  • Hot keys: a popular auction's summary might take 20,000 reads per second. Redis handles that on one shard, but add a tiny in-process cache (100 ms to 1 s) on API servers for the hottest keys. Viewers then read through the SSE stream anyway, so polling of the summary is rare.

Can the CDN cache the summary? With a very short TTL (1 to 2 seconds) and request collapsing, yes. This turns 20,000 reads per second into a handful of origin requests per edge. The cost is up to 2 seconds of staleness, which is fine for display, because the bid path never trusts cached prices. For a bidder's own view, read your own write directly from the bid response (Deep Dive 5).

Images. Sellers upload several photos per item. Serve them through the CDN with resized variants (thumbnail, gallery, zoom), produced by an image pipeline after upload. Photos dominate bytes: a page with 8 photos at ~150 KB each is 1.2 MB, against a 200-byte summary.

Search and browse pages ("ending soon in Watches", "under $50") are served from the search index (Deep Dive 9). Their prices can be seconds stale, which is acceptable. Clicking through shows the live price.

Client-side countdowns. The page shows a ticking timer to endsAt. Don't trust the device clock for it: phones and laptops are often seconds or minutes off. Send the server time with the summary and with every SSE event. The client computes its offset (serverNow − localNow, adjusted for half the request's round trip) and counts down using local time plus that offset. A soft-close extension simply sends a new endsAt, and the countdown jumps forward. Render "ending..." in the last second, rather than "ended", until the server confirms. That avoids a misleading display for a bid that is still being processed.

9. How do sellers post items, and how do buyers find them?#

Posting an item looks simple but has several steps:

  1. Upload photos directly to object storage via pre-signed URLs. Large binary traffic never touches the API servers (see Pattern: Handling Large Files and Blobs). A processing job then validates, scans and resizes them.
  2. Create the item and auction in one transaction: title, description, category, condition, starting price, optional reserve, optional buy-it-now price, start and end times. Validate the rules: end time is in the allowed window (for example 1 to 10 days), starting price is positive, and the reserve is not below the start.
  3. Schedule the start (if future) and the end in the timer service (Deep Dive 6).
  4. Publish an AuctionCreated event. Consumers index it for search, run trust and safety checks (prohibited items, counterfeit signals), and notify followers of the seller.

Editing rules. Before the first bid, the seller can edit almost anything. After bids exist, many marketplaces restrict edits to additions (for example adding to the description), because changing the item under existing bidders would be unfair. Enforce this in the Auction Service with a check on bid_count = 0, inside the same transaction as the edit.

Search. Buyers search by keyword, category, price range, condition, location and "ending soonest". That is a classic inverted-index workload. Use Elasticsearch or OpenSearch fed by change data capture from the auctions database (see Change Data Capture and the Outbox Pattern and Elasticsearch and Search Systems):

  • the document holds title, description, category, attributes, current price, bid count and ends_at;
  • current price updates happen on every bid. At 20,000 bids per second, re-indexing every one is wasteful. Coalesce: update the index at most every few seconds per auction, and always on close;
  • ended auctions move out of the live index (or a status filter hides them) into a "sold items" index, which sellers use for price research.

"Ending soonest" sorting is just sort: ends_at asc with a filter on ends_at > now. The index needs nothing special, because the field is a plain date.

10. What happens when an auction ends?#

Closing is a small multi-step workflow (see Pattern: Multi-Step Processes and Workflows):

  1. Freeze. Conditional update status = 'ENDED' WHERE status = 'LIVE' AND ends_at <= now(). From this moment no bid can commit: the bid transaction checks both the status and the time.
  2. Determine the outcome. The winner is the current high bidder, at the current price. Reserve check: if a reserve exists and the high bidder's maximum is below it, the outcome is RESERVE_NOT_MET. With proxy bidding, the price is raised to the reserve automatically if the high bidder's maximum is at or above it, so "reserve met" depends on the max, not the visible price. With no bids, the outcome is NO_SALE.
  3. Write the outcome row (auction_outcome) idempotently, keyed by auction id.
  4. Publish AuctionEnded. Consumers:
    • notify the winner ("You won! Pay within 48 hours"), the seller, and the losing bidders;
    • create an order in the order or checkout service, which handles payment and shipping. The auction system's job ends with a trustworthy outcome;
    • update search and the live gateway (the final price and "ENDED" to all viewers).
  5. Payment. The winner pays through the normal checkout, using the payment platform (see the payment-system problem). If they don't pay within the window, the seller can open an unpaid-item case and, on some platforms, send a second-chance offer to the next-highest bidder at their max bid. The bid history makes the runner-up easy to find.

Each step is idempotent and retry-safe. A workflow engine or a chain of event consumers with an outbox both work. Notifications fan out at most a few dozen messages per auction, which is trivial compared with the bid path.

Notification fan-out during the auction.

  • Outbid alerts are the most valuable notification in the product: they drive the next bid. Send them immediately via push and email whenever a user's maximum is beaten. That is one message per accepted bid at most (only the previous leader is outbid).
  • Ending soon alerts go to watchers at fixed offsets (Deep Dive 6). A popular auction with 50,000 watchers means 50,000 notifications at T minus 1 hour. Queue them through the notification service with rate control, so many auctions ending at once do not spike the push providers.

11. How should we store bid history?#

Bids are an append-only log. A bid is never updated or deleted (retractions are new events, Deep Dive 12). The auction's current state, meaning price, leader, count and end time, is a pure function of its bid sequence. That is exactly the shape event sourcing suits (see Event Sourcing and CQRS).

What we do in practice: event-sourced data, state-stored row.

  • The bids table (or the Kafka log, in the single-writer variant) is the authoritative history. The auctions row holds the materialised current state, updated in the same transaction. We gain fast reads of current state without replaying, plus a complete history for audits and disputes.
  • Replay as verification. A nightly job replays each ended auction's bids through the proxy-bidding function and checks that the outcome matches the stored one. A mismatch means a bug, and the job catches it before customers do.
  • CQRS read models. Bid history pages, the "my bids" view per user, and seller analytics are separate projections built from the bid event stream. Each is shaped for its own query: (auction_id, seq) for history; (bidder_id, created_at) for "my bids".

Volume and retention.

  • 14 million bids per day at ~200 bytes is about 3 GB per day, or ~1 TB per year.
  • Keep live and recently ended auctions in the hot OLTP store, partitioned by month.
  • Move older bids to cheaper storage: a columnar warehouse for analytics, or object storage in Parquet. Legal and dispute retention for marketplaces is typically several years. Confirm the requirement with legal, rather than inventing a number.

Event schema evolution. Bid events live for years, and the code reading them changes many times. Give every event a schema version, and register its schema (Avro or Protobuf, with a schema registry). Make only backward-compatible changes: add optional fields, never rename or re-type them. When the proxy rules change (a new increment table, say), record the rules version in the auction, not inside each bid's logic. A replay years later can then apply the rules that were in force at the time. Without this discipline, the promise that "history is replayable" quietly breaks the first time someone changes a field. It usually surfaces during a dispute, which is the worst time to find out.

Privacy. Public history masks bidder identities (for example "a***b (153)"), to stop bidders being targeted off-platform. Only the seller and support see more, according to policy. The raw table holds the real ids, so access controls and audit logs on it matter (see Security Fundamentals for System Design).

12. How do we stop fraud and abuse?#

Auctions attract specific abuse, because prices are set by other people's behaviour:

  • Shill bidding: a seller, or their friend, bids on their own item to push the price up. Signals include:
    • bidder accounts linked to the seller (same device, payment instrument, address or IP ranges);
    • bidders who bid often on one seller's items but rarely win;
    • bids that stop just below the leader's maximum, as if probing it. Detection is a streaming and batch ML problem, using the bid event stream plus account graphs. Bids from linked accounts can also be blocked synchronously by a check in the bid path (a cached "linked to seller" flag).
  • Bid retractions: allowed only in narrow cases, such as an obvious typo ($1,000 instead of $100). Model them as BidRetracted events. They trigger a recomputation of the price from the remaining bids, by replaying the proxy-bidding function. A retraction near the end is suspicious (it can be used to discover a rival's maximum), so rate-limit and review them.
  • Bots and sniping tools: a small number of automated clients can flood a hot auction in its last seconds. Apply rate limits per user per auction, and per user globally (see Rate Limiting and Throttling). Proxy bidding reduces the advantage of sniping, because your maximum still defends you. Soft close removes it.
  • Non-paying winners and bid manipulation by new accounts: require verified payment methods, or minimum account history, to bid on high-value items. Bid limits scale with account trust.
  • Account takeover: an attacker uses stolen credentials to bid huge amounts. Use step-up authentication for bids far above a user's history, and alert on unusual bidding (see Authentication and Authorization).

These checks must not slow the bid path. Keep synchronous checks to cheap cached lookups (a few milliseconds total), and do heavier analysis asynchronously from the event stream, with the power to cancel bids or suspend accounts after the fact.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Hot auction in its final minuteHundreds of bids per second contend for one row lock. Latency rises and bids time out.Short transactions, early rejection of losing bids from the cached price, a single writer per hot auction, soft close, rate limits per bidder
Shard primary failsBids for auctions on that shard fail for the failover window, typically 10 to 60 secondsSynchronous standby with automatic failover, so no accepted bid is lost. Retry with idempotency keys. Extend end times for auctions that ended during the outage.
Two bids racing on stale readsBoth accepted, or the price regressesSerialise per auction: row lock, OCC version check, or a single writer. Never trust a cached price on the write path.
Close scheduler lags or diesAuctions stay "LIVE" in the UI after the deadline. Winners are notified late.The bid path enforces now() < ends_at itself, so correctness is unaffected. A safety sweep and several workers with SKIP LOCKED. Alert on close lag.
Burst of closes at popular end timesClose Workers and notification fan-out spikeTiming wheels spread work to the exact second. Scale workers on queue depth. Queue notifications with rate control.
Outbox relay or Kafka downLive updates, cache refreshes and search updates stall. Bids still commit.The outbox buffers events in the database. Alert on relay lag. Clients fall back to polling the summary. Replay once healthy.
Summary cache out of date or regressedViewers see a wrong priceVersion-guarded updates, so stale events never overwrite newer ones. A TTL backstop. The bid path never reads the cache for decisions.
Realtime gateway crashTens of thousands of viewers drop at once and reconnect togetherJittered exponential backoff on clients. Resume from the last version via Last-Event-ID. Connection draining on deploys.
Very popular auction with 1M watchersA single pub/sub channel and its subscribers saturateCoalesce updates (at most a few per second), and fan out through relay trees across gateways
Duplicate bid submissions (double-click, retries)The same user bids twice, or a payment dispute followsIdempotency-Key per bid attempt, with a unique constraint on (auction_id, idempotency_key)
Clock skew between serversBids accepted after the end on one server, rejected before it on anotherAll acceptance decisions use the database clock of the auction's primary. App-server clocks are hints only.
Shill bidding and bot floodsUnfair prices and loss of trustSynchronous cheap checks (linked accounts, rate limits), plus asynchronous ML detection with the power to void bids

What Interviewers Expect#

Mid-level.

  • Gets the core entities (Item, Auction, Bid, User) and APIs right, including the idempotency key for bids.
  • Explains why a naive read-then-write is a race, and fixes it with a row lock or a conditional update.
  • Picks SSE or WebSockets for live price updates, and explains polling's cost.
  • Handles auction end by checking ends_at in the bid path and running a scheduled job to close auctions.

Senior.

  • Compares the consistency options (pessimistic lock, OCC, single writer) with their throughput and failure trade-offs, and explains why the bids table alone cannot be locked (phantoms).
  • Designs proxy bidding correctly, including ties and the reserve check against the maximum, not the visible price.
  • Makes bids durable before acknowledging (a synchronous replica or Kafka acks=all) and uses an outbox so events are never lost.
  • Scales the push tier with pub/sub, coalescing and reconnect storms in mind, and puts versions on events so the UI never goes backwards.
  • Shards by auction id, and has a plan for the hot-auction hotspot.

Staff and above.

  • Separates correctness (the serialisation point, the DB clock) from timeliness (the scheduler, notifications), so that no background job is on the correctness path.
  • Discusses hard versus soft close as a product and systems decision: sniping, load spikes and how an extended end time propagates through the system.
  • Designs for failure: failover with zero bid loss, end-time extension policies after outages, degraded modes (bids accepted while live updates lag).
  • Brings in fairness (ordering at the serialisation point, latency fairness), fraud (shill bidding, retractions) and auditability (replaying the bid log to verify outcomes).
  • Quantifies everything: bids per second per shard, per-auction ceilings, connection counts, fan-out volume, storage growth.
Deep Dive: the auction lifecycle as a state machineShow

Many bugs in auction systems are illegal state transitions: a cancelled auction that still accepts bids, or a closed auction re-opened by a late retry. Write the lifecycle down explicitly, and enforce every transition as a conditional update on the current state.

Rules that the state machine makes explicit:

  • Only LIVE accepts bids. The bid transaction includes status = 'LIVE' in its conditional update. A cancellation and a bid racing each other are therefore serialised, and exactly one wins.
  • Cancellation with bids is a policy question. Many marketplaces allow it only for good reasons (the item was lost or damaged) and may charge the seller a fee. In the system, it is a transition that also notifies every bidder and voids their bids. Each bid row stays in the log, with a CANCELLED outcome event.
  • ENDED is a short-lived state between freezing the auction and writing the outcome. A sweep looks for auctions stuck in ENDED for more than a minute, and finishes them.
  • Relisting an unsold item creates a new auction for the same item, rather than re-opening the old one. History stays clean, and each auction's bid log has exactly one lifetime.
  • Terminal states never change. A late AuctionEnded retry finds the state already SOLD, and does nothing.

Store the state as an enum column, and keep a small auction_transitions table (from, to, at, actor). Support and dispute teams then see the full story of every auction without reading logs.

Deep Dive: contention maths for a hot auctionShow

How much traffic can one auction absorb? Model the auction row as a single server queue: bids arrive at rate λ, and each holds the lock for a service time S.

Pessimistic locking.

  • Capacity is 1/S. With S = 4 ms (read row, compute, insert bid, update row, insert outbox, synchronous commit to a nearby standby), that is 250 bids per second.
  • In an M/M/1 queue, the mean time in the system is S / (1 − ρ), where ρ = λS is the utilisation. At λ = 200 per second, ρ = 0.8, and the mean latency is 4 ms / 0.2 = 20 ms. At λ = 240, ρ = 0.96, and it is 100 ms. Near capacity the queue explodes. That is why a hot auction needs headroom, not just enough average capacity.
  • The synchronous commit dominates S. A standby in the same region adds ~0.5 to 2 ms. One in a distant region would add 30 to 80 ms, capping a single auction near 15 to 30 bids per second. That is a strong reason to keep the synchronous replica close and replicate further asynchronously.

Optimistic concurrency.

  • Each attempt reads the row, computes, and then tries the conditional update. If another bid commits during that window W, the attempt fails and retries.
  • With Poisson arrivals at rate λ, the probability that at least one other commit lands in the window is about 1 − e^(−λW). With W = 5 ms and λ = 50 per second, that is 1 − e^(−0.25) ≈ 22 percent. At λ = 200 per second it is 1 − e^(−1) ≈ 63 percent, and the retries add even more load. OCC is excellent at low contention (most auctions, most of the time) and degrades sharply on hot auctions.
  • That is the quantitative basis for the "switch to pessimistic or single writer when the retry rate rises" rule.

Single writer in memory.

  • With state in memory, S becomes the cost of validating a bid and appending it to a durable log. Batched appends (group commit) make it tens of microseconds per bid. A single auction can then absorb thousands of bids per second.
  • Latency is dominated by the log append (a Kafka produce with acks=all is a few milliseconds in-region), and many bids share each append.

Early rejection's effect. If a fraction f of arriving bids is already below the minimum, and those are rejected from the cache, the load on the row is λ(1 − f). In the final seconds of a contested auction, f is often high, because many sniping tools fire at similar prices and only the first succeeds. Rejecting 60 percent of arrivals moves ρ from 0.96 to under 0.4, and the queueing delay falls from ~100 ms to under 7 ms.

Deep Dive: building the single-writer bid engineShow

When an auction (or a whole category of auctions) needs more than a database row can give, the single writer design processes all bids for an auction in one thread, in order, from memory. Here is how to build it without losing correctness.

The pieces.

  • Partitioning: the input topic is keyed by auction id, so all bids for an auction land in one partition, in arrival order. Each engine instance owns a set of partitions. It keeps the state of their live auctions in memory: price, leader, leader's max, version and end time.
  • Decide, then log: the engine validates each bid against in-memory state, and appends the result to the output log before applying it (or applies it and appends it before acknowledging). The output log is the durable record. The database is a downstream projection.
  • Responding: the API instance that received the request waits for the result with a matching request id. It can consume a reply topic, or the engine can respond directly over RPC after the log append. The client sees ACCEPTED only after the result is durable.
  • Recovery: when an engine dies, another one takes over its partitions. It rebuilds state by loading the latest snapshot (written every few seconds or every N bids) and replaying the output log from the snapshot's offset. With snapshots, recovery takes seconds.
  • Exactly-once effects: if the engine crashes after appending a result but before committing its input offset, the replacement will see the input bid again. It must recognise it (by idempotency key, which is kept in memory per auction) and skip it. Kafka transactions, which write the output and commit the input offset atomically, are another way to get the same effect.
  • Time: the engine decides "is this bid before ends_at?" using its own clock at processing time. Because a single process makes every decision for an auction, ordering is consistent. Synchronise the clock tightly, and include the decision timestamp in each result for audit.
  • Fencing: during a partition hand-over, two engines could briefly both think they own a partition. Kafka's consumer-group generation, together with transactional producer fencing (an old producer epoch is rejected), keeps the old owner from writing. This is the same idea as fencing tokens for locks (see Distributed Locks).

When is it worth it? It is more complex than a row lock: snapshotting, replay, request-reply over a log, and fencing. Use it when measurements show the database path cannot hold your hottest auctions, or when you want a uniform, very high-throughput engine. Exchanges' matching engines (see the stock-exchange problem) use the same pattern for the same reason.

Deep Dive: bidders around the world (multi-region)Show

Bidders join from every continent, but each auction must have one serialisation point. Two regions accepting bids on the same auction independently would produce conflicting leaders, with no correct way to merge them. "Last writer wins" would silently discard a valid higher bid.

Home-region design.

  • Each auction has a home region, usually the seller's, chosen at creation time and stored in the auction id or a directory.
  • Bids from anywhere are routed to the home region (see Multi-Region and Global Data). A bidder in Sydney bidding on a London auction pays ~250 to 300 ms of round trip. Inside the home region, the bid path is unchanged.
  • Reads (auction pages, history) and real-time streams are served locally in every region, from asynchronous replicas and a local push tier. A watcher in Sydney sees updates ~150 ms later than a watcher in London. For display that is fine.

Latency fairness. In a hard-close auction, a distant bidder's last-second bid has to travel further, so it is more likely to arrive after the end. Options:

  • Accept it as physics, and say so clearly in the UI ("bids must be received by our servers before the end time").
  • Soft close removes most of the disadvantage: a late bid extends the auction and gives everyone time to respond.
  • Edge timestamping (accepting bids by the time they reached a nearby edge) sounds fairer, but it moves trust to many clocks and opens the door to manipulation. Most systems avoid it.

Disaster recovery. If the home region fails, auctions homed there pause. Fail them over to another region by promoting a replica. Bids in the replication lag window may be lost, unless replication is synchronous across regions, which costs every bid the cross-region round trip. A common compromise: synchronous replication to a nearby second zone, asynchronous replication across regions, plus the end-time extension policy for affected auctions (see Disaster Recovery and Backups).

Deep Dive: money, increments and roundingShow

Store money as integers in the smallest currency unit (cents, pence or yen), together with an ISO 4217 currency code. Floating point cannot represent 0.10 exactly, and repeated additions drift. A bid of $100.10 stored as a float can compare as less than $100.10 computed another way. That is unacceptable in a system whose central question is "is this bid higher?".

One currency per auction. The auction is priced in the seller's currency. Buyers may see converted estimates, but every bid is stored and compared in the auction currency. Conversion rates change by the second, and comparing bids across currencies would make the leader depend on the exchange rate.

Increments as a function. The minimum next bid is current + increment(current), where the increment comes from a tiered table, for example:

Current priceIncrement
$0.01 to $0.99$0.05
$1.00 to $4.99$0.25
$5.00 to $24.99$0.50
$25.00 to $99.99$1.00
$100.00 to $249.99$2.50
$250.00 to $499.99$5.00
$500.00 and up$10.00 or more

These figures are illustrative; real platforms publish their own tables. Version the table, store the version on each auction, and use that version for the whole auction. A rule change mid-auction would otherwise change who is leading.

Edge cases the proxy rule must handle:

  • The new maximum is less than one increment above the leader's maximum. Then min(M_new, M_leader + inc) yields M_new. The new leader pays their full maximum, which is correct.
  • Equal maximums. The earlier bidder keeps the lead, at a price equal to their maximum. The bid log's order proves who was first.
  • A reserve between the two maximums. If M_leader ≥ reserve > the price the proxy rule computed, raise the price to the reserve. A winning bidder who has stated they would pay at least the reserve is then charged exactly the reserve.
  • A bidder raising their own maximum. This does not move the price. It updates leader_max only. Many platforms allow it without a new visible bid.
Deep Dive: proving the bid path correctShow

"We used a lock" is not a proof. Here is how strong teams gain confidence.

State the invariant. For every auction, at every moment:

  1. the visible price never decreases;
  2. the leader is the bidder with the highest maximum, with earliest-wins on ties;
  3. the price equals the proxy rule applied to the bid sequence;
  4. no accepted bid has a server timestamp at or after ends_at.

The correctness condition for concurrent access is linearizability: every bid appears to take effect at a single instant between its request and its response, in an order consistent with real time. The term comes from Herlihy and Wing's "Linearizability: A Correctness Condition for Concurrent Objects" (ACM TOPLAS, 1990) (see Consistency Models).

Testing approaches:

  • Property-based tests for the proxy function: generate random sequences of bids, run them through the function, and check the invariants against a brute-force reference implementation.
  • Concurrency tests: fire thousands of concurrent bids at one auction in a test environment, record every request and response with timestamps, then check that a single sequential order exists that explains every response. That check is what linearizability checkers do. Jepsen, the testing framework by Kyle Kingsbury, popularised this approach for databases.
  • Fault injection: kill the primary, partition the network, pause the relay and skew clocks during those concurrency tests. Then verify that no acknowledged bid disappeared and no invariant broke.
  • Production replay: the nightly recomputation of outcomes from the bid log (Deep Dive 11) is a continuous, real-data version of the same check.

Common bugs these approaches catch:

  • comparing against a cached price on the write path;
  • an UPDATE that checks the amount but not the version, so the proxy state gets overwritten;
  • a close that uses the application server's clock;
  • retries that create duplicate bids because the idempotency key was generated on the server rather than the client.
Deep Dive: the same bid path on DynamoDBShow

PostgreSQL is the default in this design, but a key-value store with conditional writes can host the bid path just as well. Seeing the translation clarifies what the design really needs: an atomic compare-and-set on one auction's state, plus an append to its history.

Table design (single table):

  • PK = AUCTION#<id>, SK = STATE holds price, leader, leader max, bid count, version, status and ends_at.
  • PK = AUCTION#<id>, SK = BID#<seq, zero-padded> holds each bid. A query on the partition key, with the sort-key prefix BID#, returns history in order.
  • A global secondary index on bidder_id serves "my bids".

Placing a bid is one TransactWriteItems call with two actions:

  1. Update the STATE item with ConditionExpression: version = :v AND #s = :live AND ends_at > :now. It sets the new price, leader and version.
  2. Put the BID item with ConditionExpression: attribute_not_exists(SK).

Both succeed or neither does. A failed condition means a concurrent bid won, so re-read and retry: optimistic concurrency, exactly as in the PostgreSQL version.

Differences to respect (see Amazon DynamoDB in Practice):

  • Time comes from the application, because DynamoDB has no server-side now() in conditions. The :now value is the app server's clock, so clock discipline (NTP, small skew) matters more. Some designs add a small grace margin, and treat the close as the final word.
  • Per-partition throughput limits. A single partition supports up to about 1,000 write units per second, and transactional writes consume double units. One hot auction's items all share a partition key, so its ceiling is a few hundred bids per second. That is similar to the row-lock ceiling, and the same early-rejection and single-writer techniques apply.
  • Events come from DynamoDB Streams, which deliver item changes in order per item. That is a built-in change-data-capture feed, replacing the outbox relay.
  • No ad-hoc queries. "Auctions ending in the next minute" needs a separate index (for example, a GSI keyed by end-time bucket) or the external timer store from Deep Dive 6.

Choosing between them: PostgreSQL gives richer constraints, server time, SQL for support and analytics, and familiar tooling. DynamoDB gives managed horizontal scale and predictable latency without shard management. Either is a defensible interview answer, if you explain the conditional write and the hot-partition limit (see Choosing a Database: A Decision Guide).

Deep Dive: the outbid notification pipelineShow

The outbid alert is the most time-sensitive notification in the product. A bidder who learns within seconds that they have been outbid can respond before the auction ends. One who learns ten minutes later cannot. Treat it as a small real-time pipeline, not as a batch email.

Design points:

  • Who to notify is in the event itself. The bid event carries previousLeader (if the leader changed), so the notifier needs no extra lookup to decide.
  • Deduplicate and coalesce. In a bidding war, the same user may be outbid five times in thirty seconds. Send the first alert immediately. Fold the following ones into a single update ("outbid again, now $420") within a short window, so they don't spam the user.
  • Respect preferences: channels, quiet hours and per-auction muting live in a preferences store, cached in the notifier.
  • Channel fallbacks: push first. Email if push isn't enabled. In-app badges always. For high-value items, some platforms also offer SMS.
  • Latency budget: commit, relay, Kafka, notifier and push provider together take about 1 to 3 seconds, usually dominated by the push provider. Measure from bid commit to provider acknowledgement.
  • Ending-soon reminders to watchers use the scheduler (Deep Dive 6) and the same notifier, at lower priority. When 50 popular auctions end at 20:00, 2 million reminders at 19:00 are queued and sent at a controlled rate.
Deep Dive: watch lists, 'my bids' and other per-user viewsShow

Users spend much of their time on personal views: auctions they are watching, auctions they have bid on (winning or losing), and auctions they have won. These are read models built from the event stream, not queries against the bid shards.

  • Watch list: a watches(user_id, auction_id, created_at) table, sharded by user_id. Adding a watch also subscribes the user's open pages to the auction's live channel, and enrols them for ending-soon reminders. A popular auction may have hundreds of thousands of watchers. Store the reverse index (auction_id → watcher count) as a counter, rather than scanning.
  • My bids: a projection keyed by (bidder_id, auction_id), holding the bidder's maximum, their current status (LEADING or OUTBID) and the auction's current price. It is updated from bid events: when a bid changes the leader, both the new and the previous leader's rows are updated. Querying the bid shards by bidder instead would hit every shard, because bids are sharded by auction.
  • Display joins: each personal view lists auction ids. Live prices come from the summary cache with a multi-get. The view never stores a price it cannot keep fresh.

This is the CQRS idea in practice: the write model (auction rows and bids, sharded by auction) is optimised for correctness, and each read model is shaped and sharded for its own query. The cost is eventual consistency: "my bids" may lag the truth by a second. That is why the bid response itself always shows the authoritative result.

Deep Dive: rehearsing the peak before it happensShow

Auction peaks are predictable: end times are published days in advance. A celebrity charity auction, or a rare item featured on the home page, ends at a known second. Use that predictability.

Know in advance which auctions will be hot. Watcher count, page views per minute and bid rate in the last hour are good predictors of last-minute bid storms. A daily job, and a live detector, flag auctions above thresholds (say, 10,000 watchers or 1 bid per second sustained). Flagged auctions get:

  • the pessimistic or single-writer path from the start of their final hour, rather than switching mid-storm;
  • pre-warmed caches on every API node and CDN edge;
  • relay-tree fan-out in the realtime tier, with a dedicated channel shard;
  • extra Close Worker attention: their close is triggered by the timing wheel and checked by a dedicated sweep a second later.

Load-test the pattern, not just the average. A steady 20,000 bids per second across many auctions is easy. The dangerous test is one auction receiving 500 bids per second for 5 seconds, while 100,000 viewers hold open SSE streams and 30 other auctions end in the same minute. Script exactly that with a load generator. Record bid p99 latency, the rate of AUCTION_ENDED rejections, close lag, and end-to-end update latency to watchers. Run it against a production-sized staging shard, and repeat after every significant change to the bid path (see Capacity Planning and Load Testing).

Game days. During a rehearsal, kill the shard primary at T minus 5 seconds, stop the outbox relay, and drop a realtime gateway. Then verify:

  • no acknowledged bid was lost;
  • the extension policy triggered for the affected auction;
  • watchers recovered within the reconnect budget;
  • the final outcome matches a replay of the bid log.

Runbook for the real event. On-call engineers know the auction ids, have dashboards filtered to those auctions' shard and channel, and know the switches available: force hot mode, raise per-user rate limits, pause ending-soon notifications to free capacity, or (as a last resort, under a documented policy) extend the auction. Writing this down beforehand turns a stressful minute into a routine one.

Deep Dive: a bid handler with optimistic concurrency and proxy biddingShow

This is the core of the Bid Service, in TypeScript-style pseudo-code. It uses the OCC variant from Deep Dive 1 and the proxy rule from Deep Dive 2. It is short on purpose: every line is on the critical path.

async function placeBid(auctionId: bigint, bidderId: bigint, maxCents: number, key: string) {
  for (let attempt = 0; attempt < 5; attempt++) {
    const a = await db.one(`SELECT *, now() AS db_now FROM auctions WHERE id = $1`, [auctionId]);
    const prior = await db.oneOrNone(`SELECT * FROM bids WHERE auction_id=$1 AND bidder_id=$2
                                      AND idempotency_key=$3`, [auctionId, bidderId, key]);
    if (prior) return toResponse(prior);                     // safe retry: same answer
    if (a.status !== 'LIVE' || a.db_now >= a.ends_at) return { error: 'AUCTION_ENDED' };
    const minNext = a.leader_id ? a.current_price_cents + increment(a.current_price_cents)
                                : a.start_price_cents;
    if (maxCents < minNext) return { error: 'BID_TOO_LOW', minNext };
 
    let leader = a.leader_id, leaderMax = a.leader_max_cents, price: number, result: string;
    if (!leader || maxCents > leaderMax) {                   // new leader
      price = leader ? Math.min(maxCents, leaderMax + increment(leaderMax)) : a.start_price_cents;
      leader = bidderId; leaderMax = maxCents; result = 'LEADING';
    } else {                                                 // existing proxy defends (ties: earlier wins)
      price = Math.min(leaderMax, maxCents + increment(maxCents)); result = 'OUTBID_BY_PROXY';
    }
    const ok = await db.tx(async t => {
      const n = await t.result(`UPDATE auctions SET current_price_cents=$1, leader_id=$2,
          leader_max_cents=$3, bid_count=bid_count+1, version=version+1
          WHERE id=$4 AND version=$5 AND status='LIVE' AND now() < ends_at`,
          [price, leader, leaderMax, auctionId, a.version]);
      if (n.rowCount === 0) return false;                    // someone else won the race
      await t.none(`INSERT INTO bids VALUES ($1,$2,$3,$4,$5,$6,now(),$7)`,
          [auctionId, a.version + 1n, bidderId, maxCents, price, result, key]);
      await t.none(`INSERT INTO outbox(topic, payload) VALUES ('bids', $1)`,
          [{ auctionId, version: a.version + 1n, price, leader, bidCount: a.bid_count + 1 }]);
      return true;
    });
    if (ok) return { result, price, version: a.version + 1n };
    await sleep(jitter(attempt));                            // brief backoff, then re-read
  }
  return { error: 'CONTENDED_RETRY' };                       // client retries with the same key
}

Points worth noticing:

  • The conditional UPDATE is the serialisation point. It re-checks version, status and now() < ends_at atomically, using the database clock. Everything before it is a speculative computation.
  • The bid, the state change and the outbox event commit together. An accepted bid is therefore never missing from history or from the event stream.
  • Idempotency comes from the lookup by key, plus the unique constraint as a final guard if two retries race. Map a unique violation to "return the stored result".
  • Under heavy contention, OCC retries pile up. That is the signal to switch the auction to the pessimistic SELECT ... FOR UPDATE path, or to the single writer. Some systems make the switch automatically when the retry rate for an auction crosses a threshold.
  • The bidder's own maximum is never returned to others. Only price, leader (masked) and bidCount go into the public event.
Deep Dive: the last 60 seconds of a hot auction, step by stepShow

A rare watch, hard close at 20:00:00, 40,000 watchers, the price at $8,200 at 19:59:00. A walk through what each part of the system sees:

  1. 19:59:00 to 19:59:50. About 2 bids per second. Each takes ~4 ms in the database. Watchers receive each new price within ~300 ms (outbox relay, then Kafka, then fan-out, then the SSE gateways). The summary cache stays fresh through version-guarded updates.
  2. 19:59:50. Sniping tools fire. In the next 10 seconds, ~1,500 bid requests arrive, peaking at ~400 per second in the final 2 seconds.
  3. Early rejection. The API layer checks the cached price, and ~60 percent of requests are already below the minimum next bid. They get BID_TOO_LOW without touching the database. The remaining ~600 go to the shard.
  4. Contention. At ~150 per second reaching one row, OCC would retry heavily. This auction was flagged "hot" at 19:59:30 (bid rate above a threshold), so its bids are routed to the pessimistic path. They queue on the row lock, and each holds it for ~4 ms. The queue drains at ~250 per second, and the p99 latency rises to ~400 ms, which is acceptable for a few seconds.
  5. 19:59:59.998. A bid commits with now() = 19:59:59.998. It is accepted.
  6. 20:00:00.003. A bid waiting for the lock finally acquires it. Its conditional update checks now() < ends_at, which fails. It is rejected with AUCTION_ENDED. This is correct: the bid was processed after the end, and the fairness rule (Deep Dive 5) is that the serialisation point decides. The client shows "Auction ended before your bid was processed".
  7. 20:00:00.010. The timing wheel fires the close. The conditional update moves the auction to ENDED. The outcome is written: the winner's maximum is above the reserve, and the final price is $9,450.
  8. 20:00:00.300. Watchers receive "ENDED, sold for $9,450". The winner receives a push notification and an email. The seller is notified. An order is created.

What if it were soft close? Every bid in the last 2 minutes would extend the end. The 10-second burst would spread into a sequence of rounds, each ending when bidders stop. Peak load is lower, and late bidders always get a chance to respond. The price may be higher, because bidders reveal their true willingness to pay.

The lesson: the dangerous moment is short and predictable. Plan for it explicitly: early rejection, a hot-auction mode, and a rejection message that explains the outcome honestly.

Deep Dive: failure walkthroughsShow

1. The shard primary dies at 19:59:58 on a hot auction.

  • Accepted bids before the crash are safe: synchronous commit means the standby has them.
  • Failover takes ~20 seconds. Bids during that window fail with retryable errors. Clients retry with the same idempotency key.
  • The auction's end time passes during the outage. Policy (decided in advance, and published in the terms): extend auctions whose final N minutes overlapped an outage by, say, 10 minutes, and notify all bidders. The extension is a conditional update on the new primary. The new endsAt goes out over SSE.
  • Without an extension policy, bidders who were locked out at the end would rightly complain that the auction was unfair.

2. The outbox relay is stuck for 3 minutes.

  • Bids commit normally, and responses to bidders are correct (they include the new price).
  • Watchers see a frozen price. After ~10 seconds without updates, clients that track versions can fall back to polling the summary endpoint. But the summary cache is also stale, because it is fed by the same events. So the summary endpoint should read from a replica when its cached version is older than a threshold, or the UI should show "live updates delayed".
  • When the relay recovers, it drains the backlog in order. Version guards make every consumer catch up correctly.

3. A Close Worker crashes after setting ENDED but before publishing AuctionEnded.

  • If the outbox row was written in the same transaction as the status change, the event is not lost: the relay publishes it.
  • If the design used "update, then publish" without an outbox, the safety sweep should also look for ENDED auctions without an outcome row, and finish them. The steps are idempotent, so re-running is safe.

4. A bad deploy computes proxy prices wrongly.

  • The nightly replay (Deep Dive 11) detects mismatches between stored outcomes and recomputed ones.
  • Because history is complete, the fix is to recompute affected auctions and correct the outcomes before payment. That is a strong reason to keep the bid log authoritative and immutable.

5. Redis (summary cache) cluster is lost.

  • Reads fall back to replicas, with request collapsing to protect them. The read path slows, but bids are unaffected.
  • After Redis returns, it fills on demand. Pre-warm the hottest auctions (those with the most watchers) from the database.
Deep Dive: what to monitorShow

Correctness signals (page someone):

  • bids accepted with server_ts >= ends_at (should be zero, always);
  • outcomes that differ from the replayed computation;
  • price regressions seen by clients (a version arriving lower than one already shown);
  • auctions whose ends_at passed more than 60 seconds ago but are still LIVE (close lag).

Latency and throughput:

  • bid p50, p99 and p99.9 latency, split by path (OCC, pessimistic, single writer);
  • OCC retry rate per auction, used to trigger hot mode;
  • row-lock wait time on each shard;
  • end-to-end update latency: from bid commit to the event arriving at a watcher. Measure it with a timestamp in the event, compared on the gateway;
  • outbox relay lag and Kafka consumer lag.

Real-time tier: connections per gateway, reconnect rate (a spike means a gateway problem or a deploy), messages per second and dropped or coalesced messages.

Business: bids per second, auctions ending per minute, the share of auctions with at least one bid, sell-through rate, and the rate of BID_TOO_LOW and AUCTION_ENDED rejections (a surge can mean a stale UI).

Use distributed tracing on the bid path, so that one slow bid can be followed from the API gateway through the Bid Service to the database (see Observability: Logs, Metrics and Traces).

Deep Dive: a 45-minute interview planShow
MinutesFocusWhat to produce
0 to 5ClarifyAuction type (English, ascending), proxy bidding yes or no, hard or soft close, scale (10M live auctions), consistency needs
5 to 10Requirements and estimatesFunctional and non-functional lists. Bids per second (average and peak), watchers, hot-auction rate.
10 to 15Entities and APIItem, Auction, Bid, User. POST bids with maxAmount and an idempotency key. SSE stream.
15 to 25High-level designAuction Service, Bid Service, sharded database, outbox to Kafka, realtime gateways, close scheduler, cache, CDN
25 to 40Deep dives, chosen with the interviewerBid consistency (lock vs OCC vs single writer), real-time fan-out, closing on time, hot auctions
40 to 45Wrap-upFailure modes, the extension policy, fraud, what you would build next

Phrases that signal depth:

  • "The bid path is the source of truth for time. The scheduler only tidies up."
  • "The cache is for display. Decisions are always made under the auction's serialisation point."
  • "Bids are an immutable log, and the auction row is a materialised view of it."
  • "A hot auction is a single-row hotspot, which sharding cannot fix. So I reject early and serialise efficiently."
Deep Dive: auction variants and how the design changesShow

The design above is an English (ascending) auction with proxy bidding. Other formats change specific parts:

  • Sealed-bid auctions (first-price or second-price). Bidders submit once, and bids are hidden until the end. There is no live price, so the real-time tier mostly disappears. Consistency is simpler: bids are independent inserts, with a uniqueness rule per bidder. The close becomes the hard part: compute the winner over all bids at the deadline, often with an audit trail, because nobody saw the bids during the auction. A second-price sealed-bid auction (the winner pays the second-highest bid) is the Vickrey auction. William Vickrey showed in "Counterspeculation, Auctions, and Competitive Sealed Tenders" (Journal of Finance, 1961) that bidding your true value is a dominant strategy in it. Proxy bidding in an English auction produces a similar outcome: the winner pays about the second-highest maximum plus one increment.
  • Dutch (descending) auctions. The price starts high and drops on a schedule. The first bidder to accept wins. This is a contention problem rather than a bidding one: many people click "buy" at the same instant, and exactly one (or N, for multi-unit) must win. It looks like the flash-sale problem: an atomic conditional decrement on remaining quantity.
  • Penny auctions (each bid costs a fee and extends the timer). A soft close by design, with very high bid rates near the end. The single-writer model fits best. Many jurisdictions treat such schemes with suspicion. Mention it only as a load-pattern example.
  • Buy It Now alongside bidding. A fixed-price purchase that ends the auction immediately, often only until the first bid. It is just another transition on the auction row, under the same serialisation point: UPDATE ... SET status='SOLD' WHERE status='LIVE' AND bid_count = 0.
  • Ad auctions (real-time bidding in advertising). Millions of auctions per second, each lasting ~100 ms, run entirely in memory with no persistence of individual bids. Search advertising has long used variants of the generalised second-price (GSP) auction, analysed by Edelman, Ostrovsky and Schwarz in "Internet Advertising and the Generalized Second-Price Auction" (American Economic Review, 2007). Ad auctions are a different system: latency-bound and statistical rather than transactional (see the ad-click-aggregator problem for the counting side).
  • Multi-unit auctions (10 identical items, the top 10 bidders win). The auction row holds the current top-N set rather than a single leader. The serialisation point is the same, but the state is a small sorted list.

Why not WebRTC for live updates? WebRTC creates peer-to-peer media and data channels between browsers. It is designed for low-latency audio, video and data between a few peers, such as calls or multiplayer games. Here the data flows one way, from the server to many viewers, and must come from the authoritative backend. Peers have nothing to send each other. WebRTC also needs signalling servers and NAT traversal (STUN and TURN). SSE or WebSockets are simpler and better suited (see Polling, Long Polling, SSE, WebSockets and Webhooks).

Deep Dive: real-world notesShow
  • eBay popularised online English auctions with proxy bidding (a bidder enters a maximum and the system bids for them in increments) and a hard close at the published end time. Sniping tools and services have long existed because of that hard close. Treat specific internal architecture claims about eBay with caution: public details vary by era.
  • Soft close ("extended bidding", "popcorn bidding") is common on many auction-house platforms and charity auction sites. The extension window and rules vary by platform.
  • The economics literature explains the behaviour you will see in the data. Roth and Ockenfels, in "Last-Minute Bidding and the Rules for Ending Second-Price Auctions" (American Economic Review, 2002), compared eBay's hard close with Amazon Auctions' soft close (now discontinued). They found far more last-minute bidding on eBay. That is evidence that the close rule shapes the load pattern the system must handle, not just the outcome.
  • Bid increments are tiered by price on most platforms (for example $0.50 at low prices and larger steps at higher prices). Store the increment table as configuration, version it, and record which version applied to each auction, so that disputes can be resolved against the rules in force at the time.

Key Takeaways#

  • Every auction needs one serialisation point. A row lock, a version-checked update or a single writer, so that concurrent bids are ordered and the price never regresses. The bids table alone cannot be locked, because of phantoms.
  • Proxy bidding sets the price to about the second-highest maximum plus one increment. The reserve is compared against the leader's maximum. Ties go to the earlier bid.
  • Durability before acknowledgement: synchronous replication, plus an outbox that commits the event together with the bid, so live views, caches and search all eventually reflect every accepted bid.
  • Real-time updates use SSE (or WebSockets) through a gateway tier, fed by pub/sub. Coalesce updates for hot auctions, put versions on every event, and plan for reconnect storms.
  • Time is decided in the bid path with the database clock. The scheduler (timing wheels, sorted sets, safety sweeps) only closes auctions promptly and kicks off post-auction workflows, idempotently.
  • Hard vs soft close is a product choice with system consequences: last-second spikes versus extended end times that must propagate everywhere.
  • Scale comes from independence. Shard by auction id. The real limit is the hot auction, which you handle with early rejection, short critical sections and a single-writer mode.
  • Bids are an immutable log. Use it for audit, replay verification, history views and fraud detection (shill bidding, retractions).