Multi-Level Parking Facility: Allocation, Ticketing, and Payments
System DesignModel answerLast updated
Design a multi-level parking facility with typed spots, entry/exit gates, ticketing, pricing, and availability — covering concurrency, consistency, and failure handling.
You are asked to design the software behind a parking facility (or a chain of them). The facility has several floors, each with many bays, and several drive-in and drive-out gates.
Requirements to cover:
- Several vehicle classes and bay sizes, with a fit rule between them.
- A ticket is created on arrival, a price is computed on departure, payment is collected, and the barrier opens.
- Prices follow a rate card: an hourly rate per vehicle class plus a per-day maximum, and stays can span many days.
- Live counts of free bays, per floor and per vehicle class, feed signage and a mobile app.
- Define the main objects, their relationships, and the endpoint shapes for arriving, leaving, paying, and checking availability.
- Explain how you prevent one bay being handed to two cars, how ticket and payment state stays consistent, and what happens with duplicate requests, a misplaced ticket, a network partition at a gate, and a completely full facility.
State your assumptions about size and traffic explicitly. Expect follow-up questions on failure modes, monitoring, and how you would roll this out.
Hints
Hint 1
Start by pinning down the fit rule and the fact that per-facility write rates are tiny — correctness, not throughput, is the real problem, which then justifies partitioning state by facility.
Hint 2
For double-allocation, a conditional UPDATE ... WHERE status='FREE' or SELECT ... FOR UPDATE SKIP LOCKED is enough at these volumes; don't reach for a distributed lock unless you can explain why.
Hint 3
Make payments idempotent with a unique key, model paid_until as a short grace window, and decide explicitly whether an offline gate lets cars out unpaid.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is two problems stapled together: a clean object model, and a distributed-consistency problem hiding behind a slow, low-volume workload. A strong answer spends maybe 20% on classes and APIs, then most of the time on allocation races, the ticket/payment state machine, and degraded-mode behavior.
1. Requirements and scale (say these out loud)
Functional. Vehicle classes: motorcycle, car, truck. Bay sizes: small, compact, large. Fit rule: a motorcycle fits anything, a car fits compact or large, a truck fits large only. Multiple floors, multiple gates. Arrival issues a ticket; departure computes a fee, takes payment, opens the barrier. Free-bay counts per floor and per class drive signage and the app. Pricing: hourly rate per class, rounded up per started hour, plus a daily cap, with multi-day stays.
Non-functional.
- A bay must never be assigned twice — strong consistency inside one facility.
- Gates must keep serving cars when the network to the cloud is degraded; a stuck barrier is a visible outage.
- Payments look exactly-once to the user.
- Signage/app counts may lag a few seconds.
Scale. One facility: 10 floors × 500 bays = 5,000 bays, ~10 gates. Peak arrival rate ≈ one car per 5 s per gate ≈ 2 writes/s per facility. A chain of 1,000 facilities: 5M bays, roughly 2–5K writes/s at peak, more availability reads. The important observation: writes are trivial. This is a correctness problem, so partition all state by facility_id — each facility's bays, tickets, and payments live in one shard/leader, and strong consistency becomes cheap. Don't shard within a facility.
2. Object model
class VehicleClass(Enum): MOTORCYCLE, CAR, TRUCK
class BaySize(Enum): SMALL, COMPACT, LARGE
class BayState(Enum): FREE, HELD, OCCUPIED, OUT_OF_SERVICE
class TicketState(Enum): OPEN, SETTLED, CLOSED, MISSING
class Vehicle: plate: str; cls: VehicleClass
class Bay: id; floor_id; size: BaySize; state: BayState; ticket_id: str | None
class Floor: id; bays: list[Bay]
class Facility: id; floors; gates; rate_card: RateCard
class Ticket: id; facility_id; plate; cls; bay_id; entered_at;
rate_card_version; state; paid_until: datetime | None
class Payment: id; ticket_id; amount; state; idem_key; provider_ref
class Gate: id; facility_id; kind # IN / OUT; local controller process
class BayChooser: def pick(self, facility, cls) -> Bay | None: ...
class Pricer: def quote(self, cls, start, end, rate_card) -> Money: ...
Relationships: a Facility owns Floors, which own Bays. A Ticket points at exactly one bay and has zero or more Payments. BayChooser and Pricer are injected strategies so allocation policy and pricing change independently of the core.
Pricing. Example card: cars $4/started hour, $30 daily cap. For a stay of d full days plus h leftover hours: fee = d*30 + min(ceil(h)*4, 30). Keep the card versioned in a rate_cards table; store rate_card_version on the ticket so a mid-stay price change never alters the quoted amount.
3. APIs
POST /facilities/{fid}/entries {plate, cls, gateId, idemKey}
-> 201 {ticketId, bayId, floor, enteredAt}
-> 409 FACILITY_FULL
GET /tickets/{tid}/quote -> {amount, quotedAt, validUntil}
POST /tickets/{tid}/payments {amount, method, idemKey}
-> {paymentId, state, paidUntil}
POST /facilities/{fid}/exits {ticketId | plate, gateId}
-> {allowed, amountDue}
POST /tickets/recover {facilityId, plate} -> {ticketId, amountDue}
GET /facilities/{fid}/availability?cls=CAR
-> {total, free, byFloor:[{floor, free}]}
Every mutating call carries an idempotency key: gates retry on timeout, so retries must be no-ops, not second charges or second tickets.
4. Architecture
- Gate controller — on-premise process per gate: barrier, printer, plate camera. Keeps a local append-only journal for offline operation.
- Facility service — stateless, routed by
facility_id; handles entries, exits, allocation. - Primary store — relational (Postgres/Aurora) sharded by
facility_id:bays,tickets,payments,rate_cards. Transactions and conditional updates are exactly the primitives we need; no fancy coordination service. - Payment service — wraps the external provider, uses a transactional outbox plus reconciliation.
- Availability service — consumes bay-change events (CDC → Kafka), keeps Redis counters keyed by
(facility, floor, size); serves signage and app. Eventually consistent by design. - Analytics/notifications — async consumers of the same event stream.
5. Deep dives
No double allocation. Two gates can race for the same free bay. The one I'd defend: conditional update in a transaction — UPDATE bays SET state='OCCUPIED', ticket_id=:t WHERE id=:s AND state='FREE'; if zero rows change, try the next candidate. Or SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1 over free bays of the fitting sizes. At 2 writes/s per facility either is fine; a Redis/Distributed lock buys nothing and adds a failure mode. The chooser tries the smallest fitting size first, then larger, so cars don't squat in truck bays while compact bays sit empty.
Consistency between bays, tickets, availability. The database is truth; bay flip and ticket insert are one transaction. Counters are derived and may lag — but the entry decision never reads a counter, only the transactional allocation. A periodic job recomputes counters from the DB and alerts on drift.
Ticket/payment state machine. OPEN → SETTLED → CLOSED, with OPEN → MISSING → SETTLED for a lost ticket. Payment sets paid_until = now + 15 min as grace; the exit gate admits if SETTLED and now <= paid_until, otherwise charges the difference. Idempotency keys are unique-constrained. On provider timeout, mark the payment PENDING and resolve via status query or webhook — never re-charge blindly.
Lost ticket. Given plate and facility, find open tickets for that plate. Exactly one → use it. Several (re-entry) → charge the oldest. None → flat lost-ticket penalty capped at a sane amount, or the max daily rate; then mark MISSING, settle, allow exit. Track repeat plates to curb abuse.
Full facility. Allocation fails → 409 FACILITY_FULL; the gate shows "FULL" and issues nothing. Optional reservations: a bay goes FREE → HELD, the entry gate validates plate or QR, then HELD → OCCUPIED; holds expire after a grace period and are released by a sweeper.
Gate offline. Controller journals entries/exits locally (SQLite) and prints tickets with local sequence numbers; on reconnect it replays the journal and the facility service reconciles. Exits offline are the hard call: block (bad UX, cars trapped) vs. let out and reconcile later (some non-payment). I'd let cars out, record the debt against the plate, and bill or flag on next visit — and say so explicitly rather than hand-wave.
Pricing edge cases. Multi-day stays apply the cap per 24-hour period; rate changes use the ticket's stored card version; overstay past paid_until charges the delta at exit.
6. Failures and monitoring
Double allocation → conditional-update no-op plus a unique constraint on active (bay_id). Provider down → outbox with exponential backoff, exit allowed with recorded debt. Counter drift → recompute + alert. Gate hardware failure → heartbeat detection, dispatch, reroute to other gates.
Metrics: entry/exit latency p50/p99, error rate per gate, allocation conflict retries, payment PENDING age, counter-vs-DB drift, offline-journal backlog. Roll out facility by facility behind a flag, canary one site, keep the old process readable for manual override.