AlgoViz

Design an online auction

hard 90 min

Design the classes of an auction with maximum bids, a secret reserve, steps and a soft close.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:05

Theory

Read or listen first. About 2 min.

What it is

An online auction sells one lot to whoever offers most. In the common form people write the most they would pay, and the system bids for them: the visible price is just above the second-highest maximum.

Underneath it is one changing standing with a strict order of changes: best bid, price and end. Every new bid is judged against the newest standing, so somebody has to own it.

Around this small core are things that are not in order and must not slow it down: watchers, messages, payment, search. Keeping them outside is the larger part of the design.

Why it exists

It is a popular exercise because the naive version fails in public. Two bids at once, a bid in the last second, a timer thread: each gives a wrong winner.

The price rule looks like one line and has seven cases. It shows whether a candidate works with examples or with hope.

The same shape is everywhere: the last seat, a leaderboard, a counter with a limit. One owner, an order, a rule, and news for the others.

A short history

  1. 500 BC

    About this time auctions are first recorded. Herodotus writes about some in Babylon.

  2. 1641

    Auctions by candle are known in England: the last bid before the flame dies wins. Pepys describes two, in 1660 and 1662, and a bidder who watched for the last flare of the wick.

  3. 1744

    Samuel Baker, a bookseller, establishes on 11 March in London what becomes the auction house Sotheby's.

  4. 1961

    William Vickrey publishes the analysis of sealed second-price auctions: writing down the true value is the best plan. Stamp collectors had used the form since 1893.

  5. 1995

    Pierre Omidyar starts AuctionWeb, later eBay, on 3 September as a hobby site.

Words to know

Lot
What is sold in one auction.
Maximum
The most a bidder would pay. Secret.
Reserve
The least the seller accepts. Secret here.
Step or increment
The smallest raise at a price.
Standing
Leader, price and end at one moment.
Soft close
A late bid moves the end.
Sniping
Bidding in the last moment, so that nobody can answer.
Shill
Somebody who bids for the seller, to push the price.
Fold
Computing a state from a list of facts, one after the other.
Term
The number of an owner's reign. Older ones are refused.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Bid. Known key, in time, high enough: one block under the lock of the lot

Understand it

Start here

Bella is for sale

A village sells a cow by candle
Bella the cowprice100leadsnobodyAUCTIONNot below whatI wrote down.

Notes, board, candle, hammer: maximum, view, end, close. Whoever holds the desk decides the order.

What an interviewer looks for here

  • One owner

    Price, leader and end change together. A class with a lock owns them, and nobody else can write.

  • The rule of the price

    Maximum bids, steps, ties, reserve. Small, exact, full of edges.

  • The last second

    Bids, the end and the closer meet. The design must say who wins, not the scheduler.

  • Secrets

    Reserve and maxima must not leave the class. Types can make that easy.

  • Telling others

    Screens, losers, the seller. After the lock, with versions.

  • Fairness in time

    Who came first, what a retry means, what happens to a late bid.

Questions

Six questions, and what each answer changes

AskIf the answer isThen the design has
Is a bid a price or a maximum?A maximumHidden maxima, and a price computed from two of them
Is there a least price, and is it secret?Yes, secretreserve, unsold as a result
What is the smallest raise?Depends on the priceA table of steps
What happens to bids at the last second?They move the endA rule for the end, a closer that asks again
Who wins a tie?The earlier oneNumbers given under the lock
Can a bid be taken back?NoAn append-only list. Otherwise see the FAANG page

Price

From two maxima to one price

Start 100, reserve 150, step 10

Standing beforeBidLeaderPriceWhy
nobodyAsha 140Asha100First bid: start price
Asha 140 at 100Lee 200Lee150140 + 10, and the reserve 150 is met
Lee 200 at 150Sam 155Lee150Refused: at least 160
Lee 200 at 150Sam 180Lee190180 + 10
Lee 200 at 190Sam 200Lee200Tie: earlier wins, capped at the maximum
Lee 200 at 190Lee 300Lee190Own raise: no change
Lee 200 at 190Asha 205Asha205200 + 10 is above 205: capped

The visible price

p=max⁡(min⁡(m1,;m2+s(m2)),;r)if m1≥rp = \max\bigl(\min(m_1,; m_2 + s(m_2)),; r\bigr) \quad\text{if } m_1 \ge r
m1 is the highest maximum, m2 the highest of all others, s the step, r the reserve. With one bidder only, the start price takes the place of the minimum. If the leader raises the own maximum after the cap was reached, the price stays.

A bid arrives

Everything from the key to the answer is one block under the lock of this lot.

Design, first try

The design most people draw first

The design to avoid: everybody may change the price

AuctionSystem- instance: AuctionSystem- users, items, auctions+ placeBid(user, item, amount)+ endAuction(), pay(), email()

1/4A global system

Every bid for every item goes through one class and, as soon as somebody adds synchronized, through one lock.

owns (dies together)extends (is a)uses

Two writers, no owner. The last ten seconds of every auction are a race.
Python
def place_bid(self, user, item, amount):    if time.time() < item.end_time:            # clock before the lock        if amount > item.highest_bid:          # two threads pass here            item.highest_bid = amount          # the lower one may write last            item.highest_bidder = user         # and these two lines can mix            self.email(item.old_bidder)        # slow, and fails the bid
Five mistakes in six lines: the time is checked too early, check and act are apart, two fields can belong to different bids, a mail server decides about a bid, and no bid is recorded.

Design, better

The design to reach

One Auction object for each lot owns the standing, the end and the phase. Rules answers two questions. Everything that leaves is a frozen View. The House finds auctions, closes due ones and tells listeners.

The design to reach: one object owns one lot, rules come from outside

Auction- best: Bid?, price?- endsAt, phase, version- bids, answers, lock+ place(...): Answer+ close(now): View?+ view(): View

1/5One owner for each lot

Only Auction changes price, leader and end, and it has one lock for all of them. Two lots never wait for each other.

owns (dies together)has (lives on)uses

Secrets stay inside Auction. Everything that leaves is a frozen View.

Roles

What each class owns

ClassKnowsDoes not know
AuctionStanding, end, history of one lotOther lots, screens, mail
RulesSteps and the soft closeBids
Lot, BidWhat was decided onceWhat became of it
ViewWhat people may see nowReserve and maxima
HouseWhich auctions exist, when to lookHow a price is made

States

The life of an auction

One lot

There is no state between the end and the close. A bid after the end is refused by the time, whether or not the closer has been there.

The hard part

The last second

Bid and closer meet

Both orders are fine. If the closer were first, with the clock at 600 it would close, and Sam, reading the clock under the lock, would be late.

Why the clock is read under the lock

A time that was read before waiting is a memory. Read it when you decide.

Two bids arrive at the same moment. How do you keep the standing right?

BreaksCompare and set two fields
How
if amount > highest: highest = amount; bidder = user.
Limit
Check and act are apart, and the two fields can come from two bids.
Choose when
Never.
WorksOne lock for each lot
How
Everything about one lot in one block.
Limit
Bids for one lot queue. A bid takes microseconds.
Choose when
The right answer in one process.
StrongOne writer for each lot
How
Bids go into a queue for the lot, one worker takes them in order. No lock, and a clear order that can be logged and replayed.
Limit
Answers come back over a future or a message.
Choose when
Very popular lots, many processes, an audit. See the FAANG pages.

Edges

Time and ties

MomentRuleReason
Bid at the end exactlyToo lateThe end is not included, like all periods here
Two equal maximaEarlier number winsThe one who took the risk first
Leader repeats a lower maximumRefusedIt would change nothing, or take back a promise
Same key againSame answerThe client did not hear us
Same key again after the endSame answerThe bid counted then
Closer twiceSame resultClosing is a state, not an act

Do

  • Give each lot one owner with one lock
  • Read the clock under the lock
  • Number bids under the lock
  • Keep reserve and maxima out of views
  • Answer a repeated key with the first answer
  • Let the closer ask and not decide
  • Tell listeners after the lock, with a version

Do not

  • Use one lock for all lots
  • Set price and leader from outside
  • Sort by timestamps
  • Treat an outbid answer as an error
  • Run a sleeping thread for each lot
  • Send mail inside place
  • Use floating point for money

Which part changes?

Summary

The whole topic in one minute.

Each lot has one owner with one lock. A bid is checked, numbered, settled and answered in one block, with the clock read inside. The price is one step above the best of the others, capped by the leader's maximum and lifted to the reserve.

Late bids move the end in the same block, the closer only asks. Views are frozen, secret-free and versioned, and listeners hear them after the lock. The list of bids is the truth from which any standing can be computed again.

  • A bid is a maximum. The price is one step above the best of the others, capped by the leader's maximum.
  • The reserve lifts the price as soon as the leader would pay it, and decides sold or unsold.
  • One owner for each lot: standing, end and phase change in one block.
  • The clock is read under the lock. The end is not included.
  • Order comes from numbers given under the lock. Equal maxima: the earlier one.
  • Soft close: a late bid moves the end. The closer asks again.
  • Views are frozen, have no secrets and carry a version.

Sources