LLD

Full Designs

Ticket Waitlist

A weak answer puts people in a queue and pops the first one when a ticket comes back. We build the waitlist for a sold-out show so that returned tickets go to the right person under a rule that can change, an offer holds tickets for a fixed time, a declined card does not lose anyone's place, and a ticket coming back, an offer running out and a payment arriving at the same moment never give one ticket to two people.

"Design a waitlist for a sold-out concert" sounds like a queue. A weak answer puts people in a Queue, and when a ticket comes back it pops the first person and sells them the ticket. Then it stops. Nothing in that answer says what happens when the first person wants four tickets and only two came back, or when they never answer.

The interviewer is checking three things. First, the rule for who gets tickets back, and whether that rule can change without a rewrite. Second, the offer: tickets held for one person for a fixed time, and what happens when the time runs out, the person says no, or the card is declined. Third, concurrency. A ticket can come back, an offer can run out and a payment can arrive in the same instant, and no ticket may go to two people or be lost.

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.

The waitlist at a glance
People join a tier's line with the number of tickets they want (1). The box office sends tickets back when someone cancels (2). The fit rule picks who gets them, and the waitlist makes an offer that holds those tickets for 15 minutes (3). The notifier tells that person (4). They claim the offer, and the payment gateway charges their card (5). If they decline, or the offer runs out, its tickets go back to the free count and round again (6).People join a tier's line with the number of tickets they want (1). The box office sends tickets back when someone cancels (2). The fit rule picks who gets them, and the waitlist makes an offer that holds those tickets for 15 minutes (3). The notifier tells that person (4). They claim the offer, and the payment gateway charges their card (5). If they decline, or the offer runs out, its tickets go back to the free count and round again (6).
Tickets that come back become offers. An offer ends in a claim, or its tickets go round again. People join a tier's line with the number of tickets they want (1). The box office sends tickets back when someone cancels (2). The fit rule picks who gets them, and the waitlist makes an offer that holds those tickets for 15 minutes (3). The notifier tells that person (4). They claim the offer, and the payment gateway charges their card (5). If they decline, or the offer runs out, its tickets go back to the free count and round again (6).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Does the waitlist pick seats?No. A tier, such as general admission, has a count of ticketsNo seat ids; a count per tier
Where do tickets come from?Cancellations, or the organiser releasing moreOne release(tier, count) method
How many tickets can one person want?1 to 4, counting tickets already claimedA limit checked on join
Can one person wait twice, or in two tiers?No. One entry per person per eventOne map from person to entry
Someone wants 4 and 2 come back. Who gets them?The first person in line who fits. The rule will changeAn interface for the rule
How long does an offer last?15 minutes, set per eventAn offer with a deadline, and a clock we control
What if the person declines or never answers?They leave the line, and the tickets go to the next personA sweep that ends late offers
How do people pay?By card, through a gateway that can decline or failAn interface for the gateway, called outside any lock
Do people see their place in line?YesA position query
Do things happen at once?Yes: returns, claims and the timer, from many threadsEvery method is safe to call from many threads

The question about partial fits matters most. A person who wants four tickets blocks everyone behind them, or is skipped by everyone behind them. Either answer is a fairness rule, and the business will change its mind about it.

Requirements

Functional:

  1. A person joins one tier's line for 1 to 4 tickets. A second entry for the same person, in any tier, is refused, and so is a request that takes them over 4 tickets claimed and wanted together.
  2. When tickets come back to a tier, a fit rule picks who gets them. That person gets an offer that holds those tickets for 15 minutes, and is told about it.
  3. The person claims the offer by paying for it before it runs out. A declined card leaves the offer open until its deadline.
  4. An offer that is declined or runs out takes the person out of line, and its tickets go to the next person the rule picks.
  5. A person can leave the line at any time, and can ask for their place in it.
  6. No ticket is held by two offers, claimed twice, or lost.

Out of scope: seat maps, closing the waitlist when the doors open, waiting in two tiers, presale fans going first, and many servers. We come back to these at the end. Picking seats and holding them is the BookMyShow design; this page is about the line in front of the tickets.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Many things at once. release, claim, decline and the timer's sweep run on many threads, often on the same offer.
  • A rule that changes. Who gets returned tickets is a business choice. Changing it must not mean editing the core class.
  • A slow, unreliable bank. A charge can be declined, take time, or throw without saying whether money moved.
  • Time. Deadlines must be testable, so the code takes a Clock and never reads the system time itself.

Finding the classes

The nouns in the requirements are event, tier, ticket, seat, person, line, entry, offer, card, payment and message. Most become classes. Some do not.

From nouns to classes
Event, tier, entry, offer and claim become records. The waitlist becomes the one class with behaviour, EventWaitlist. The rule for partial fits becomes the FitRule interface, and the bank and the text message become interfaces too. The state of an offer becomes the OfferStatus enum. A ticket becomes a count on its tier, a person becomes an id string, the line becomes a map inside EventWaitlist, the box office is a caller of release(), and a seat is BookMyShow's business.Event, tier, entry, offer and claim become records. The waitlist becomes the one class with behaviour, EventWaitlist. The rule for partial fits becomes the FitRule interface, and the bank and the text message become interfaces too. The state of an offer becomes the OfferStatus enum. A ticket becomes a count on its tier, a person becomes an id string, the line becomes a map inside EventWaitlist, the box office is a caller of release(), and a seat is BookMyShow's business.
Most nouns become classes. A ticket, a person and the line do not. Event, tier, entry, offer and claim become records. The waitlist becomes the one class with behaviour, EventWaitlist. The rule for partial fits becomes the FitRule interface, and the bank and the text message become interfaces too. The state of an offer becomes the OfferStatus enum. A ticket becomes a count on its tier, a person becomes an id string, the line becomes a map inside EventWaitlist, the box office is a caller of release(), and a seat is BookMyShow's business.
Decision

Should a ticket be an object?

A Ticket class with an id and a status

A ticket that comes back would be found, marked free, then marked held by an offer. That is three changes to keep in step for every ticket. General admission tickets are all the same, so the ids carry no information.

No. A tier has a count of free ticketsOur pick

A returned ticket adds 1 to freeTickets for its tier, and an offer subtracts its quantity. An offer records how many it holds. If seats matter, the seat ids and their holds come from BookMyShow, and the waitlist still only decides who goes next.

Data or behaviour?

Most classes here carry data that never changes once made, so they are records: Event, Tier, Entry, Offer and Claim. A record's fields are fixed at creation, and it gets equals, hashCode and toString for free.

waitlist/Offer.javalines 6–6 of 7
public record Offer(String id, String personId, String tierId, int quantity, long amountCents, Instant expiresAt) {

An Offer has no status field. Its status changes several times in its life, and every change must happen under the waitlist's lock, so the status lives in a map inside EventWaitlist. The offer itself stays a fixed record that is safe to hand to the notifier.

The class diagram

The classes and how they connect
EventWaitlist owns the lines, the free counts, the live offers and their statuses, and one lock over all of them. It holds a FitRule, a PaymentGateway, an OfferNotifier and a Clock, and knows none of their implementations. SkipToFit and StrictOrder implement FitRule. Event, Tier, Entry, Offer, Claim and PaymentResult are records, and OfferStatus is an enum.EventWaitlist owns the lines, the free counts, the live offers and their statuses, and one lock over all of them. It holds a FitRule, a PaymentGateway, an OfferNotifier and a Clock, and knows none of their implementations. SkipToFit and StrictOrder implement FitRule. Event, Tier, Entry, Offer, Claim and PaymentResult are records, and OfferStatus is an enum.
EventWaitlist owns every changing thing. A rule, a bank and a messenger sit behind interfaces. EventWaitlist owns the lines, the free counts, the live offers and their statuses, and one lock over all of them. It holds a FitRule, a PaymentGateway, an OfferNotifier and a Clock, and knows none of their implementations. SkipToFit and StrictOrder implement FitRule. Event, Tier, Entry, Offer, Claim and PaymentResult are records, and OfferStatus is an enum.

The classes fall into three groups:

  • Data: Event, Tier, Entry, Offer, Claim, PaymentResult and the OfferStatus enum.
  • The core: EventWaitlist. It holds every piece of state that changes and keeps it correct under many threads.
  • Rules and outside systems: FitRule, PaymentGateway, OfferNotifier and java.time.Clock. The core depends on these and never on an implementation.

Building it

Joining the line

EventWaitlist keeps one LinkedHashMap per tier, from person to entry. A LinkedHashMap remembers the order of insertion, so it is the line, and it can also remove a person from the middle in one step. A second map, entriesByPerson, finds anyone's entry without knowing their tier.

waitlist/EventWaitlist.javalines 83–109 of 404
    public Entry join(String personId, String tierId, int quantity) {        Objects.requireNonNull(personId, "personId");        Objects.requireNonNull(tierId, "tierId");        if (quantity < 1) {            throw new IllegalArgumentException("quantity must be at least 1");        }        return lockedGet(now -> {            if (!tiers.containsKey(tierId)) {                throw new JoinRefusedException("there is no tier " + tierId);            }            if (entriesByPerson.containsKey(personId)) {                throw new JoinRefusedException(personId + " is already waiting");            }            int allowed = maxPerPerson - claimedByPerson.getOrDefault(personId, 0);            if (allowed == 0) {                throw new JoinRefusedException(personId + " has already claimed " + maxPerPerson + " tickets");            }            if (quantity > allowed) {                throw new JoinRefusedException(personId + " can ask for at most " + allowed + " tickets");            }            Entry entry = new Entry(personId, tierId, quantity, now);            lines.get(tierId).put(personId, entry);            entriesByPerson.put(personId, entry);            offerFreeTickets(tierId, now);            return entry;        });    }

join refuses a person who already has an entry in any tier, and a request over the limit. The limit counts tickets already claimed, so someone who claimed 3 can come back for 1 more, not 4, and someone who claimed 4 is told so. A refusal is a JoinRefusedException with a message for the person. A quantity under 1 or a null id is a programmer's mistake, because the app only offers 1 to 4, so those throw IllegalArgumentException or NullPointerException before the lock is taken.

The last step of join is offerFreeTickets. Tickets may already be free, waiting for someone who fits, and the new person may be that someone.

Decision

One entry per person, or one per tier?

One entry per person per tier

A fan could wait for general admission and for the floor at once. Then two offers can arrive together, and the limit has to be checked again at claim time, across tiers. Each tier's line also needs to know about the others.

One entry per person for the whole eventOur pick

One map from person to entry gives the duplicate check, the place in line and the limit in one lookup. The cost is that a fan must choose a tier. The follow-up table at the end says what changes if they need not.

Who gets returned tickets

Two tickets come back. Asha is first in line and wants 4, and Ben is second and wants 2. There are three reasonable answers. The tickets can wait until Asha's 4 are free. They can go to Ben, the first person they fit. Or Asha can be offered 2 of her 4. Each one is fair in its own way, and an organiser will want to switch.

fit/FitRule.javalines 8–15 of 15
/** Decides who gets the next offer when tickets come back to a tier. */public interface FitRule {    /**     * Picks one of the people waiting, who are listed in the order they joined,     * or nobody. The person picked must want no more than freeTickets.     */    Optional<Entry> pick(List<Entry> waiting, int freeTickets);}

The rule gets the people waiting in one tier, in the order they joined, and the number of free tickets. It returns one person or nobody. People holding a live offer are left out of the list before the rule sees it. Here are the two rules in the project:

fit/SkipToFit.javalines 9–19 of 19
public class SkipToFit implements FitRule {    @Override    public Optional<Entry> pick(List<Entry> waiting, int freeTickets) {        for (Entry entry : waiting) {            if (entry.quantity() <= freeTickets) {                return Optional.of(entry);            }        }        return Optional.empty();    }}
fit/StrictOrder.javalines 9–21 of 21
public class StrictOrder implements FitRule {    @Override    public Optional<Entry> pick(List<Entry> waiting, int freeTickets) {        if (waiting.isEmpty()) {            return Optional.empty();        }        Entry first = waiting.get(0);        if (first.quantity() <= freeTickets) {            return Optional.of(first);        }        return Optional.empty();    }}
Two tickets come back, two rules
Asha wants 4, Ben 2 and Chen 1, and 2 tickets come back. StrictOrder looks only at Asha. She wants more than 2, so nobody is offered anything and the 2 tickets wait. SkipToFit passes over Asha, who keeps place 1, and offers both tickets to Ben, the first person who wants 2 or fewer.Asha wants 4, Ben 2 and Chen 1, and 2 tickets come back. StrictOrder looks only at Asha. She wants more than 2, so nobody is offered anything and the 2 tickets wait. SkipToFit passes over Asha, who keeps place 1, and offers both tickets to Ben, the first person who wants 2 or fewer.
StrictOrder keeps the line's order. SkipToFit keeps tickets moving. Asha wants 4, Ben 2 and Chen 1, and 2 tickets come back. StrictOrder looks only at Asha. She wants more than 2, so nobody is offered anything and the 2 tickets wait. SkipToFit passes over Asha, who keeps place 1, and offers both tickets to Ben, the first person who wants 2 or fewer.

The core calls the rule in a loop, because one return can serve several people:

waitlist/EventWaitlist.javalines 272–296 of 404
    private void offerFreeTickets(String tierId, Instant now) {        int free = freeTickets.get(tierId);        while (free > 0) {            List<Entry> waiting = lines.get(tierId).values().stream()                    .filter(entry -> !liveOfferIdByPerson.containsKey(entry.personId()))                    .toList();            Optional<Entry> picked = fitRule.pick(waiting, free);            if (picked.isEmpty()) {                return;            }            Entry entry = picked.get();            if (!waiting.contains(entry) || entry.quantity() > free) {                throw new IllegalStateException("the fit rule picked " + entry + " with " + free + " free");            }            long amountCents = Math.multiplyExact(tiers.get(tierId).priceCents(), entry.quantity());            Offer offer = new Offer("O-" + nextOfferNumber++, entry.personId(), tierId, entry.quantity(),                    amountCents, now.plus(offerWindow));            free -= entry.quantity();            freeTickets.put(tierId, free);            liveOffers.put(offer.id(), offer);            liveOfferIdByPerson.put(entry.personId(), offer.id());            statuses.put(offer.id(), OfferStatus.OPEN);            offersToSend.add(offer);        }    }

Each pass builds the list of people waiting, asks the rule, and makes one offer. The offer's price is the tier's price times the quantity. The constructor refuses a tier whose price for the most tickets one person may want would not fit in a long, so this multiplication cannot overflow. The loop stops when nothing is free or the rule picks nobody. Lines 283 to 285 check the rule's answer. A rule that picks a stranger, or someone who wants more than is free, throws IllegalStateException before any offer is made.

Decision

Who gets tickets when the first person wants more than came back?

The first person waits for enough tickets (StrictOrder)

This keeps the order people joined in exactly. But tickets can sit unsold while one large group waits, and a show that is close to starting can end with empty spaces.

Offer the first person what came back, fewer than they asked for

Tickets move, and the order holds. But a group of four who get two must decide who stays home, and a "no" puts the tickets back after a wasted offer window. It also needs a smallest acceptable number on each entry.

A FitRule interface, with SkipToFit as the defaultOur pick

The first person who fits gets the tickets, and anyone skipped keeps their place for the next return. Tickets do not sit idle. The cost is that a large group can be passed over many times while small returns trickle in. An organiser who cares more about order passes StrictOrder instead, and nothing else changes.

Offers that end

An offer has a short life. It starts OPEN. A claim moves it to CLAIMING while the bank is asked, and then to CLAIMED. It can also end as DECLINED or LAPSED.

The life of an offer
A new offer is OPEN. claim() moves it to CLAIMING and calls the bank. An approval makes it CLAIMED. A declined card or a failed call before the deadline puts it back to OPEN (amber), and after the deadline it becomes LAPSED. decline() or leave() makes an OPEN offer DECLINED, and the deadline makes it LAPSED. DECLINED and LAPSED offers give their tickets back to the free count.A new offer is OPEN. claim() moves it to CLAIMING and calls the bank. An approval makes it CLAIMED. A declined card or a failed call before the deadline puts it back to OPEN (amber), and after the deadline it becomes LAPSED. decline() or leave() makes an OPEN offer DECLINED, and the deadline makes it LAPSED. DECLINED and LAPSED offers give their tickets back to the free count.
Only OPEN and CLAIMING offers hold tickets. A new offer is OPEN. claim() moves it to CLAIMING and calls the bank. An approval makes it CLAIMED. A declined card or a failed call before the deadline puts it back to OPEN (amber), and after the deadline it becomes LAPSED. decline() or leave() makes an OPEN offer DECLINED, and the deadline makes it LAPSED. DECLINED and LAPSED offers give their tickets back to the free count.

When an offer is declined or lapses, endOffer takes the person out of line and adds the tickets back to the free count. Then offerFreeTickets runs for that tier, so the tickets go straight to the next person.

Decision

What happens to someone who declines or lets an offer lapse?

They keep their place

The rule would pick the same person on the next pass, and the tickets would bounce between them and the free count. A person who never reads their messages would hold up the line for ever.

They go to the back of the line

This is gentler, but a person who never answers comes round again and again, and each visit costs the people behind a full offer window.

They leave the lineOur pick

One offer per entry keeps the line moving. A person who said no, or who did not answer in 15 minutes, can join again and starts at the back. That is the same place the second option gives them, but only if they ask.

Something has to notice that a deadline has passed. lapseExpired runs at the start of every call that takes the lock:

waitlist/EventWaitlist.javalines 256–270 of 404
    private void lapseExpired(Instant now) {        List<Offer> lapsed = new ArrayList<>();        for (Offer offer : liveOffers.values()) {            if (statuses.get(offer.id()) == OfferStatus.OPEN && !now.isBefore(offer.expiresAt())) {                lapsed.add(offer);            }        }        for (Offer offer : lapsed) {            endOffer(offer, OfferStatus.LAPSED);        }        // All lapsed tickets are back before anyone is offered them, so one sweep gives one answer.        for (String tierId : lapsed.stream().map(Offer::tierId).distinct().toList()) {            offerFreeTickets(tierId, now);        }    }

The check is !now.isBefore(offer.expiresAt()), so an offer made at 19:10 lapses at exactly 19:25. Only OPEN offers lapse here; line 259 skips a CLAIMING offer, for a reason we come to under claiming. The method first ends every late offer and only then offers the tickets again. If two single tickets lapse in one sweep and the next person wants 2, they get both, whatever order the two offers are found in.

Decision

Who ends an offer whose time is up?

A timer for every offer

Each offer schedules its own end. A busy show has thousands of timers, a timer that fires late leaves tickets held, and tests have to wait for real time to pass.

A background job that sweeps every few seconds, and nothing else

It is simple, but between two sweeps a claim can arrive for an offer that has run out, and nothing stops it.

Every call lapses old offers first, and a job may sweep as wellOur pick

Every public method that touches offers or lines lapses late offers before it does anything else, so no call treats an OPEN offer past its deadline as open. expireOffers exists for a timer to call every few seconds, so a quiet waitlist still moves its tickets on and tells the next person. Time comes from the injected Clock, so tests move it forward by exactly 15 minutes. This is the same answer as BookMyShow's holds.

Leaving works the same way. leave on a person holding an open offer declines it, and their tickets go to the next person:

waitlist/EventWaitlist.javalines 111–129 of 404
    /** Takes a person out of line. An open offer is declined and its tickets go to the next person. */    public boolean leave(String personId) {        Objects.requireNonNull(personId, "personId");        return lockedGet(now -> {            Entry entry = entriesByPerson.get(personId);            if (entry == null) {                return false;            }            String offerId = liveOfferIdByPerson.get(personId);            if (offerId != null) {                requireOpen(offerId);                endOffer(liveOffers.get(offerId), OfferStatus.DECLINED);            } else {                removeFromLine(entry);            }            offerFreeTickets(entry.tierId(), now);            return true;        });    }

Line 126 matters even when the person had no offer. Under StrictOrder, free tickets may be waiting for the first person in line. If that person leaves, the next one may fit the tickets already free, so the tickets are offered again.

Claiming and paying

A claim calls the bank, and the bank is slow. The waitlist must not hold its lock while it waits, or every return and every sweep would stop behind one card. So claim has three steps, and only the first and last take the lock.

waitlist/EventWaitlist.javalines 165–203 of 404
    public Claim claim(String offerId, String card) {        Objects.requireNonNull(offerId, "offerId");        Objects.requireNonNull(card, "card");        Attempt attempt = lockedGet(now -> {            Offer open = requireOpen(offerId);            statuses.put(offerId, OfferStatus.CLAIMING);            int number = attempts.merge(offerId, 1, Integer::sum);            return new Attempt(open, offerId + "/" + number);        });        Offer offer = attempt.offer();        String chargeKey = attempt.chargeKey();         PaymentResult result;        try {            result = Objects.requireNonNull(gateway.charge(chargeKey, offer.amountCents(), card), "no result");        } catch (RuntimeException e) {            voidQuietly(chargeKey);            try {                afterFailedCharge(offer);            } catch (RuntimeException alsoFailed) {                e.addSuppressed(alsoFailed);            }            throw e;        }        if (!result.approved()) {            afterFailedCharge(offer);            throw new PaymentFailedException("the card was declined for " + offerId);        }         finishLocked(now -> {            statuses.put(offerId, OfferStatus.CLAIMED);            liveOffers.remove(offerId);            liveOfferIdByPerson.remove(offer.personId());            removeFromLine(entriesByPerson.get(offer.personId()));            claimedByPerson.merge(offer.personId(), offer.quantity(), Integer::sum);        });        return new Claim(offerId, offer.personId(), offer.tierId(), offer.quantity(), offer.amountCents(),                result.reference());    }
  1. Mark the offer CLAIMING (lines 168 to 173). requireOpen refuses an offer that is not OPEN, so a second claim of the same offer, from another phone or a double tap, is refused here. The charge key is the offer id and an attempt number, such as O-5/1.
  2. Charge the card, with no lock held (lines 178 to 192). A declined card or an exception goes to afterFailedCharge.
  3. Mark the offer CLAIMED (lines 194 to 200), take the person out of line, and add the quantity to what they have claimed, which the limit counts.

The gateway promises that two calls with the same key charge at most once. Each attempt gets its own key, because a second attempt may use a different card. If charge throws, nobody knows whether money moved, so claim first calls voidCharge with that key. The gateway promises that a void gives the money back if the charge went through, and refuses a later charge with that key if it did not. If the void fails too, the key goes into chargesToVoid for a job to retry with retryVoids, and the gateway's own exception still reaches the caller, with any later failure attached to it.

waitlist/EventWaitlist.javalines 395–403 of 404
    private void voidQuietly(String chargeKey) {        try {            gateway.voidCharge(chargeKey);        } catch (RuntimeException e) {            synchronized (lock) {                chargesToVoid.add(chargeKey);            }        }    }
waitlist/EventWaitlist.javalines 334–343 of 404
    private void afterFailedCharge(Offer offer) {        finishLocked(now -> {            if (now.isBefore(offer.expiresAt())) {                statuses.put(offer.id(), OfferStatus.OPEN);            } else {                endOffer(offer, OfferStatus.LAPSED);                offerFreeTickets(offer.tierId(), now);            }        });    }

After a failed charge, an offer still inside its deadline goes back to OPEN, and the person can try another card. An offer whose deadline passed while the bank was thinking lapses there and then, and its tickets go to the next person.

Decision

What happens to an offer when the card is declined?

The offer ends and the tickets go to the next person

This is simple, but one mistyped card number costs a fan their tickets after a long wait.

It stays open until its deadlineOur pick

The person can try again with another card. Nobody else waits longer than the 15 minutes they would have waited anyway, because the deadline does not move.

Decision

Can an offer lapse while its payment is running?

Yes, at its deadline, and a late approval is refunded

BookMyShow chose this for seat holds. The deadline means the same in every state. But the sweep would hand the tickets to the next person while the first person's bank may still say yes, so a refund is needed every time a payment ends late.

No. A claim that starts in time finishesOur pick

The deadline decides who may start a claim. lapseExpired skips CLAIMING offers, so a claim that began at 19:19:59 is honoured even if the bank answers at 19:20:05, and no refund is needed. The cost is that an offer can outlive its deadline by as long as the bank takes, so the gateway must answer within its own timeout. The PaymentGateway interface states that promise.

A ticket comes back as an offer runs out

Here is the moment the design must survive. Ben's offer O-1 ends at 19:20:00. At that instant, his claim arrives on one thread and the timer's sweep runs on another. A returned ticket on a third thread would lapse the offer too, because every call lapses late offers first.

A claim and a sweep at the deadline
On the left, there is no lock. The claim reads O-1 as OPEN and starts charging Ben. The sweep also reads O-1 as OPEN and past its deadline, lapses it and offers the same 2 tickets to Fay. Ben is charged, and Fay is offered his tickets. On the right, both take the event's lock. If the claim is first, O-1 is CLAIMING and the sweep skips it. If the sweep is first, O-1 is LAPSED and the claim is refused before any charge.On the left, there is no lock. The claim reads O-1 as OPEN and starts charging Ben. The sweep also reads O-1 as OPEN and past its deadline, lapses it and offers the same 2 tickets to Fay. Ben is charged, and Fay is offered his tickets. On the right, both take the event's lock. If the claim is first, O-1 is CLAIMING and the sweep skips it. If the sweep is first, O-1 is LAPSED and the claim is refused before any charge.
Without a lock, the claim and the sweep can both believe they own Ben's tickets. On the left, there is no lock. The claim reads O-1 as OPEN and starts charging Ben. The sweep also reads O-1 as OPEN and past its deadline, lapses it and offers the same 2 tickets to Fay. Ben is charged, and Fay is offered his tickets. On the right, both take the event's lock. If the claim is first, O-1 is CLAIMING and the sweep skips it. If the sweep is first, O-1 is LAPSED and the claim is refused before any charge.

EventWaitlist has one lock, a plain Object, and every method that reads or changes its state takes it. Everything goes through underLock, except the three small methods for the list of voids, which take the lock directly:

waitlist/EventWaitlist.javalines 364–383 of 404
    /** Lapses old offers if asked, runs the action, then sends the new offers once the lock is released. */    private <T> T underLock(boolean lapseFirst, Function<Instant, T> action) {        List<Offer> made = List.of();        try {            synchronized (lock) {                try {                    Instant now = clock.instant();                    if (lapseFirst) {                        lapseExpired(now);                    }                    return action.apply(now);                } finally {                    made = List.copyOf(offersToSend);                    offersToSend.clear();                }            }        } finally {            sendQuietly(made);        }    }

Inside the lock, underLock reads the clock, lapses late offers, then runs the method's own work. A method that waited for the lock judges deadlines by the moment it runs, not the moment it was called. The last step of a claim and the step after a failed charge go through finishLocked, which skips the sweep. A sweep for some other offer could throw, and these steps must finish what the claim started. Between the claim's first step and its last, the offer is CLAIMING, and no other method will change it: requireOpen refuses it, lapseExpired skips it, and leave refuses a person whose offer is being paid for.

The project includes a check, demo/RaceCheck.java. It runs 200 rounds. In each round, 40 people wait for 1 to 4 tickets. Three threads return 30 tickets one at a time. Four threads pick up offers as they are sent, then claim them, decline them, or put them back to answer later. The bank declines one card in four. One more thread moves the clock forward a minute at a time and sweeps. After each round, every returned ticket must be free, held by a live offer, or claimed, exactly once.

$ java demo.RaceCheck
200 rounds: 40 people waiting, 30 tickets coming back one at a time, 8 threads
Tickets claimed: 5478
Offers that lapsed: 1504
Rounds where a ticket was lost or held twice: 0
Offers claimed twice: 0
Claims for a number of tickets other than asked: 0
Rounds where money taken does not match tickets claimed: 0

The counts of tickets claimed and offers lapsed change from run to run. The four zeros do not. We also ran the same check with the lock removed from underLock. Both runs we tried crashed. One threw a ConcurrentModificationException, because one thread changed the live offers while another walked them. The other failed on a null that had slipped into the list of offers waiting to be sent.

Decision

Where does the lock go?

A ConcurrentHashMap for each piece of state

Each map is safe on its own, but a lapse changes four of them: the offer's status, the live offers, the line and the free count. Another thread can see some of those changes and not others.

A lock per tier

Returns in different tiers would not wait for each other. But join checks a person across every tier, and the limit spans tiers, so those calls would need every tier's lock, taken in a fixed order.

One lock per eventOur pick

Everything that must stay consistent sits under one lock. It is held only for map reads and writes, never for the bank or the notifier, so calls wait for each other only briefly. Different events have different waitlists and never wait for each other.

Telling people

When an offer is made, the person must hear about it, usually by text message. That message is outside code and can be slow or fail.

notify/OfferNotifier.javalines 5–8 of 8
/** Tells a person they have tickets to claim, by text or email. Outside our code. */public interface OfferNotifier {    void offerMade(Offer offer);}

Offers are made inside the lock, but they are not sent there. offerFreeTickets adds each new offer to offersToSend. When the method's work ends, underLock copies that list and clears it while it still holds the lock. After the lock is released, the finally at line 380 sends each offer through sendQuietly. That finally also sends offers made by the lapse at the start of a call that then failed, such as a join that was refused. sendQuietly logs a notifier that throws and goes on to the next offer.

Decision

When is a person told about an offer?

Inside the lock, as the offer is made

The message would go out in the same step. But a slow text service would hold the lock, and every claim and return would wait for it. A notifier that waits for another thread to read the waitlist would never finish.

After the lock is releasedOur pick

The lock is held only for map work. The cost is that a message can arrive a moment after the offer has already changed, for example after a fast decline. The message is a prompt, so the app should read the offer's status before it shows a pay button.

The final design

EventWaitlist is the core. It owns the lines, the free counts and every offer under one lock, and reaches the fit rule, the bank, the messenger and the clock only through interfaces. A new fit rule or a new card provider is a new class, and EventWaitlist is not edited.

The finished design
This figure shows the classes from the class diagram without their fields. EventWaitlist uses three interfaces and a Clock, which is grey because it comes from java.time. Amber badges 1 to 9 match the rows of the table below: 1, 2, 5 and 8 on EventWaitlist, 3 on FitRule, 4, 6 and 7 on OfferStatus, and 9 on OfferNotifier. A purple tag marks FitRule as a Strategy.This figure shows the classes from the class diagram without their fields. EventWaitlist uses three interfaces and a Clock, which is grey because it comes from java.time. Amber badges 1 to 9 match the rows of the table below: 1, 2, 5 and 8 on EventWaitlist, 3 on FitRule, 4, 6 and 7 on OfferStatus, and 9 on OfferNotifier. A purple tag marks FitRule as a Strategy.
Each amber badge marks where one decision landed. The purple tag names the pattern. This figure shows the classes from the class diagram without their fields. EventWaitlist uses three interfaces and a Clock, which is grey because it comes from java.time. Amber badges 1 to 9 match the rows of the table below: 1, 2, 5 and 8 on EventWaitlist, 3 on FitRule, 4, 6 and 7 on OfferStatus, and 9 on OfferNotifier. A purple tag marks FitRule as a Strategy.
S.No.The questionWhat we choseWhy
1Should a ticket be an object?No. A tier has a count of free ticketsTickets in a tier are all the same.
2One entry per person, or one per tier?One entry per person for the whole eventOne lookup gives the duplicate check, the place and the limit.
3Who gets tickets when the first person wants more than came back?A FitRule interface, with SkipToFit as the defaultTickets keep moving, and the rule can change.
4What happens to someone who declines or lets an offer lapse?They leave the lineOne offer per entry keeps the line moving.
5Who ends an offer whose time is up?Every call lapses old offers first, and a job may sweep as wellNo call acts on a late offer.
6What happens to an offer when the card is declined?It stays open until its deadlineA mistyped card does not cost the tickets.
7Can an offer lapse while its payment is running?No. A claim that starts in time finishesNo refunds for late answers.
8Where does the lock go?One lock per eventA lapse changes four maps together.
9When is a person told about an offer?After the lock is releasedA slow message service never holds the lock.

Here is Dev's claim of O-5 from the demo, step by step:

  1. release("FLOOR", 2) takes the lock, adds 2 to the free count, and offerFreeTickets asks SkipToFit.pick, which returns Dev's entry. The offer O-5 goes into liveOffers, and after the lock is released sendQuietly tells Dev.
  2. claim("O-5", card) takes the lock in lockedGet, lapses any late offers, and requireOpen finds O-5 open. It becomes CLAIMING with charge key O-5/1, and the lock is released.
  3. PaymentGateway.charge is the outside call, made with no lock held. The bank does not answer and throws. voidQuietly voids O-5/1, then afterFailedCharge takes the lock and finds the deadline not yet passed, so O-5 is OPEN again.
  4. Dev claims again with key O-5/2. The charge is approved, and finishLocked marks O-5 CLAIMED, takes Dev out of line, and adds 2 to Dev's claimed count.

The other way out of an offer is shorter. Any call after the deadline runs lapseExpired under the lock. It ends each late OPEN offer, puts its tickets back, and only then asks the fit rule for the next person, as Chen's offer showed at 19:25.

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.

waitlistEventWaitlist.java
package waitlist; import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.OptionalInt;import java.util.function.Consumer;import java.util.function.Function;import java.util.logging.Level;import java.util.logging.Logger; import event.Event;import event.Tier;import exception.JoinRefusedException;import exception.OfferNotOpenException;import exception.PaymentFailedException;import fit.FitRule;import notify.OfferNotifier;import payment.PaymentGateway;import payment.PaymentResult; /** The waitlist of one sold-out event: who is waiting, which tickets are free, and every offer. */public class EventWaitlist {    private static final Logger LOG = Logger.getLogger(EventWaitlist.class.getName());     private final Map<String, Tier> tiers = new HashMap<>();    private final int maxPerPerson;    private final Duration offerWindow;    private final FitRule fitRule;    private final PaymentGateway gateway;    private final OfferNotifier notifier;    private final Clock clock;     // Everything below is guarded by lock.    private final Object lock = new Object();    private final Map<String, LinkedHashMap<String, Entry>> lines = new HashMap<>();    private final Map<String, Integer> freeTickets = new HashMap<>();    private final Map<String, Entry> entriesByPerson = new HashMap<>();    private final LinkedHashMap<String, Offer> liveOffers = new LinkedHashMap<>();    private final Map<String, String> liveOfferIdByPerson = new HashMap<>();    private final Map<String, OfferStatus> statuses = new HashMap<>();    private final Map<String, Integer> attempts = new HashMap<>();    private final Map<String, Integer> claimedByPerson = new HashMap<>();    private final List<String> chargesToVoid = new ArrayList<>();    private final List<Offer> offersToSend = new ArrayList<>();    private long nextOfferNumber = 1;     private record Attempt(Offer offer, String chargeKey) {    }     public EventWaitlist(Event event, int maxPerPerson, Duration offerWindow, FitRule fitRule,            PaymentGateway gateway, OfferNotifier notifier, Clock clock) {        Objects.requireNonNull(event, "event");        if (maxPerPerson < 1) {            throw new IllegalArgumentException("each person must be allowed at least one ticket");        }        if (offerWindow.isNegative() || offerWindow.isZero()) {            throw new IllegalArgumentException("an offer needs time to be claimed");        }        this.maxPerPerson = maxPerPerson;        this.offerWindow = offerWindow;        this.fitRule = Objects.requireNonNull(fitRule, "fitRule");        this.gateway = Objects.requireNonNull(gateway, "gateway");        this.notifier = Objects.requireNonNull(notifier, "notifier");        this.clock = Objects.requireNonNull(clock, "clock");        for (Tier tier : event.tiers()) {            if (tier.priceCents() > Long.MAX_VALUE / maxPerPerson) {                throw new IllegalArgumentException(tier.id() + " costs too much for " + maxPerPerson + " tickets");            }            tiers.put(tier.id(), tier);            lines.put(tier.id(), new LinkedHashMap<>());            freeTickets.put(tier.id(), 0);        }    }     public Entry join(String personId, String tierId, int quantity) {        Objects.requireNonNull(personId, "personId");        Objects.requireNonNull(tierId, "tierId");        if (quantity < 1) {            throw new IllegalArgumentException("quantity must be at least 1");        }        return lockedGet(now -> {            if (!tiers.containsKey(tierId)) {                throw new JoinRefusedException("there is no tier " + tierId);            }            if (entriesByPerson.containsKey(personId)) {                throw new JoinRefusedException(personId + " is already waiting");            }            int allowed = maxPerPerson - claimedByPerson.getOrDefault(personId, 0);            if (allowed == 0) {                throw new JoinRefusedException(personId + " has already claimed " + maxPerPerson + " tickets");            }            if (quantity > allowed) {                throw new JoinRefusedException(personId + " can ask for at most " + allowed + " tickets");            }            Entry entry = new Entry(personId, tierId, quantity, now);            lines.get(tierId).put(personId, entry);            entriesByPerson.put(personId, entry);            offerFreeTickets(tierId, now);            return entry;        });    }     /** Takes a person out of line. An open offer is declined and its tickets go to the next person. */    public boolean leave(String personId) {        Objects.requireNonNull(personId, "personId");        return lockedGet(now -> {            Entry entry = entriesByPerson.get(personId);            if (entry == null) {                return false;            }            String offerId = liveOfferIdByPerson.get(personId);            if (offerId != null) {                requireOpen(offerId);                endOffer(liveOffers.get(offerId), OfferStatus.DECLINED);            } else {                removeFromLine(entry);            }            offerFreeTickets(entry.tierId(), now);            return true;        });    }     /** Tickets come back to a tier: a cancellation, or the organiser releasing more. */    public void release(String tierId, int count) {        Objects.requireNonNull(tierId, "tierId");        if (count < 1) {            throw new IllegalArgumentException("release at least one ticket");        }        locked(now -> {            Integer free = freeTickets.get(tierId);            if (free == null) {                throw new IllegalArgumentException("there is no tier " + tierId);            }            // Free and held tickets can all come back to the free count, so all of them must fit.            Math.addExact(Math.addExact(free, heldIn(tierId)), count);            freeTickets.put(tierId, free + count);            offerFreeTickets(tierId, now);        });    }     /** Ends every open offer whose time is up. Every other public method does this first as well. */    public void expireOffers() {        // locked() lapses old offers before every action, so this action has nothing left to do.        locked(now -> {        });    }     public void decline(String offerId) {        Objects.requireNonNull(offerId, "offerId");        locked(now -> {            Offer offer = requireOpen(offerId);            endOffer(offer, OfferStatus.DECLINED);            offerFreeTickets(offer.tierId(), now);        });    }     public Claim claim(String offerId, String card) {        Objects.requireNonNull(offerId, "offerId");        Objects.requireNonNull(card, "card");        Attempt attempt = lockedGet(now -> {            Offer open = requireOpen(offerId);            statuses.put(offerId, OfferStatus.CLAIMING);            int number = attempts.merge(offerId, 1, Integer::sum);            return new Attempt(open, offerId + "/" + number);        });        Offer offer = attempt.offer();        String chargeKey = attempt.chargeKey();         PaymentResult result;        try {            result = Objects.requireNonNull(gateway.charge(chargeKey, offer.amountCents(), card), "no result");        } catch (RuntimeException e) {            voidQuietly(chargeKey);            try {                afterFailedCharge(offer);            } catch (RuntimeException alsoFailed) {                e.addSuppressed(alsoFailed);            }            throw e;        }        if (!result.approved()) {            afterFailedCharge(offer);            throw new PaymentFailedException("the card was declined for " + offerId);        }         finishLocked(now -> {            statuses.put(offerId, OfferStatus.CLAIMED);            liveOffers.remove(offerId);            liveOfferIdByPerson.remove(offer.personId());            removeFromLine(entriesByPerson.get(offer.personId()));            claimedByPerson.merge(offer.personId(), offer.quantity(), Integer::sum);        });        return new Claim(offerId, offer.personId(), offer.tierId(), offer.quantity(), offer.amountCents(),                result.reference());    }     /** 1 for the first person in their tier's line, counting everyone ahead, with or without an offer. */    public OptionalInt positionOf(String personId) {        Objects.requireNonNull(personId, "personId");        return lockedGet(now -> {            Entry entry = entriesByPerson.get(personId);            if (entry == null) {                return OptionalInt.empty();            }            int position = 1;            for (String waiting : lines.get(entry.tierId()).keySet()) {                if (waiting.equals(personId)) {                    break;                }                position++;            }            return OptionalInt.of(position);        });    }     public Optional<Offer> liveOfferFor(String personId) {        return lockedGet(now -> Optional.ofNullable(liveOfferIdByPerson.get(personId)).map(liveOffers::get));    }     public Optional<OfferStatus> statusOf(String offerId) {        return lockedGet(now -> Optional.ofNullable(statuses.get(offerId)));    }     public int freeTickets(String tierId) {        return lockedGet(now -> freeTickets.getOrDefault(tierId, 0));    }     public List<String> chargesToVoid() {        synchronized (lock) {            return List.copyOf(chargesToVoid);        }    }     /** For a job to call: sends again every void the gateway failed to take. */    public void retryVoids() {        List<String> keys;        synchronized (lock) {            keys = new ArrayList<>(chargesToVoid);            chargesToVoid.clear();        }        for (String key : keys) {            voidQuietly(key);        }    }     // ---- under the lock     private void lapseExpired(Instant now) {        List<Offer> lapsed = new ArrayList<>();        for (Offer offer : liveOffers.values()) {            if (statuses.get(offer.id()) == OfferStatus.OPEN && !now.isBefore(offer.expiresAt())) {                lapsed.add(offer);            }        }        for (Offer offer : lapsed) {            endOffer(offer, OfferStatus.LAPSED);        }        // All lapsed tickets are back before anyone is offered them, so one sweep gives one answer.        for (String tierId : lapsed.stream().map(Offer::tierId).distinct().toList()) {            offerFreeTickets(tierId, now);        }    }     private void offerFreeTickets(String tierId, Instant now) {        int free = freeTickets.get(tierId);        while (free > 0) {            List<Entry> waiting = lines.get(tierId).values().stream()                    .filter(entry -> !liveOfferIdByPerson.containsKey(entry.personId()))                    .toList();            Optional<Entry> picked = fitRule.pick(waiting, free);            if (picked.isEmpty()) {                return;            }            Entry entry = picked.get();            if (!waiting.contains(entry) || entry.quantity() > free) {                throw new IllegalStateException("the fit rule picked " + entry + " with " + free + " free");            }            long amountCents = Math.multiplyExact(tiers.get(tierId).priceCents(), entry.quantity());            Offer offer = new Offer("O-" + nextOfferNumber++, entry.personId(), tierId, entry.quantity(),                    amountCents, now.plus(offerWindow));            free -= entry.quantity();            freeTickets.put(tierId, free);            liveOffers.put(offer.id(), offer);            liveOfferIdByPerson.put(entry.personId(), offer.id());            statuses.put(offer.id(), OfferStatus.OPEN);            offersToSend.add(offer);        }    }     private void endOffer(Offer offer, OfferStatus ending) {        statuses.put(offer.id(), ending);        liveOffers.remove(offer.id());        liveOfferIdByPerson.remove(offer.personId());        removeFromLine(entriesByPerson.get(offer.personId()));        freeTickets.merge(offer.tierId(), offer.quantity(), Integer::sum);    }     private int heldIn(String tierId) {        int held = 0;        for (Offer offer : liveOffers.values()) {            if (offer.tierId().equals(tierId)) {                held += offer.quantity();            }        }        return held;    }     private void removeFromLine(Entry entry) {        entriesByPerson.remove(entry.personId());        lines.get(entry.tierId()).remove(entry.personId());    }     private Offer requireOpen(String offerId) {        OfferStatus status = statuses.get(offerId);        if (status == null) {            throw new OfferNotOpenException("there is no offer " + offerId);        }        if (status != OfferStatus.OPEN) {            throw new OfferNotOpenException(offerId + " is " + status.name().toLowerCase());        }        return liveOffers.get(offerId);    }     // ---- the lock, and the calls made after it is released     private void afterFailedCharge(Offer offer) {        finishLocked(now -> {            if (now.isBefore(offer.expiresAt())) {                statuses.put(offer.id(), OfferStatus.OPEN);            } else {                endOffer(offer, OfferStatus.LAPSED);                offerFreeTickets(offer.tierId(), now);            }        });    }     private void locked(Consumer<Instant> action) {        lockedGet(now -> {            action.accept(now);            return null;        });    }     private <T> T lockedGet(Function<Instant, T> action) {        return underLock(true, action);    }     /** For the last step of a claim: nothing else runs first, so nothing else can stop it. */    private void finishLocked(Consumer<Instant> action) {        underLock(false, now -> {            action.accept(now);            return null;        });    }     /** Lapses old offers if asked, runs the action, then sends the new offers once the lock is released. */    private <T> T underLock(boolean lapseFirst, Function<Instant, T> action) {        List<Offer> made = List.of();        try {            synchronized (lock) {                try {                    Instant now = clock.instant();                    if (lapseFirst) {                        lapseExpired(now);                    }                    return action.apply(now);                } finally {                    made = List.copyOf(offersToSend);                    offersToSend.clear();                }            }        } finally {            sendQuietly(made);        }    }     private void sendQuietly(List<Offer> made) {        for (Offer offer : made) {            try {                notifier.offerMade(offer);            } catch (RuntimeException e) {                LOG.log(Level.WARNING, "could not tell " + offer.personId() + " about " + offer.id(), e);            }        }    }     private void voidQuietly(String chargeKey) {        try {            gateway.voidCharge(chargeKey);        } catch (RuntimeException e) {            synchronized (lock) {                chargesToVoid.add(chargeKey);            }        }    }}
Click a class name in the code to open its fileJava · 404 lines · 990 in the project

demo/Main.java runs one evening of a sold-out show with SkipToFit. Five people join, two joins are refused, and one person leaves. Then tickets come back in small numbers, and the offers end every way an offer can end:

$ java demo.Main
19:00  Nightfall Live is sold out. GA $85.00, FLOOR $120.00, up to 4 tickets each
19:00  asha 4, ben 2, chen 1 and gia 1 wait for GA. dev 2 waits for FLOOR
19:00  asha asks for 2 FLOOR: refused, asha is already waiting
19:00  eli asks for 6 GA: refused, eli can ask for at most 4 tickets
19:02  gia leaves the line
19:02  places in GA: asha 1, ben 2, chen 3
19:05  2 GA tickets come back
   -> O-1 to ben: 2 tickets, $170.00, claim by 19:20
19:08  ben pays for O-1 with a card that is declined
19:08  claim refused: the card was declined for O-1
19:08  O-1 is OPEN until 19:20
19:09  ben pays again
19:09  ben claimed 2 GA tickets for $170.00, payment PAY-1
19:10  3 GA tickets come back
   -> O-2 to chen: 1 ticket, $85.00, claim by 19:25
19:10  GA tickets waiting for someone who fits: 2
19:25  chen has not paid
19:25  O-2 is LAPSED. GA tickets free: 3
19:25  claim refused: O-2 is lapsed
19:30  fay joins GA for 2
   -> O-3 to fay: 2 tickets, $170.00, claim by 19:45
19:32  fay declines O-3
19:33  1 GA ticket comes back
   -> O-4 to asha: 4 tickets, $340.00, claim by 19:48
19:35  2 FLOOR tickets come back
   -> O-5 to dev: 2 tickets, $240.00, claim by 19:50
19:36  dev pays for O-5, and the bank does not answer
19:36  claim failed: the bank did not answer in time
19:36  O-5 is OPEN. Voided charges: [O-5/1]
19:37  dev pays again
19:37  dev claimed 2 FLOOR tickets for $240.00, payment PAY-2
19:37  asha is place 1 in GA, holding O-4

Notice three things in the output. At 19:10, three tickets came back and Asha wanted 4, so Chen got one and two waited. At 19:30, Fay joined after Asha and was offered tickets at once, because SkipToFit passes over anyone the free tickets do not fit, and Asha stayed at place 1. And when Dev's bank did not answer, O-5 stayed OPEN, the charge O-5/1 was voided, and Dev's second try went through.

Follow-up questions

The interviewer asksWhat changesWhat does not
"Let people accept fewer tickets than they asked for."Entry gains a smallest acceptable quantity. A new FitRule that returns the person and a quantity, so pick changes its return type, and offerFreeTickets uses that quantity.The lock, claiming, payment.
"Close the waitlist when the doors open."Event gains a start time. join and release refuse after it, and a last sweep lapses every open offer.Fit rules, payment.
"Let a fan wait in two tiers."entriesByPerson maps a person to a list. The limit counts open offers too, and claim checks it again.Fit rules, the notifier.
"Presale members go first."Entry gains a priority, and a new FitRule sorts by it before applying a fit.EventWaitlist's flows.
"Tell people when they move up."OfferNotifier gains a second method, sent from underLock the same way offers are.The line, fit rules, payment.
"Run this on many servers."The maps move to a database. OPEN to CLAIMING becomes a conditional update on the offer's row, and the sweep becomes a job.The fit rules, the gateway's contract, the flows.
"The fans pick seats."Each offer holds seats through BookMyShow's holds instead of a count.Who goes next, deadlines, the claim steps.
"Stop bots joining with many accounts."A check before join, such as a verified phone number, and a limit per card at claim.Everything inside the waitlist.

In most rows the change lands in a rule, a record field or a new class. When you answer a follow-up, say which classes change and which do not, and say when a method's signature changes, as it does for partial offers.

What the interviewer looks for

Mid-level

A mid-level candidate shows a line per tier, an offer with a deadline, and a claim that charges a card. They refuse duplicate entries and requests over the limit. They mention that returns and claims can happen at once, even if the lock is in a less than ideal place.

Senior

A senior candidate shows everything above and gives the reasons. They name the partial-fit question themselves, put the answer behind an interface, and say what each rule costs. They walk through what happens on a declined card and when the deadline passes during a payment. They keep the bank and the messages outside the lock, and they pass in a clock.

Staff+

A staff candidate leads with the invariant: every returned ticket is free, held or claimed, exactly once. They test the design against a claim, a sweep and a return at the same instant. They raise the charge whose outcome is unknown, and they say how the design moves to a database without losing the one-step move from OPEN to CLAIMING.

Common mistakes

  • Popping the first person off a queue. A queue's poll only takes the head, so it cannot skip someone who does not fit and keep their place.
  • A ticket object with a status. General admission tickets are identical. A count per tier is one number to keep right instead of many.
  • Checking the deadline, then calling the bank, with nothing in between. A sweep can hand the same tickets to the next person while the charge runs.
  • Calling the bank or the text service under the lock. One slow card stops every return and every claim.
  • Ending the offer on a declined card. A typing mistake costs a fan their tickets.
  • Leaving a person in line after they let an offer lapse. The rule picks them again, and the line stops moving.
  • Instant.now() inside the waitlist. Deadlines become impossible to test.

Summary

  • Ask about partial fits first. The answer is a fairness rule, and it will change, so it goes behind FitRule.
  • Keep tickets as a count per tier. Seats belong to BookMyShow's design.
  • An offer holds tickets for a fixed time and ends in a claim, a decline or a lapse. Declined and lapsed tickets go straight to the next person.
  • Every call lapses late offers first, and a timer sweeps as well.
  • A claim marks the offer CLAIMING under the lock, calls the bank with no lock, then finishes under the lock. The sweep skips CLAIMING offers.
  • A declined card reopens the offer until its deadline. A charge that throws is voided by its key.
  • One lock per event, held only for map work. Messages go out after it is released.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.