"Design an online auction" sounds like one comparison: if the new bid is higher than the highest bid, keep it. A weak answer stores highestBid, adds an Auction with a status and an end time, and stops. That answer cannot say what the winner pays, what happens when two people bid in the same millisecond, or what happens to a bid that arrives as the clock hits the end time.
The interviewer is checking three things. First, the price: on a real auction site a bidder gives a maximum, and the site bids for them, so the price is worked out and not typed in. Second, the end: a bid in the last second can win before anyone can answer it, and the design has to choose what to do about that. Third, the race at the close: bids race each other, and they race the timer that closes the auction. The third needs one clear answer about which came first.
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| One item or many per auction? | One item, one auction | One Listing per Auction |
| What kind of auction? | Open, with rising prices. The highest maximum wins | A leader and a price, and no sealed bids |
| Do bidders type exact amounts? | No. They give a maximum, and the auction bids for them up to it | Bid holds a maximum, and the price is worked out |
| What does the winner pay? | The runner-up's maximum plus one increment, never more than their own maximum | BidBook.priceCents() |
| How big is each step? | It depends on the price, in tiers: 50 cents under $20, $5 from $100 to $499.99 | An IncrementRule interface |
| Is there a reserve price? | Optional and hidden. Below it, the item is not sold | reserveCents and RESERVE_NOT_MET |
| What about a bid in the last seconds? | A soft close. A bid in the last 2 minutes moves the end to 2 minutes after it | A ClosingRule interface, with SoftClose |
| Who takes the payment? | Not this design. The result goes to whoever handles orders | No payment interface, and an AuctionResult for listeners |
| Can the seller bid? | No | A SELLER_CANNOT_BID answer |
| How many bidders at once? | Many, on many threads, and most of them in the last minute | One lock per auction |
The last question matters most. Interest in an auction peaks at its end, so the busiest moment and the moment the auction closes are the same moment. The design must say which came first, a bid or the close, and give one answer to every caller.
Requirements
Functional:
- A seller lists an item with a start price, an optional hidden reserve and an end time.
- A bidder places a maximum, and the auction bids for them up to it. The first bid must be at least the start price. Every later bid from anyone but the leader must be at least the current price plus one increment. The leader may raise their own maximum by any amount.
- The leader pays the runner-up's maximum plus one increment, but never more than their own maximum. Once the reserve is met, the price is at least the reserve. Of two equal maximums, the earlier one leads.
- A bid accepted less than 2 minutes before the end, a leader's raise included, moves the end to 2 minutes after that bid.
- A bid at or after the end time is refused, even if the auction has not been closed yet.
- Each auction closes exactly once, as SOLD, RESERVE_NOT_MET or NO_BIDS.
- A bidder who loses the lead is told, and listeners hear every result.
Out of scope: payment and a winner who does not pay, buy-it-now, taking a bid back, a limit on how many times the end can move, and auctions of many identical items. We come back to these at the end.
Everything lives in memory, as is normal for a low-level design interview. Saving bids so they survive a restart is a storage question for a separate discussion.
What the code itself must handle:
- Many bidders at once.
placeBidandcloseDuerun on many threads, on the same auction. - Rules that change. The increment tiers and the closing rule are business choices. Changing them should not mean editing the auction.
- Testable time. The end time decides everything, so a test must control the clock.
Finding the classes
A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.
Two kept nouns are rules, not data. The increment and the closing time are business choices that will change, so each gets an interface. The price is a third kind of noun: it is a result of the bids, so BidBook works it out each time it is asked.
Should Bidder and Seller be classes?
Bidder and Seller classes, each with a list of their auctions
Many answers draw them, because the question names them. But nothing in the auction needs a bidder's name, address or history. Two classes with a list each give two more places that must agree with the auctions, and both lists need their own lock.
Ids on the records. Accounts live in another serviceOur pick
The auction needs to know only who a bid belongs to, and who the seller is so they cannot bid. A String id on Bid and on Listing does both. "My bids" is a query for the accounts service, or for a store of bids if the interviewer asks for one.
Data or behaviour?
Most of the design is data that never changes once made: a listing, a bid, the answer to a bid and the result of an auction. In Java these are records: classes whose fields are fixed when they are created, with equals, hashCode and toString written for us. A Listing checks its own values when it is made:
public record Listing(String sellerId, String title, long startPriceCents, long reserveCents, Instant endTime) { public static final long NO_RESERVE = 0; public Listing { Objects.requireNonNull(sellerId, "sellerId"); Objects.requireNonNull(title, "title"); Objects.requireNonNull(endTime, "endTime"); if (sellerId.isBlank() || title.isBlank()) { throw new IllegalArgumentException("A listing needs a seller and a title"); } if (startPriceCents <= 0 || startPriceCents > Bid.MAX_CENTS) { throw new IllegalArgumentException("The start price must be from 1 cent to $1,000,000,000: " + startPriceCents); } if (reserveCents != NO_RESERVE && (reserveCents < startPriceCents || reserveCents > Bid.MAX_CENTS)) { throw new IllegalArgumentException("A reserve must be at least the start price: " + reserveCents); } }}A reserve of zero means there is none. Otherwise it may not be below the start price. Money is a long of cents, because double cannot hold 0.1 exactly.
The class diagram
The classes fall into three groups:
- Data:
Listing,Bid,BidResult,BidStatus,AuctionResult,Outcome,AuctionViewand the package-privateBidOutcome. These are records and enums. - The core:
AuctionHouse,AuctionandBidBook. The house finds an auction by id and talks to listeners. An auction holds the lock and the end time. ABidBookdoes the proxy bidding sums and nothing else. - Rules and outside systems:
IncrementRule,ClosingRuleandAuctionListener. All three are interfaces.
Building it
What a bidder is told
A bid can fail in ways a person must see: too low, too late, or from the seller. These are answers, not errors, so placeBid returns a BidResult with a BidStatus:
public enum BidStatus { LEADING, OUTBID, TOO_LOW, AUCTION_ENDED, SELLER_CANNOT_BID; public boolean accepted() { return this == LEADING || this == OUTBID; }}LEADING and OUTBID both mean the bid was accepted. OUTBID means it raised the price, but someone else's maximum is higher. The result also carries the price, the minimum next bid and the end time, so the page can say "too low, the minimum is $160.00".
Are refusals exceptions or results?
An exception for each refusal: BidTooLowException, AuctionEndedException
A refused bid is then hard to miss. But a refusal happens all the time in the last minute of an auction, and every caller would need a try around normal business. An exception also loses the minimum next bid unless we add fields to it.
A BidStatus in the result. Exceptions only for programmer mistakesOur pick
Every answer a person may see is a value the caller switches on. Exceptions are kept for mistakes in the calling code: a null bidder, a bid of zero cents or over $1 billion, an auction id that does not exist. Every IncrementRule promises a step of at most $1 billion, and TieredIncrement checks it, so adding a step to a price can never overflow a long.
The price: proxy bidding
On a real auction site, a bidder does not type $155. They type the most they will pay, say $180, and the site bids for them, one step at a time, only as far as it has to. This is called proxy bidding, and the price it produces has a simple rule: the leader pays the runner-up's maximum plus one increment, but never more than their own maximum.
That rule needs only two numbers, the top two maximums. So BidBook stores two bids, not a price:
private Bid leading; // the highest maximum, or null before the first bid private Bid runnerUp; // the highest maximum of anyone else, or null boolean place(Bid bid) { if (leading != null && leading.bidderId().equals(bid.bidderId())) { if (bid.maxCents() <= leading.maxCents()) { return false; } leading = bid; return true; } if (bid.maxCents() < minimumNextBidCents()) { return false; } if (leading == null || bid.maxCents() > leading.maxCents()) { runnerUp = leading; leading = bid; } else { // An equal maximum does not take the lead: the earlier bid keeps it. runnerUp = bid; } return true; } /** What the leader would pay if the auction ended now. */ long priceCents() { if (leading == null) { return startPriceCents; } long price = startPriceCents; if (runnerUp != null) { long oneStepAbove = Math.addExact(runnerUp.maxCents(), increments.incrementAt(runnerUp.maxCents())); price = Math.min(leading.maxCents(), oneStepAbove); } return reserveMet() ? Math.max(price, reserveCents) : price; }place has three cases. A leader raising their own maximum changes only leading. The price then moves only if the old maximum was the cap, or the new one meets the reserve. A higher maximum takes the lead, and the old leader becomes the runner-up. An equal or lower maximum becomes the new runner-up, and the leader stays. priceCents() then works the price out from scratch: the runner-up's maximum plus one step, capped at the leader's maximum, and lifted to the reserve once the leader's maximum reaches it.
Equal maximums go to the earlier bid, which is the else on line 38. If asha has $180 and ben then bids $180, ben's bid becomes the runner-up. The price is capped at asha's maximum, so it is exactly $180, and asha still leads.
What does the winner pay?
Their own maximum
This is simple to explain. But then a maximum is a real bid, so nobody will tell the site their true limit. Bidders come back and raise by small steps instead, which is exactly the work proxy bidding was meant to do for them.
The runner-up's maximum plus one increment, capped at their own maximumOur pick
The winner pays only what it took to beat the next person, so it is safe to give your true maximum. The cap matters when two maximums are close: with $180 against $178, one $5 step would give $183, which is more than the leader agreed to, so the price is $180.
Store the current price, or work it out?
A priceCents field, updated on each bid
It looks cheaper. But every case in place must then update the price correctly, and one case is easy to get wrong. Asha has $180 and ben bids $178, so the price is capped at $180. If asha then raises to $200, the stored price stays at $180, while the rule says ben's $178 plus $5, which is $183.
Keep the top two bids, and work the price out on every readOur pick
There is one formula, on lines 46 to 56, and every case goes through it. The cost is a few comparisons each time the price is read, which is nothing next to a network call. The minimum next bid is the price plus one step at that price.
A bid history is the obvious thing to store, and we leave it out on purpose. Bids below the runner-up can never change the price again. If the interviewer asks for a "bid history" page, a list of accepted bids can sit beside BidBook without changing its sums.
The minimum increment
Auction sites raise the step as the price grows: 50 cents is a real step on a $12 lamp, and nothing on a $900 watch. The tiers are a business choice.
public static TieredIncrement standard() { return new TieredIncrement(Map.of( 0L, 50L, // under $20: 50 cents 20_00L, 1_00L, // $20 to $99.99: $1 100_00L, 5_00L, // $100 to $499.99: $5 500_00L, 10_00L, // $500 to $999.99: $10 1_000_00L, 25_00L)); // $1,000 and up: $25 } @Override public long incrementAt(long priceCents) { if (priceCents < 0) { throw new IllegalArgumentException("A price cannot be negative: " + priceCents); } return incrementFromPrice.floorEntry(priceCents).getValue(); }floorEntry finds the tier that starts at or below the price. The step is worked out at the runner-up's maximum: at $150 it is $5, so ben's $150 gives a price of $155. The constructor refuses a set of tiers without one at $0, a tier with a negative start, and a step of zero or over $1 billion.
Placing a bid
Auction.placeBid puts the pieces together. It is synchronized, so one bid at a time runs it for this auction:
synchronized BidOutcome placeBid(Bid bid) { // Read under the lock, so the order of bid times is the order the bids are handled in. Instant now = clock.instant(); if (result != null || !now.isBefore(endTime)) { return refused(BidStatus.AUCTION_ENDED); } if (bid.bidderId().equals(listing.sellerId())) { return refused(BidStatus.SELLER_CANNOT_BID); } Optional<String> previousLeader = book.leaderId(); if (!book.place(bid)) { return refused(BidStatus.TOO_LOW); } endTime = closingRule.endAfterBid(endTime, now); String leader = book.leaderId().orElseThrow(); BidStatus status = leader.equals(bid.bidderId()) ? BidStatus.LEADING : BidStatus.OUTBID; String outbid = previousLeader.filter(previous -> !previous.equals(leader)).orElse(null); return new BidOutcome(resultWith(status), outbid); }The order of the checks matters. Time comes first: a late bid is refused before anything else is read (line 43). Then the seller check, then book.place, which may refuse a bid as too low. Only an accepted bid reaches line 53 and may move the end time. The method also notes who led before, so the house can tell that person they were outbid.
A bid in the last second
With a fixed end time, the best move is to bid in the last few seconds, so that nobody can answer. This is called sniping. Ben's $300 at 17:59:30 would win at $250, and asha would have 30 seconds to see the notice and react.
A soft close removes that advantage. Each accepted bid in the last 2 minutes moves the end time to 2 minutes after that bid, so every bid leaves the others time to answer.
@Override public Instant endAfterBid(Instant currentEnd, Instant bidTime) { // Every bid leaves at least one full window for the others to answer it. Instant extended = bidTime.plus(window); return extended.isAfter(currentEnd) ? extended : currentEnd; }endAfterBid returns the later of two times: the current end, or the bid time plus the window. An early bid never shortens the auction, and a late one always leaves a full window.
A fixed close or a soft close?
A fixed close
Everyone knows exactly when it ends, and the code has no extension at all. But the auction rewards whoever bids last and fastest, and a seller loses the higher price the other bidder would have paid if they had been given time.
A soft close, with the rule behind an interfaceOur pick
The highest willing bidder wins, not the fastest. ClosingRule has two implementations, FixedClose and SoftClose, and the house is given one. The cost is that the end is no longer known in advance, so the timer must read it again each time, which the next section covers.
Closing an auction
Someone has to turn an auction past its end into a result. The end can move, so a timer set for 18:00 when the auction was listed would be wrong after the first snipe.
/** A timer calls this every second. It closes every open auction whose end time has passed. */ public List<AuctionResult> closeDue() { List<AuctionResult> closed = new ArrayList<>(); for (String id : openIds) { auctions.get(id).closeIfDue().ifPresent(result -> { openIds.remove(id); closed.add(result); tellClosed(result); }); } return closed; } synchronized Optional<AuctionResult> closeIfDue() { if (result != null || clock.instant().isBefore(endTime)) { return Optional.empty(); } if (book.leaderId().isEmpty()) { result = AuctionResult.unsold(id, Outcome.NO_BIDS, 0); } else if (!book.reserveMet()) { result = AuctionResult.unsold(id, Outcome.RESERVE_NOT_MET, book.priceCents()); } else { result = AuctionResult.sold(id, book.leaderId().orElseThrow(), book.priceCents()); } return Optional.of(result); }A timer calls closeDue() every second. The house keeps openIds, the auctions not yet closed, and drops an id once its auction closes. For each open auction, closeIfDue takes that auction's lock and checks the end time that is current now (line 62). After ben's snipe, the 18:00 sweep finds the end at 18:01:30 and does nothing. Once result is set, the auction never closes again, so each result is announced exactly once.
Bids do not wait for the sweep. Line 43 of placeBid refuses a bid at or after the end time even if the sweep has not run yet, so the timer being a second late changes only when the result is announced.
Who closes an auction?
A timer task per auction, set for its end time
This is exact to the millisecond. But every extension must cancel the task and set a new one, and a task that fires just as a bid extends the end must still check again. The check is needed anyway, so the task saves nothing.
Close it on the next read or bid
This needs no timer. But an auction nobody looks at after its end is never closed, and the winner is never told.
A sweep every second that re-checks each end time under the lockOur pick
The sweep is simple, and it reads the end time that is current when it runs, so extensions need no extra code. The cost is a loop over every open auction each second. With millions of auctions, a queue sorted by end time would replace the loop, and the check under the lock would stay the same.
Bids against the clock
This is the part the interviewer pushes on hardest. At 18:00:00, ben's bid and the timer reach the same auction together. Under a soft close, a bid just before the end moves it, and the close must then find nothing to do. Just after the end, the bid must be refused. The question is: whose clock reading decides?
placeBid reads the clock on line 42, inside the synchronized method. A bid that waited for the lock is judged by the moment it is handled, not the moment it arrived. BookMyShow makes the same choice for its seat holds, for the same reason.
Which moment decides whether a bid is on time?
The moment the request arrived, stamped before the lock
This feels fair to the bidder. But a stamped bid can wait for the lock while the close runs, and then it is on time for an auction that is already sold. One answer refuses an on-time bid. The other reopens a closed auction after the winner was told.
The moment the auction handles it, read under the lockOur pick
The bids and the close happen in one order, the order they take the lock, and their times follow that order. "Before the end" then means "before the close", and there is no case to argue about. The cost is that a bid that waited a few milliseconds for the lock is judged a few milliseconds late.
The project includes a check, demo/RaceCheck.java. First, 8 bidders bid $30, $60 and so on up to $240 on one auction at the same moment, in 2,000 rounds. Whatever the order, the $240 bidder must lead at $210 plus $5. Then, in 5,000 rounds, ben's $500 bid starts 1 ms before the end, together with a timer that moves the clock to the end and calls closeDue():
8 bidders at once, 2,000 rounds rounds where $240 did not lead at $215.00: 0 One bid and the close at the end time, 5,000 rounds bid accepted, auction extended: 2498 bid refused as too late: 2502 bidder told they lead, but someone else won: 0
The bid is accepted in about half the rounds and refused in the rest, and these two counts vary from run to run. What never varies is the last line: a bidder told LEADING always won. We also ran the check with synchronized removed from placeBid and closeIfDue. Every run we tried had wrong rounds in the first part: two bids changed the leader and the runner-up at the same time, and the round ended with the wrong leader or the wrong price. The second part told a bidder LEADING and then sold to someone else in some runs and not in others. The gap between the close's time check and its reading of the leader is only a few instructions wide, so the bug is rare, and it is still a bug.
Where does the lock go?
One lock on the whole AuctionHouse
It is correct and easy to explain. But a bid on a lamp would wait for a bid on a watch, and every auction ending at 18:00 would queue behind one lock at the busiest moment of the day.
No lock. An AtomicReference to an immutable state, swapped with compareAndSet
It never blocks. But a state here is the leader, the runner-up, the end time and the result together. A loser of the swap must redo the whole bid, and it is harder to show that the time and the close stay in order.
One lock per auction, on the Auction itselfOur pick
Everything that must agree, the two bids, the end time and the result, lives in one Auction, and its synchronized methods guard all of it. Auctions never wait for each other. The house's map of auctions is a ConcurrentHashMap, and ids come from an AtomicLong, so listing needs no lock. Under the lock the code only compares numbers, reads the clock and asks the two rules. No listener runs there.
Telling people they were outbid
When ben takes the lead, asha should hear about it. The auction should not know whether that is an email, a push message or both.
public BidResult placeBid(String auctionId, String bidderId, long maxCents) { Bid bid = new Bid(bidderId, maxCents); Auction auction = find(auctionId); BidOutcome outcome = auction.placeBid(bid); // The auction's lock is released by now, so a slow listener holds up no other bidder. tellOutbid(auctionId, outcome); return outcome.result(); }Auction.placeBid only returns the name of the person who lost the lead, inside a BidOutcome. The house calls the listeners on line 56, after the auction's lock is released. Every call goes through a try that logs a failure and moves on, so a listener that throws an exception cannot fail an accepted bid. It cannot stop the other listeners, or the other auctions in a sweep. Turning a notice into a delivered email, with retries and quiet hours, is the job of a notification service. Across many machines it becomes a pub-sub topic.
Tell listeners inside the lock, or after it?
Inside the lock, as part of placeBid
The notices go out in exactly the order of the bids. But an email call that takes two seconds would hold the auction's lock for two seconds, in the last minute, while every other bidder waits.
After the lock is releasedOur pick
A slow or broken listener holds up only its own caller. A listener may even bid back, as an auto-rebid would, by calling placeBid from inside onOutbid. Its bid runs as a nested call, after the first bid has released the lock. The cost is order. Two notices from two quick bids can reach a listener in the opposite order, so each notice carries the price it was sent with, and a page should ask view() for the current state.
The final design
AuctionHouse is the entry point. It owns the auctions and the ids of the open ones, finds one by id, and keeps the list of listeners. Each Auction owns its BidBook, its end time and its lock. The closing rule, the increment rule and the listeners are interfaces, and the time comes from a Clock passed in. Bids and the close meet only inside the auction's lock, and no listener runs while it is held.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should Bidder and Seller be classes? | Ids on the records. Accounts live in another service | The auction needs only who a bid belongs to. |
| 2 | Are refusals exceptions or results? | A BidStatus in the result. Exceptions only for programmer mistakes | A refusal is normal business, not an error. |
| 3 | What does the winner pay? | The runner-up's maximum plus one increment, capped at their own maximum | It is safe to give your true maximum. |
| 4 | Store the current price, or work it out? | Keep the top two bids, and work the price out on every read | One formula covers every case. |
| 5 | A fixed close or a soft close? | A soft close, with the rule behind an interface | The highest bidder wins, not the fastest. |
| 6 | Who closes an auction? | A sweep every second that re-checks each end time under the lock | Extensions need no extra code. |
| 7 | Which moment decides whether a bid is on time? | The moment the auction handles it, read under the lock | Bids and the close happen in one order. |
| 8 | Where does the lock go? | One lock per auction, on the Auction itself | Auctions never wait for each other. |
| 9 | Tell listeners inside the lock, or after it? | After the lock is released | A slow listener never holds up a bid. |
Here is ben's $300 bid at 17:59:30 from the demo, step by step:
AuctionHouse.placeBidbuilds aBid, which refuses a bad amount, and finds auction A-1 in its map.Auction.placeBidtakes the auction's lock and reads the clock: 17:59:30, before the 18:00 end.BidBook.placemakes ben the leader and asha the runner-up.priceCents()gives $185, lifted to the $250 reserve.ClosingRule.endAfterBidmoves the end to 18:01:30, and the lock is released.- Outside the lock,
tellOutbidcallsAuctionListener.onOutbidfor asha, andplaceBidreturnsLEADINGat $250 to ben.
Closing is the other path. The timer calls AuctionHouse.closeDue(), which asks each open Auction for closeIfDue(). That method takes the same lock, reads the clock and the end time as they are now, and sets result only once. The house then calls onClosed on each listener, outside the lock. A bid at or after the end time never reaches BidBook, so the leader cannot change after the end, whether the sweep has run yet or not.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package auction; import java.time.Clock;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.atomic.AtomicLong; import bid.Bid;import bid.BidResult;import exception.AuctionNotFoundException;import listing.Listing;import notify.AuctionListener;import result.AuctionResult;import rules.ClosingRule;import rules.IncrementRule; public final class AuctionHouse { private static final System.Logger LOG = System.getLogger(AuctionHouse.class.getName()); private final IncrementRule increments; private final ClosingRule closingRule; private final Clock clock; private final Map<String, Auction> auctions = new ConcurrentHashMap<>(); private final Set<String> openIds = ConcurrentHashMap.newKeySet(); private final AtomicLong auctionCounter = new AtomicLong(); private final List<AuctionListener> listeners = new CopyOnWriteArrayList<>(); public AuctionHouse(IncrementRule increments, ClosingRule closingRule, Clock clock) { this.increments = Objects.requireNonNull(increments, "increments"); this.closingRule = Objects.requireNonNull(closingRule, "closingRule"); this.clock = Objects.requireNonNull(clock, "clock"); } public String list(Listing listing) { Objects.requireNonNull(listing, "listing"); if (!listing.endTime().isAfter(clock.instant())) { throw new IllegalArgumentException("The end time must be in the future: " + listing.endTime()); } String id = "A-" + auctionCounter.incrementAndGet(); auctions.put(id, new Auction(id, listing, increments, closingRule, clock)); openIds.add(id); return id; } public BidResult placeBid(String auctionId, String bidderId, long maxCents) { Bid bid = new Bid(bidderId, maxCents); Auction auction = find(auctionId); BidOutcome outcome = auction.placeBid(bid); // The auction's lock is released by now, so a slow listener holds up no other bidder. tellOutbid(auctionId, outcome); return outcome.result(); } /** A timer calls this every second. It closes every open auction whose end time has passed. */ public List<AuctionResult> closeDue() { List<AuctionResult> closed = new ArrayList<>(); for (String id : openIds) { auctions.get(id).closeIfDue().ifPresent(result -> { openIds.remove(id); closed.add(result); tellClosed(result); }); } return closed; } public AuctionView view(String auctionId) { return find(auctionId).view(); } public void addListener(AuctionListener listener) { listeners.add(Objects.requireNonNull(listener, "listener")); } private Auction find(String auctionId) { Auction auction = auctions.get(Objects.requireNonNull(auctionId, "auctionId")); if (auction == null) { throw new AuctionNotFoundException(auctionId); } return auction; } private void tellOutbid(String auctionId, BidOutcome outcome) { if (outcome.outbidBidderId() == null) { return; } for (AuctionListener listener : listeners) { try { listener.onOutbid(auctionId, outcome.outbidBidderId(), outcome.result().priceCents()); } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "Outbid notice failed", e); } } } // A broken listener must not undo a close, or stop the other listeners and auctions. private void tellClosed(AuctionResult result) { for (AuctionListener listener : listeners) { try { listener.onClosed(result); } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "Close notice failed", e); } } }}demo/Main.java runs two auctions with a soft close of 2 minutes. A lamp gets two small bids and closes below its reserve. A watch gets a proxy bid, a refused low bid, a refused seller bid, a snipe that moves the end twice, and a bid that arrives exactly at the final end:
17:30:00 A-1 watch: starts at $100.00, hidden reserve, ends 18:00:00
17:30:00 A-2 lamp: starts at $5.00, hidden reserve, ends 17:55:00
17:40:00 asha bids up to $180.00 on A-1
-> LEADING, price $100.00, ends 18:00:00, reserve not met
17:45:00 ben bids up to $150.00 on A-1
-> OUTBID, price $155.00, ends 18:00:00, reserve not met
17:46:00 ben bids up to $120.00 on A-1
-> TOO_LOW, the minimum is $160.00
17:50:00 rita bids up to $200.00 on A-1
-> SELLER_CANNOT_BID
17:51:00 dev bids up to $12.50 on A-2
-> LEADING, price $5.00, ends 17:55:00, reserve not met
17:52:00 esha bids up to $20.75 on A-2
notice to dev: you were outbid on A-2, price now $13.00
-> LEADING, price $13.00, ends 17:55:00, reserve not met
17:55:00 timer calls closeDue()
notice: A-2 closed, RESERVE_NOT_MET, highest price $13.00
17:59:30 ben bids up to $300.00 on A-1
notice to asha: you were outbid on A-1, price now $250.00
-> LEADING, price $250.00, ends 18:01:30
18:00:00 timer calls closeDue()
-> nothing closed: A-1 now ends 18:01:30
18:01:00 asha bids up to $400.00 on A-1
notice to ben: you were outbid on A-1, price now $305.00
-> LEADING, price $305.00, ends 18:03:00
18:03:00 chen bids up to $500.00 on A-1
-> AUCTION_ENDED
18:03:00 timer calls closeDue()
notice: A-1 SOLD to asha for $305.00Notice three things in the output. Ben's $150 at 17:45 is OUTBID at once, and the price rises to $155 without asha doing anything: that is proxy bidding. The sweep at 18:00:00 closes nothing, because ben's snipe moved the end to 18:01:30. And chen's bid at exactly 18:03:00 is refused as AUCTION_ENDED before the sweep in the same second closes the watch at $305, ben's $300 plus one $5 step.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "The winner does not pay." | A payment step after onClosed. If it fails, a second-chance offer to the runner-up, which needs the runner-up's id in AuctionResult | Bidding, closing and the lock. |
| "Add buy-it-now." | A buyNow method on Auction, under the same lock, allowed only before the first bid. It sets result to SOLD at once | BidBook, the rules and the sweep. |
| "Stop an auction from being extended forever." | endAfterBid also takes the listing's original end, and SoftClose never goes more than, say, 30 minutes past it. Auction passes the extra argument | BidBook, the sweep and the lock. |
| "Let a bidder take back a bid." | BidBook must keep every maximum, not just two, so it can find the new runner-up. The price formula stays | The lock, the closing rule and the listeners. |
| "Show the bid history." | A list of accepted bids beside BidBook, under the same lock, and a method to read a copy | The price sums. |
| "Sell ten identical items in one auction." | A different BidBook that keeps the top ten maximums, and a result with ten winners. AuctionResult changes shape | The lock, the closing rule and the sweep. |
| "Millions of auctions." | The sweep reads a queue sorted by end time instead of every open auction. An extension adds the new end time to the queue, and a stale entry is skipped when its auction is checked | closeIfDue and its check under the lock. |
| "Run on several servers." | Each auction is owned by one server, chosen by its id, so its lock stays in one place. Listeners become a pub-sub topic | The classes inside one auction. |
| "A flat $1 step for charity sales." | A new IncrementRule, given to that house | Everything else. |
Most rows change one class or add a small one beside the core. Two are bigger: taking back a bid and selling ten items both change what BidBook must remember, because two maximums are no longer enough.
What the interviewer looks for
Mid-level
A mid-level candidate shows an auction with a highest bid, an end time and a check that refuses late and low bids. They use cents in a long, not a double. They say that two bids at once need a lock, even if the lock covers more than it needs to.
Senior
A senior candidate shows everything above and adds proxy bidding with an exact price rule, including the cap and the reserve. They put the increment and the closing rule behind interfaces, and explain soft close as the answer to sniping. They put one lock on each auction, and they keep listener calls outside it.
Staff+
A staff candidate starts from the race at the close and asks which clock reading decides. They read the time under the lock so that the order of events is the order of times. They explain why the price is worked out from two maximums, and what breaks if a bid can be taken back. They also say how ownership by auction id lets the same design run on many servers.
Common mistakes
- Storing only the highest bid. Proxy bidding needs the runner-up's maximum, and without it the price cannot be worked out.
- Charging the winner their own maximum. Nobody then gives a true maximum, and the site loses the reason proxy bidding exists.
- Storing the price and updating it in each case. One missed case, such as a leader raising after a capped price, leaves the price wrong.
- Reading the time before taking the lock. A bid can then be on time for an auction that is already closed.
- A timer set once for the original end time. After a soft-close extension it fires too early, and only a check under the lock saves it.
- Calling listeners while holding the lock. One slow email holds up every bid on that auction in its last minute.
- Exceptions for a low or late bid. These are normal answers, and the bidder needs the minimum next bid, not a stack trace.
Summary
- Ask what the winner pays, how big each step is, and what a last-second bid does. Each answer changes the code.
- Store the top two maximums and work the price out: the runner-up plus one step, capped at the leader, lifted to a met reserve.
- Put the increment tiers and the closing rule behind interfaces, and use a soft close against sniping.
- Give each auction one lock, and read the clock under it, so bids and the close happen in one order.
- Refuse a bid at the end time even before the sweep runs, and close each auction exactly once.
- Return refusals as a
BidStatus, and keep exceptions for mistakes in the calling code. - Tell listeners after the lock is released, and keep a broken listener from failing a bid or a sweep.