1. Functional requirements
- Search lots near a destination for a time window, with availability and price.
- Reserve a spot for that window and pay.
- Enter and exit through a gate and get charged.
Assumption: capacity is reserved at the lot, not a numbered spot.
Below the line: operators, cancellations, event pricing, walk-ins, spot types.
Scale: 2M reservations a day, about 25/s; searches ~10x that; peaks of 20K cars on a dozen lots in two hours. Throughput is small. The design is driven by contention on one lot’s popular windows, and gates that must work offline.
2. Non-functional requirements
- Consistency for reservations: no overselling a window
- Gate opens in under 1 s, online or offline
- Availability for search: fresh within seconds, under 500 ms
- Exactly-once billing: no double charge on retries or late exits
3. Core entities
- Drivers
- Vehicles
- Lots
- Rate plans
- Reservations: reserved → active → completed | cancelled | no_show
- Gate events
- Payments
4. API routes
Auth is a header on all three. Simple enough to start; the offline gate evolves the third one.
Search
GET /lots/search
params: lat, lng, radius, start, end
returns: Lot[] with free spots and price
Reserve
POST /reservations Idempotency-Key header
body: lotId, vehicleId, start, end, paymentMethodId
returns: reservationId, qrToken
Gate event
POST /lots/:lotId/gates/:gateId/events device auth, eventId dedupes
body: type entry | exit, plate | qrToken, at
returns: open | deny
5. High-level design
The simplest system that satisfies the three routes. Two clients, one gateway, three services, one database. The deep dives change this picture.
Boxes, drawing order: driver app and gate controller · gateway · lot service, reservation service, gate service · Postgres · Stripe beside reservations.
Data model:
Lot id, lat, lng, capacity
RatePlan lotId, hourly, daily, monthly
Reservation id, driverId, vehicleId, lotId, start, end, status, qrToken
GateEvent eventId, lotId, type, plate, at
Payment id, reservationId, type: window | overstay, amount
Postgres, one primary: transactions for capacity and money, unique constraints for the idempotency key and eventId, range query on the window. Throughput is 25 writes/s, so nothing else is needed yet.
6. Deep dives
Order in the room: 6.1 must · 6.2 if time · 6.3, 6.4, 6.5 one line each, only if asked. Each deep dive opens with three spoken sentences: Problem, Pick, Cost. Everything under them is what you say when the interviewer digs.
6.1 No overselling: slot counters
Problem. Reserve is read-then-write: two drivers taking the last spot both count capacity − 1 and both insert.
Pick. A capacity counter per lot per 30-minute slot; reserve is one conditional update across the window’s slot rows, reserved + 1 where reserved < capacity, rollback and 409 if any row misses.
Cost. 30-minute granularity and a per-lot serialization point, ~1 ms per row, fine at 25 writes/s. Rejected: numbered spots and a seat map, because drivers do not care which spot.
Draw: a SlotInventory table beside Reservations.
Flow
SlotInventory (lotId, slotStart) → capacity, reserved, rows created lazily fromLot.capacity.- One transaction:
UPDATE slot_inventory SET reserved = reserved + 1 WHERE lot_id = ? AND slot_start IN (…) AND reserved < capacity. Rows updated ≠ slots in the window → rollback and 409; else insert the reservation asreservedand commit. - The rows are locked only for the transaction (~1 ms), so concurrent reserves on one lot serialize there and the second sees the first’s count.
Follow up: the app times out after the commit and retries. Does the driver get two reservations?
Answer: No. The Idempotency-Key is a unique column on the reservation, written in the same transaction as the slot update; a retry hits the unique index and the service returns the existing reservationId and qrToken. The window charge uses the reservationId as the Stripe idempotency key, so a replay returns the same charge. Keys are kept 24 hours.
6.2 Gate under 1 s, offline: the controller decides locally
Problem. Opening needs a round trip and a database lookup, so a lot with no connectivity opens for nobody, and the round trip is not reliably under 1 s. Pick. The controller holds its lot’s reservations for the next 6 hours from a versioned sync every 60 s, matches the plate or QR locally in < 100 ms, and queues entry and exit events that drain when connected, deduped by eventId. Cost. A list up to 60 s stale, and walk-in capacity is approximate offline. Rejected: server validation at the gate.
Draw: the controller gets a local list and a queue; the gate route widens into a sync pull and a batch event upload.
Routes (evolve the gate route from section 4):
GET /lots/:lotId/gate-sync?since={version} → { version, reservations: [ { plate, qrToken, start, end } ] }
POST /lots/:lotId/gate-events [ { eventId, type: entry | exit, plate, at } ] → ack
Flow
- Sync: the gate service bumps a per-lot version on every reservation change; the controller pulls the delta every 60 s and on reconnect, and keeps reservations overlapping the next 6 hours.
- Decide: a list entry whose window covers now opens the gate in < 100 ms; exit always opens; both append an event to the local queue. No match and online → one call to the gate service; offline → the operator’s walk-in policy.
- Drain: the queue posts events in order whenever connected;
eventIdis unique inGateEvent, so a re-sent batch is a no-op. The gate service flipsreserved → activeon entry,active → completedon exit, and settles the stay (6.5).
Follow up: a driver with no reservation pulls up to the gate. What happens?
Answer: A walk-in is a reservation created at the gate. Online, the gate service runs the 6.1 conditional update for the next hour and answers open or full; the stay is charged at the hourly rate on exit. Offline, the operator’s policy applies: fail closed, or fail open while the controller’s own count of cars inside is below capacity. The queued walk-in entry creates the reservation when it drains.
6.3 Fresh availability in search
Problem. Search counts overlapping reservations per lot on every query, and only knows reservations, not cars. Pick. A Redis availability hash per lot, fed by reservation and gate events through Kafka, read by search with GEOSEARCH for the radius. Cost. About a second stale. Search is a hint and 6.1 is the check, so a stale number costs a 409, never an oversell.
6.4 Stadium peaks
Problem. 20K cars on a dozen lots in two hours: searches on those lots spike 100x and reservation attempts pile onto the same slot rows after sell-out. Pick. Searches from Redis and a CDN; reserves fast-rejected from the availability hash before Postgres; Kafka partitioned by lotId absorbs the exit burst. Cost. A sold-out lot can show one free spot for a second; the conditional update still decides.
6.5 Exactly-once billing
Problem. Charging inside the exit request double-charges on a gate retry, and after 6.2 the exit is an event that may arrive hours late. Pick. Every charge is a Payment row written in the same transaction as the state change it belongs to; a billing worker settles it with the paymentId as the Stripe idempotency key. Cost. Settlement lands after exit, plus a worker and a nightly reconciliation that alerts, never auto-refunds.
Final design
Trade-offs, the two to say:
- Slot counters over per-spot assignment: one conditional update instead of a seat map, at the cost of 30-minute granularity.
- Gate decides locally over server validation: opens in under a second without connectivity, at the cost of a list up to 60 s stale.
Study only, not for the room: full flows and the follow-up for 6.3, 6.4 and 6.5.
6.3 flow
- Search:
GEOSEARCH lots:geo(GEO set of all lots) within the radius →HMGET avail:{lotId}(hashslotStart → free) for the window’s slots → free = min over the slots, andcapacity − occupied:{lotId}for a window starting now →Lot[]. - Updates: the reservation and gate services publish
reservation.created | cancelledandgate.entry | exitto Kafkalot-eventsthrough an outbox table. The availability updater appliesHINCRBY avail:{lotId} slot ±1andINCR | DECR occupied:{lotId}, about 1 s behind. - Drift: a reconciler rebuilds
avail:{lotId}fromSlotInventoryevery 5 minutes and resetsoccupied:{lotId}nightly.
6.4 flow
- Reads: search is Redis-only (6.3); lot pages go through a CDN with a 5-minute TTL; the gateway rate limits per driver.
- Writes: the reservation service reads
avail:{lotId}for the window before opening a transaction; any slot at 0 → 409. The rest take the conditional update, ~1 ms per row, so one lot sustains ~1K reserves/s on one Postgres primary. - Gates: the controller opens locally and batches events (6.2); Kafka
lot-events, partitioned bylotId, absorbs the exit burst and the consumers drain at their own pace.
6.5 flow and follow-up
- Reserve writes the window charge as a
Paymentpendingin the 6.1 transaction; exit (deduped byeventId) writes the overstay charge in the transaction that flipsactive → completed. - The billing worker consumes
payment.pendingfrom Kafkapayments(outbox) and calls Stripe withIdempotency-Key: paymentId. Stripe keeps the key 24 h, so a replay returns the same charge, never a second one. - Result:
capturedfrom the sync response or the webhook, whichever lands first;failedat reserve releases the slots,failedat exit retries with backoff. A nightly reconciliation against Stripe’s charges alerts on any mismatch, never auto-refunds.
Follow up: a car never exits: the camera misreads the plate or the car tailgates out. When does the stay close, and what is charged?
Answer: A sweeper closes any reservation still active two hours past its end as completed with no exitedAt. It charges nothing beyond the window: with no exit event there is no evidence of overstay, and a wrong charge costs more than a lost one. An unmatched plate is compared fuzzily against the active stays at that lot (O/0, I/1) before it counts as unknown. A new entry for a plate whose stay is still active closes the old stay first. The operator can review the camera log and bill a real overstay by hand.