Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Ticket system
Ids, indexes and single use
The point: a ticket is a key to a departure and may be used once. remove returns it to exactly one caller. get followed by remove does not.
Structure
Three lookups, all O(1)
| Question | Index | Asked by |
|---|---|---|
| Which ticket is this? | id to ticket | Exit gate |
| Is this plate inside? | plate to id | Entry gate, help desk |
| Who is in L1? | space to ticket, if needed | Towing, cleaning |
Java
final class TicketService { private final ConcurrentHashMap<Long, Ticket> active = new ConcurrentHashMap<>(); private final AtomicLong ids = new AtomicLong(1); Ticket issue(Vehicle vehicle, Spot spot, Instant now) { Ticket ticket = new Ticket(ids.getAndIncrement(), vehicle, spot, now); active.put(ticket.id(), ticket); return ticket; } /** The exit that gets the ticket owns the departure. Everyone else gets empty. */ Optional<Ticket> takeForExit(long id) { return Optional.ofNullable(active.remove(id)); } int inside() { return active.size(); } // fine for a sign, not for a decision}ConcurrentHashMap and AtomicLong are safe one by one, without a lock of yours. takeForExit is one call, so two exit gates with a copied ticket cannot both win.Python
import secretsfrom dataclasses import dataclass, field@dataclassclass TicketIndex: """Three ways in, one truth. Change them together, under the lot's lock.""" by_id: dict[str, str] = field(default_factory=dict) # id -> plate by_plate: dict[str, str] = field(default_factory=dict) # plate -> id def issue(self, plate: str) -> str | None: if plate in self.by_plate: return None ticket_id = secrets.token_urlsafe(12) # 96 random bits: nobody guesses it self.by_id[ticket_id] = plate self.by_plate[plate] = ticket_id return ticket_id def take(self, ticket_id: str) -> str | None: plate = self.by_id.pop(ticket_id, None) # pop, never get and then delete if plate is not None: del self.by_plate[plate] return plateindex = TicketIndex()first = index.issue("RED-1")print(index.issue("RED-1"), len(first))print(index.take(first), index.take(first))Ids
What goes on the paper
How do you make ticket ids?
BreaksPlate plus time
- How
ABC-123-20260704- Limit
- Twice on one day collides. It prints personal data on paper. Anybody can make one.
- Choose when
- Never.
WorksA counter
- How
AtomicLong, 1, 2, 3.- Limit
- Easy to guess: the paper says 41, so 40 exists. Starts again after a restart. Two machines give the same number.
- Choose when
- Inside one process, with the number as an internal name only.
StrongRandom, or a counter with a signature
- How
- 96 random bits in the barcode, or
41.plus a short keyed signature that the gate checks. - Limit
- Longer than a person can read aloud: print a short number beside it for the desk.
- Choose when
- Whenever the paper opens a barrier.
Fields
What a ticket holds, and what it does not
| Field | On the ticket? | Reason |
|---|---|---|
| id, vehicle, space, entry time | Yes, unchanging | Facts of the entry |
| Exit time, amount | No, on the receipt | Not known yet. A half-filled record invites mistakes |
| Paid flag | No, in the session | It changes, so it needs a lock or a status change |
| Price per hour | Perhaps: the id of the tariff | If the price changes at noon, people who came before pay the old one |
| Entry time from the gate's own clock | No | Two gates disagree. One injected clock |
Failure walk
Trouble with paper
| What happens | What the system does |
|---|---|
| Copied ticket at two exits | One remove wins. The other: unknown ticket, call help |
| Printer jams after the claim | Print again: same id, same space. Or give the space back if the car turns round |
| The gate loses the answer | It asks again by plate and gets the same ticket, not a second space |
| Restart | Load active tickets from storage, then rebuild the free queues from them |
| A ticket from last month | Not active: refuse. Keep used ids, so the desk can say when it was used |