LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 31 OF 42

Design an Online Auction System: LLD in Java

An online auction designed and coded: requirements, auctions with start and end times, bids as an immutable chain, validation with a minimum increment and a hidden reserve price, one compare-and-set on an immutable snapshot so racing bids and closing never clash, Observer notifications for outbid bidders, closing on a fake clock, proxy bidding as an extension, and a full Java 17 solution.

Patterns usedObserverProxy

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 23

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 308 lines, with a small main() demo. Save it as AuctionHouse.java, then run javac AuctionHouse.java && java AuctionHouse.

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** Online auctions: bids swap an immutable snapshot with compare-and-set; listeners hear every change. */
public class AuctionHouse {

    // ---------- the model ----------
    static String money(long cents) { return String.format("%,d.%02d", cents / 100, cents % 100); }

    /** Each bid links to the bid it beat, so the top bid is the head of the whole history. */
    record Bid(String bidderId, long cents, Instant at, Bid previous) {}

    record BidResult(boolean accepted, String message) {}

    enum OutcomeType { SOLD, RESERVE_NOT_MET, NO_BIDS }

    record Outcome(OutcomeType type, String winnerId, long cents) {
        @Override
        public String toString() {
            return type == OutcomeType.SOLD ? "SOLD to " + winnerId + " for " + money(cents) : type.name();
        }
    }

    enum Status { SCHEDULED, LIVE, ENDED, CLOSED }

    // ---------- Observer ----------
    interface AuctionListener {
        default void onNewTop(Auction a, Bid top) {}

        default void onClosed(Auction a, Outcome o) {}
    }

    /** One per user: collects outbid, won and sold messages. Email or push would be more listeners. */
    static final class Inbox implements AuctionListener {
        final String userId;
        final Queue<String> messages = new ConcurrentLinkedQueue<>();

        Inbox(String userId) { this.userId = userId; }

        @Override
        public void onNewTop(Auction a, Bid top) {
            Bid beaten = top.previous();
            if (beaten != null && beaten.bidderId().equals(userId) && !top.bidderId().equals(userId))
                messages.add("Outbid on " + a.title + ": top is now " + money(top.cents()));
        }

        @Override
        public void onClosed(Auction a, Outcome o) {
            if (userId.equals(a.sellerId)) messages.add(a.title + " closed: " + o);
            else if (o.type() == OutcomeType.SOLD && userId.equals(o.winnerId()))
                messages.add("You won " + a.title + " for " + money(o.cents()));
            else messages.add(a.title + " closed, you did not win");
        }
    }

    /** Extension: bids for its owner, one increment at a time, up to a maximum. Just another listener. */
    record ProxyBidder(String userId, long maxCents) implements AuctionListener {
        @Override
        public void onNewTop(Auction a, Bid top) {
            if (top.bidderId().equals(userId)) return;
            long next = a.minimumNextBid(top);
            if (next <= maxCents) a.placeBid(userId, next);
        }
    }

    // ---------- the auction ----------
    static final class Auction {
        final String id;
        final String title;
        final String sellerId;
        final long startCents;
        final long minIncrementCents;
        final long reserveCents;
        final Instant startAt;
        final Instant endAt;
        private final Supplier<Instant> clock;
        private final List<AuctionListener> listeners = new CopyOnWriteArrayList<>();
        private final Set<String> watchers = ConcurrentHashMap.newKeySet();

        /** Everything that must agree lives in one immutable snapshot, swapped atomically. */
        private record State(Bid top, boolean closed) {}

        private final AtomicReference<State> state = new AtomicReference<>(new State(null, false));

        Auction(String id, String title, String sellerId, long startCents, long minIncrementCents,
                long reserveCents, Instant startAt, Instant endAt, Supplier<Instant> clock) {
            if (!endAt.isAfter(startAt)) throw new IllegalArgumentException("End must be after start");
            if (startCents <= 0 || minIncrementCents <= 0) throw new IllegalArgumentException("Bad prices");
            this.id = id;
            this.title = title;
            this.sellerId = sellerId;
            this.startCents = startCents;
            this.minIncrementCents = minIncrementCents;
            this.reserveCents = reserveCents;
            this.startAt = startAt;
            this.endAt = endAt;
            this.clock = clock;
        }

        void subscribe(AuctionListener l) { listeners.add(l); }

        long minimumNextBid(Bid top) { return top == null ? startCents : top.cents() + minIncrementCents; }

        Bid top() { return state.get().top(); }

        Status status() {
            Instant now = clock.get();
            if (state.get().closed()) return Status.CLOSED;
            if (now.isBefore(startAt)) return Status.SCHEDULED;
            return now.isBefore(endAt) ? Status.LIVE : Status.ENDED;
        }

        /** All bid rules in one place, checked against one snapshot. Null means valid. */
        private String reject(State s, String bidderId, long cents, Instant now) {
            if (s.closed() || !now.isBefore(endAt)) return "Auction has ended";
            if (now.isBefore(startAt)) return "Auction has not started yet";
            if (bidderId.equals(sellerId)) return "Sellers cannot bid on their own item";
            if (s.top() != null && s.top().bidderId().equals(bidderId))
                return "You are already the top bidder";
            long min = minimumNextBid(s.top());
            if (cents < min) return "Minimum bid is " + money(min);
            return null;
        }

        BidResult placeBid(String bidderId, long cents) {
            while (true) {
                State s = state.get();
                Instant now = clock.get();
                String why = reject(s, bidderId, cents, now);
                if (why != null) return new BidResult(false, why);
                Bid bid = new Bid(bidderId, cents, now, s.top());
                if (state.compareAndSet(s, new State(bid, false))) {
                    // notify after the swap, with no locks held
                    for (AuctionListener l : listeners) l.onNewTop(this, bid);
                    return new BidResult(true, "Top bid " + money(cents));
                }
                // another bid (or the closer) swapped first: validate again against the fresh snapshot
            }
        }

        /** A swap too, so a late bid can never land after the winner is chosen. Runs once. */
        Optional<Outcome> close() {
            while (true) {
                State s = state.get();
                if (s.closed()) return Optional.empty();
                if (state.compareAndSet(s, new State(s.top(), true))) {
                    Outcome o = outcome(s.top());
                    for (AuctionListener l : listeners) l.onClosed(this, o);
                    return Optional.of(o);
                }
            }
        }

        private Outcome outcome(Bid top) {
            if (top == null) return new Outcome(OutcomeType.NO_BIDS, null, 0);
            if (top.cents() < reserveCents) return new Outcome(OutcomeType.RESERVE_NOT_MET, null, 0);
            return new Outcome(OutcomeType.SOLD, top.bidderId(), top.cents());
        }

        /** Oldest first: walk the chain of previous bids, then reverse. */
        List<Bid> history() {
            List<Bid> out = new ArrayList<>();
            for (Bid b = top(); b != null; b = b.previous()) out.add(b);
            Collections.reverse(out);
            return out;
        }
    }

    // ---------- the service ----------
    private final Map<String, Auction> auctions = new ConcurrentHashMap<>();
    private final Map<String, Inbox> inboxes = new ConcurrentHashMap<>();
    private final Supplier<Instant> clock;

    AuctionHouse(Supplier<Instant> clock) { this.clock = clock; }

    Inbox inbox(String userId) { return inboxes.computeIfAbsent(userId, Inbox::new); }

    Auction list(String id, String title, String sellerId, long startCents, long incrementCents,
                 long reserveCents, Instant startAt, Duration length) {
        Auction a = new Auction(id, title, sellerId, startCents, incrementCents, reserveCents, startAt,
                startAt.plus(length), clock);
        watch(a, sellerId);
        auctions.put(id, a);
        return a;
    }

    private void watch(Auction a, String userId) {
        if (a.watchers.add(userId)) a.subscribe(inbox(userId)); // subscribe each user once
    }

    BidResult placeBid(String auctionId, String userId, long cents) {
        Auction a = auctions.get(auctionId);
        if (a == null) return new BidResult(false, "No auction " + auctionId);
        watch(a, userId);
        return a.placeBid(userId, cents);
    }

    /** Extension: proxy bidding. Bids now if needed, then answers every rival bid up to the maximum. */
    BidResult setProxy(String auctionId, String userId, long maxCents) {
        Auction a = auctions.get(auctionId);
        watch(a, userId);
        a.subscribe(new ProxyBidder(userId, maxCents));
        Bid top = a.top();
        if (top != null && top.bidderId().equals(userId)) return new BidResult(true, "Proxy set");
        long next = a.minimumNextBid(top);
        return next <= maxCents ? a.placeBid(userId, next) : new BidResult(false, "Maximum too low");
    }

    /** Run by a timer: closes every auction whose end time has passed. */
    List<String> closeDue() {
        Instant now = clock.get();
        List<String> results = new ArrayList<>();
        for (Auction a : auctions.values())
            if (!now.isBefore(a.endAt))
                a.close().ifPresent(o -> results.add(a.id + " " + a.title + ": " + o));
        Collections.sort(results);
        return results;
    }

    // ---------- demo ----------
    static void bid(AuctionHouse h, String auctionId, String user, long cents) {
        BidResult r = h.placeBid(auctionId, user, cents);
        System.out.printf("%-6s bids %10s -> %s%n", user, money(cents), r.message());
    }

    public static void main(String[] args) throws InterruptedException {
        Instant ten = Instant.parse("2026-06-01T10:00:00Z");
        AtomicReference<Instant> now = new AtomicReference<>(ten);
        AuctionHouse house = new AuctionHouse(now::get);
        Auction camera = house.list("A1", "Vintage camera", "sam", 1_000_00L, 50_00L, 1_400_00L, ten,
                Duration.ofHours(1));
        house.list("A2", "Signed poster", "sam", 500_00L, 25_00L, 5_000_00L, ten, Duration.ofHours(1));
        house.list("A3", "Old guitar", "sam", 3_000_00L, 100_00L, 0, ten.plus(Duration.ofHours(2)),
                Duration.ofHours(1));

        bid(house, "A3", "meera", 3_000_00L);
        bid(house, "A1", "sam", 1_000_00L);
        bid(house, "A1", "meera", 1_000_00L);
        bid(house, "A1", "kabir", 1_020_00L);
        bid(house, "A1", "kabir", 1_100_00L);
        System.out.println("meera sets a proxy up to 1,500.00 -> "
                + house.setProxy("A1", "meera", 1_500_00L).message());
        bid(house, "A1", "kabir", 1_300_00L);
        System.out.println("  top now " + camera.top().bidderId() + " " + money(camera.top().cents()));
        bid(house, "A1", "kabir", 1_500_00L);
        System.out.println("  top now " + camera.top().bidderId() + " " + money(camera.top().cents()));
        bid(house, "A2", "kabir", 2_000_00L);

        // Move the fake clock past the end instead of sleeping.
        now.set(ten.plus(Duration.ofMinutes(61)));
        System.out.println("A1 status " + camera.status());
        bid(house, "A1", "meera", 2_000_00L);
        house.closeDue().forEach(r -> System.out.println("closed " + r));
        System.out.println("A1 status " + camera.status() + ", second close: " + camera.close().isPresent());

        System.out.print("A1 history:");
        camera.history().forEach(b -> System.out.print(" " + b.bidderId() + "=" + b.cents() / 100));
        System.out.println();
        for (String user : List.of("meera", "kabir", "sam")) {
            System.out.println(user + "'s inbox:");
            house.inbox(user).messages.forEach(m -> System.out.println("  " + m));
        }

        // Eight bidders hit one live auction at once: the top must end as the biggest bid.
        Auction stamp = house.list("A4", "Rare stamp", "lee", 1_000_00L, 50_00L, 0, now.get(),
                Duration.ofMinutes(30));
        CountDownLatch start = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            String user = "bidder" + i;
            long cents = 1_000_00L + i * 100_00L;
            pool.submit(() -> {
                try {
                    start.await();
                    house.placeBid("A4", user, cents);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        start.countDown();
        pool.shutdown();
        if (!pool.awaitTermination(5, TimeUnit.SECONDS)) throw new AssertionError("race did not finish");
        List<Bid> h = stamp.history();
        boolean rising = true;
        for (int i = 1; i < h.size(); i++)
            rising &= h.get(i).cents() >= h.get(i - 1).cents() + stamp.minIncrementCents;
        System.out.println("Race: top " + money(stamp.top().cents()) + " by " + stamp.top().bidderId()
                + ", history rising: " + rising);
        if (stamp.top().cents() != 1_700_00L || !rising) throw new AssertionError("bids went wrong");
    }
}

Notes

Requirements

Fix the scope. A seller lists an item with a start time, an end time, a starting price, a minimum increment and an optional hidden reserve price. While the auction is live, bidders place bids and everyone can see the highest one. A bidder who is outbid gets a notification. At the end time the auction closes and picks a winner. Many bidders act at once. Payment and search are out of scope.

Ask the questions that turn into rules. Does the winner pay their own bid? Yes. How much must a new bid beat the top one by? At least the minimum increment. If the reserve is not met, there is no sale and the seller is told. The seller cannot bid on their own item. A bid counts only if it arrives strictly before the end time. Automatic proxy bidding comes later as an extension.

Requirements
  • seller lists an item with
  • start time and end time
  • starting price, min increment,
  • hidden reserve price
  • bidders place bids while live
  • show the highest bid
  • notify a bidder when outbid
  • close at end time, pick winner
  • many bidders at once
  • out of scope: payment, search
Clarify first
  • winner pays their own bid?
  • yes, first price
  • next bid must beat by how much?
  • top plus the min increment
  • reserve not met?
  • no sale, seller is told
  • can the seller bid?
  • no
  • bid at the end second?
  • only if before the end time
  • proxy bidding? as an extension

Entities

The entities. The auction house is the service that holds all auctions. An auction knows its item, its seller, its times and its price rules, and it tracks the top bid. A bid is who, how much and when. When an auction closes it produces an outcome: sold to someone at a price, reserve not met, or no bids. Listeners hear about new top bids and closing.

Class diagram

The types. Money is a long number of cents. A bid is an immutable record, and here is a neat trick: each bid holds a reference to the bid it beat. So the top bid is the head of a chain, and walking the previous links gives the full history in order. There is no separate list to keep in sync, which will matter a lot when we make bidding thread safe.

Value types
record Bid(String bidderId, long cents,
           Instant at, Bid previous) {}

record Outcome(OutcomeType type,
               String winnerId, long cents)
enum OutcomeType { SOLD,
    RESERVE_NOT_MET, NO_BIDS }

history: follow previous to the start

Lifecycle

The lifecycle. Before the start time an auction is scheduled. Between start and end it is live. Once the end time passes it accepts no bids, even if the closer has not run yet. When the closer runs, the auction becomes closed and its outcome is decided exactly once. Only closed is stored as a flag; everything else is computed from an injected clock, which also makes the tests fast.

Auction status
  • now before start: SCHEDULED
  • start up to end: LIVE
  • end reached, not closed: ENDED
  • (no bids accepted)
  • closer has run: CLOSED
  • (outcome decided, once)
  • time comes from an injected
  • Supplier<Instant>

Bid rules

Put every bid rule in one method. Reject if the auction is closed or the end time has passed. Reject if it has not started. Reject the seller. Then compute the minimum: the starting price if there is no bid yet, otherwise the top bid plus the increment. Notice the reserve price is not checked here; a bid below the reserve is fine, it just will not win the item. The method returns a reason, or nothing when the bid is valid.

reject(state, bidder, cents)
if (s.closed() || !now.isBefore(endAt))
  return "auction has ended";
if (now.isBefore(startAt))
  return "not started yet";
if (bidder.equals(sellerId))
  return "sellers cannot bid";
long min = top == null ? startCents
    : top.cents() + minIncrementCents;
if (cents < min) return "min is " + min;
return null;   // valid

Flow: place a bid

The bid flow. The bidder calls the auction house, which subscribes the bidder's inbox to that auction and passes the bid on. The auction reads its current snapshot, checks the rules against it, builds the new bid that points to the old top, and swaps the snapshot in. Only after the swap succeeds does it tell the listeners. Notifications never run while anything is locked.

Concurrency

Here is why the naive version breaks. Two bidders read the same top bid of one thousand. Both pass the check. One writes eleven hundred, the other writes ten fifty a moment later, and the top bid goes down. Both were told their bid was accepted. Under load this happens, and it is exactly the bug an interviewer is waiting for you to spot.

The naive version
if (cents >= top + increment) {
  // another thread runs here
  top = new Bid(bidder, cents);
}

A reads 1,000, B reads 1,000
A writes 1,100, B writes 1,050
top is now LOWER than a
  bid that was accepted

Compare-and-set

The fix is compare-and-set on an immutable snapshot. The auction keeps one atomic reference to a small record holding the top bid and the closed flag. A bid reads the snapshot, validates against it, and tries to swap in a new one. If someone else swapped first, the swap fails and the loop runs again with fresh data, so the rules are always checked against the real top bid. No locks, and readers never wait.

Auction.placeBid()
while (true) {
  State s = state.get();
  String why = reject(s, bidder, cents);
  if (why != null) return rejected(why);
  Bid b = new Bid(bidder, cents, now,
                  s.top());
  if (state.compareAndSet(s,
        new State(b, false)))
    { notify(b); return accepted(); }
  // lost the race: check again
}

Close vs late bid

Why put the closed flag inside the snapshot? Picture the closer reading the top bid to pick a winner while a last bid slips in. With a separate flag, that bid could be accepted after the winner was chosen. Because closing is also a compare-and-set on the same snapshot, either the bid lands first and the closer sees it, or the close lands first and the bid's swap fails and it sees closed. There is no in-between.

Concurrency

Is a lock wrong? Not at all. Making place bid and close synchronized on the auction is simple and correct, and for most auctions it is plenty. Compare-and-set avoids waiting, and readers who only show the top bid never block. In a database the same idea is a conditional update that changes the top bid only if it is still the one you read and the auction is not closed. Say which you picked and why.

CAS or a lock?
  • synchronized placeBid + close:
  • simplest, correct, fine for
  • most auctions
  • CAS on a snapshot:
  • no waiting, readers never
  • block, retries under a storm
  • database: UPDATE .. SET top =
  • ? WHERE id = ? AND top = old
  • AND closed = false

Observer: alerts

Notifications use the Observer pattern. The auction keeps a copy-on-write list of listeners and, after every successful bid, calls on new top. Each bidder's inbox is subscribed the first time they bid. The inbox checks whether the bid that was just beaten was its own; if so, it records you were outbid. Email, push and a live price ticker are just more listeners, and the auction never changes.

AuctionListener
interface AuctionListener {
  default void onNewTop(Auction a, Bid top)
    {}
  default void onClosed(Auction a,
                        Outcome o) {}
}
Inbox: if top.previous() was me
  and top is not me: "outbid"
listeners: CopyOnWriteArrayList

Flow: closing

Closing. A timer calls close due every few seconds. It reads the clock once and closes every auction whose end time has passed. Close is a compare-and-set that flips the flag, so if two timers run at once, only one produces an outcome and the other gets nothing back. The outcome goes to all listeners. In the demo a fake clock jumps past the end time, so nothing sleeps.

AuctionHouse.closeDue()
Instant now = clock.get();
for (Auction a : auctions.values())
  if (!now.isBefore(a.endAt))
    a.close().ifPresent(o ->
        results.add(a.id + " " + o));

close() returns empty if it was
  already closed: runs once

Reserve price

The reserve price is the lowest amount the seller will accept, and bidders do not see it. It is checked only once, when the auction closes. No bids means no sale. A top bid below the reserve means reserve not met, and the seller keeps the item. Otherwise the top bidder wins at their own bid. Keeping this in one small method makes the rule easy to change, for example to show a reserve met badge.

outcome(top)
if (top == null)
  return new Outcome(NO_BIDS, null, 0);
if (top.cents() < reserveCents)
  return new Outcome(RESERVE_NOT_MET,
                     null, 0);
return new Outcome(SOLD,
    top.bidderId(), top.cents());

Proxy bidding

Proxy bidding is the classic extension. A bidder says: bid for me, up to fifteen hundred. The neat part is that this needs no change to the auction at all. A proxy bidder is just another listener. Whenever someone else takes the top spot, it places the smallest valid bid on its owner's behalf, as long as that stays within the maximum. When the next bid would pass the maximum, it stops, and the owner's inbox says outbid.

Watch it run. Meera sets a maximum of fifteen hundred. Kabir bids thirteen hundred, and the proxy instantly answers thirteen fifty. Kabir bids fifteen hundred. The proxy would need fifteen fifty, which is above the maximum, so it stays quiet, and Meera's inbox gets an outbid alert. Real sites resolve two proxies in one step instead of bidding back and forth; mention that as a refinement.

ProxyBidder
record ProxyBidder(String userId,
    long maxCents) implements
    AuctionListener {
  public void onNewTop(Auction a, Bid t) {
    if (t.bidderId().equals(userId))
      return;
    long next = a.minimumNextBid(t);
    if (next <= maxCents)
      a.placeBid(userId, next);
  }
}

Concurrency

Check every shared thing. The top bid and the closed flag live together in one atomic snapshot, and because each bid links to the previous one, the history is inside that snapshot too, always consistent. Listeners are in a copy-on-write list, and watcher ids in a concurrent set. Auctions sit in a concurrent map. Notifications happen after the swap, and closing is a swap too, so it happens once.

Thread safety checklist
  • top bid + closed: one
  • AtomicReference<State>
  • bid history: immutable chain
  • inside the snapshot
  • listeners: CopyOnWriteArrayList
  • watchers: concurrent key set
  • auctions: ConcurrentHashMap
  • notify after the CAS, never
  • while holding anything
  • close(): CAS, so it runs once

Extensibility

Interviewers like to add rules. Anti-sniping, where a bid in the last two minutes extends the auction, moves the end time into the snapshot so the same swap updates it. A buy-it-now price closes the auction on a matching bid. A Dutch auction, where the price falls over time, is a different auction type. To persist, store bids in a table with a unique auction and sequence number, so the database rejects a racing duplicate.

Extension points
  • anti-sniping: a late bid moves
  • endAt forward (into State)
  • buy-it-now price: a rule that
  • closes on a matching bid
  • Dutch auction: a new Auction
  • type, price drops on a clock
  • bid retraction: a new event
  • persist: bids table, unique
  • (auction_id, sequence)

Testing

The full code is below the player. The demo rejects a seller bidding on their own item and a bid below the increment, shows an outbid alert, runs a proxy bidder until its maximum, moves the fake clock past the end and rejects a late bid, then closes the auction as sold. A second auction ends with the reserve not met. Finally eight threads bid at once, and the top is always the biggest bid, with a strictly rising history.

Run it
sam bids on own item -> rejected
meera 1,000  -> accepted
kabir 1,020  -> min is 1,050.00
kabir 1,100  -> accepted, meera outbid
meera proxy up to 1,500
kabir 1,300 -> proxy 1,350 ...
kabir 1,500 -> proxy stops
clock +61 min: late bid rejected
A1 SOLD to kabir for 1,500.00
poster: RESERVE_NOT_MET
race: top is the biggest bid

Follow-ups

Expect these follow-ups. Two bids of the same amount? The first swap wins and the second now fails the increment rule. Millions watching one auction? Publish new top bids to a message broker and fan them out to websockets. A server restart? Rebuild each auction's top from the bids table. Clock skew? One server's clock decides the end. And if the winner never pays, offer the item to the next highest bidder.

Follow-ups to expect
  • two bids, same amount?
  • first CAS wins, second fails
  • millions watching one auction?
  • push via a message broker
  • server restarts mid-auction?
  • rebuild from the bids table
  • clock skew between servers?
  • one time source decides
  • winner never pays?
  • offer to second highest

Say it like this

Here is the short version to say out loud. Each auction keeps one atomic snapshot holding the top bid and the closed flag. Bids are validated against it and swapped in with compare-and-set, and closing is also a swap, so no bid sneaks in after the winner is chosen. Inboxes and proxy bidders are listeners, and time comes from an injected clock.

In the interview
  • "An auction keeps one atomic
  • snapshot: top bid and closed.
  • Bids validate against it and
  • swap it with compare-and-set;
  • closing is a swap too, so no
  • bid sneaks in after. Inboxes
  • and proxy bidders are
  • listeners. Time is injected."

Interview questions

How do you handle two bids arriving at the same time?

Keep the top bid in an AtomicReference to an immutable snapshot. Each bid reads the snapshot, validates against it and swaps with compareAndSet; if another bid swapped first, it retries with fresh data. A synchronized placeBid is an equally correct, simpler choice.

How do you stop a bid being accepted after the auction closed?

Put the closed flag in the same atomic snapshot as the top bid, and make close a compare-and-set too. Either the bid swaps first and the closer sees it, or the close swaps first and the bid sees closed. Also reject any bid whose time is not before the end time.

What validation does a bid need?

The auction must be live (after start, before end, not closed), the bidder must not be the seller, and the amount must be at least the starting price, or the current top plus the minimum increment. The reserve is not a bid rule; it only matters at closing.

How does the reserve price work?

It is a hidden minimum the seller will accept. At closing, if the top bid is below it, the outcome is reserve not met and the item is not sold; otherwise the top bidder wins at their bid.

How are bidders notified when they are outbid?

Observer pattern: the auction calls registered listeners after each successful bid. A bidder’s inbox checks whether the beaten bid was theirs and records an outbid alert. New channels such as email or push are extra listeners.

How would you implement proxy (automatic) bidding?

A ProxyBidder listener holds a maximum. When someone else becomes the top bidder, it places the minimum valid next bid if that is within the maximum. Production systems resolve competing proxies in one calculation instead of bidding back and forth.

How do auctions close on time without a thread per auction?

One scheduled task runs every few seconds, reads the clock once and closes every auction past its end time. Close is idempotent, so overlapping runs are safe. For very many auctions, keep a priority queue ordered by end time.

How would you test closing and timing logic?

Inject the clock as a Supplier of Instant. Tests set the time before the start, during, and after the end, and call the closer directly, with no sleeping and no flaky timing.

How do you prevent last-second sniping?

Anti-sniping: if a bid arrives within the last few minutes, extend the end time. Store the end time in the same atomic snapshot so the bid and the extension happen in one swap.