Track free spaces in many lots, guide drivers to a spot, and never sell the same space twice.
“Design a scalable smart parking system. Drivers should see which lots have free spaces near them, be able to reserve one, and pay when they leave.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Distrusting the data source | Sensors lie, repeat themselves, arrive out of order and die. A strong candidate says so in the first minute and designs for it, instead of treating the device feed as truth. |
| Separating the read path from the exact path | Showing “about 12 free” may be a second stale. Reserving the last space must be exact. Putting the line between them in the right place is most of the design. |
| Reservation without overselling | Two drivers press Reserve on the last space together. The interviewer wants an atomic conditional update and a choice between reserving a space or a count of spaces. |
| Money and time | A bill depends on an entry time and an exit time. What if the exit message is lost? What about daylight saving time, an overstay or a no-show? Billing must be exact even when the devices are not. |
| IoT thinking | Devices on weak networks, a gateway in each lot, certificates per device, and what happens when a whole lot goes offline. This is the part that makes it different from a plain booking system. |
Smart parking is two problems that look like one. Counting free spaces from unreliable devices must be fast and roughly right. Reserving a space must be exact. We use a different mechanism for each.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | How we know a space is taken, reserve ahead or not, how fresh availability must be, and the scale. |
| 2. Estimate | 3 | Device events per second, the size of the live table, read traffic and the reservation rate. |
| 3. API and data | 5 | Device messages, the driver search and reserve calls, and the tables. |
| 4. High-level design | 8 | Gateway, ingestion, state service, availability cache, reservation and billing. |
| 5. Deep dives | 15 | Reliable ingestion, the read path, reservations, then pricing and billing. |
| 6. Scale and failures | 7 | Dead sensors, an offline lot, a stadium event and device security. |
| 7. Wrap up | 3 | Recap, trade-offs and what you would build next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| How do we know a space is taken: a sensor in every space, gate counters, or cameras reading plates? | This decides whether we have 10 million noisy devices or 50,000 simple counters. It sets the load and how we handle errors. | Mostly a sensor per space in garages, plus entry and exit gates. Street spaces have sensors only. | Two sources of truth that can disagree. We need a way to cross-check them. |
| Can drivers reserve ahead, or is it first come, first served? | A reservation needs an exact count and a rule for no-shows. Showing availability does not. | Both. Some spaces are reservable, the rest are walk-in only. | A reservation service with strong consistency, next to a fast, approximate availability service. |
| How fresh must the free count be? | Seconds of staleness lets us cache. Exact freshness would force every read to the source. | Within about 10 to 30 seconds is fine. A driver can be told 'about 12 free'. | In-memory counters updated from a stream, cached with a short life, and no read-your-write promise. |
| What kinds of space are there, and what does it cost? | Space types (standard, EV, disabled, compact) split the counters. Pricing rules change the billing design. | Four types. Price per 15 minutes with a daily cap, and higher prices when the lot is nearly full. | Counters per lot and type. A price engine that reads occupancy. |
| How many lots and spaces, and how many drivers use the app? | Numbers turn a vague system into a sized one. | 50,000 lots, 10 million spaces in all, 5 million drivers a day. | About 2,300 device events a second on average. The whole live table fits in memory. |
| What happens when a lot loses its network? | Cars still come and go. The server must not fall over, and the lot must still work. | The lot keeps working. Gates and sensors keep reporting to a local gateway that catches up later. | An edge gateway with a local buffer and a store-and-forward link. |
| Are reservations paid in advance, or paid on exit? | Paying in advance adds a payment flow and refunds. Paying on exit is simpler but risks a no-show. | Pay on exit for walk-ins. Reservations take a card hold and a small fee. | A no-show fee uses the payment service. Link to Design a Payment System. |
| Do we read licence plates? | Plates are personal data. They help billing but bring privacy duties. | Plates are optional and kept for a short time. Tickets and app QR codes are the default. | A retention limit and access controls. Billing must work without a plate. |
| One city or many, and are they independent? | Independent cities can be separate shards. A global operator needs a global index. | Many cities, run by one operator. A driver usually searches one city. | Partition the data by city. A geo search never crosses a city boundary. |
| Assumption | Value |
|---|---|
| Lots and spaces | 50,000 lots, 10,000,000 spaces (200 per lot on average) |
| State changes per space | 5 a day (about 2 or 3 cars, each arriving and leaving) |
| Message size | about 100 bytes (ids, state, device time, sequence number) |
| Peak versus average | 10 times, at a stadium event or a rush hour |
| Drivers | 5,000,000 a day, 10 searches each |
| Reservations | 5% of drivers reserve once a day, for about 2 hours |
| Reservation slots | 15 minutes, counters for 7 days ahead, 4 space types |
| Sessions | 2.5 stays a day per space |
| Row sizes | about 50 bytes a space, 200 bytes a lot counter, 24 bytes a capacity row |
| What | Maths | Result |
|---|---|---|
| State changes a day | 10,000,000 spaces × 5 | 50 million a day |
| Device events a second | 50,000,000 ÷ 86,400 | about 580 a second on average, 5,800 at a 10× peak |
| Ingest bandwidth at peak | 5,800 × 100 bytes | about 0.6 MB a second |
| Raw event log | 50,000,000 × 100 bytes | 5 GB a day, 150 GB for 30 days, about 1.8 TB a year |
| Live space table | 10,000,000 × 50 bytes | 500 MB (fits in memory with room to spare) |
| Live lot counters | 50,000 lots × 200 bytes | 10 MB |
| Driver searches a second | 5,000,000 × 10 ÷ 86,400 | about 580 a second, 5,800 at peak |
| Lot lookups a second | 5,800 × about 20 lots in each result | about 116,000 counter reads a second at peak (a cache absorbs them) |
| Reservations a second | 5,000,000 × 5% ÷ 86,400 | about 3 a second, about 29 at peak |
| Capacity rows | 50,000 lots × 4 types × 96 slots a day × 7 days | 134 million rows, about 3.2 GB |
| Counter changes a second | 3 a second × 8 slots per 2-hour stay | about 23 a second, 230 at peak (small) |
| Sessions a day | 10,000,000 × 2.5 | 25 million a day, about 290 a second, 5 GB of billing records a day |
| Heartbeats from lot gateways | 50,000 gateways ÷ 60 seconds | about 830 a second |
| Operator rollups | 50,000 lots × 288 five-minute buckets × 50 bytes | about 720 MB a day, 263 GB a year |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| PUT | MQTT lots/{lotId}/spaces/{spaceId}/status | { occupied: true, deviceTs, seq } | no reply needed (MQTT QoS 1 acknowledges delivery) | Sent by sensors or the lot gateway. seq goes up by one per device, so the server can drop repeats and old messages. Retained message gives the last state to a new subscriber. |
| POST | /v1/lots/{lotId}/entries | { gateId, ticketId or plate, deviceTs, seq } | 201 { sessionId } | A car passes the entry gate. Idempotent by (gateId, seq). Starts a billing session. Also bumps the lot counter. |
| POST | /v1/lots/{lotId}/exits | { gateId, ticketId or plate, deviceTs, seq } | 200 { sessionId, amountDue } | Ends the session and prices it. If no entry exists, falls back to a flat fee and a review flag. |
| GET | /v1/lots?lat=51.5&lng=-0.1&radius=800&type=standard | none | 200 { lots: [{ id, name, distance, freeApprox, price, updatedAt }] } | Cell lookup in the geo index, then free counts from memory. freeApprox is a hint with an age. Never used to promise a space. |
| POST | /v1/reservations | { lotId, spaceType, start, end } + Idempotency-Key header | 201 { reservationId, expiresAt } or 409 { fullSlots: [..] } | Decrements the capacity counter of each 15-minute slot in one transaction, never below zero. A retry returns the same reservation. |
| DELETE | /v1/reservations/{id} | none | 204 | Gives the capacity back. Idempotent. Late cancellations may carry a fee. |
| GET | /v1/lots/{lotId}/occupancy?from=&to=&step=5m | none | 200 { points: [{ ts, occupied, total }] } | For operators. Read from the rollup store, never from the live path. |
| Table or store | Key fields | Why |
|---|---|---|
| lots | lot_id, city, lat, lng, geo_cell, total_by_type, status | Small and read-heavy. Cached everywhere. The geo cell is what the search uses. |
| spaces | lot_id, space_id, type, state (FREE, OCCUPIED, UNKNOWN), last_seq, last_device_ts, last_heard_at | One row per space. last_seq lets the state service drop old or repeated messages. |
| lot_counters (in memory) | lot_id, type, free, occupied, unknown, gate_entries, gate_exits, updated_at | The hot table behind search. Rebuilt from spaces if lost. |
| capacity | lot_id, space_type, slot_start, capacity, reserved (CHECK reserved <= capacity) | One row per lot, type and 15-minute slot. The reservation counter. |
| reservations | reservation_id, driver_id, lot_id, type, start, end, status, idempotency_key (unique) | The unique key makes a retry return the same reservation. |
| sessions | session_id, lot_id, entry_ts, exit_ts, ticket_id or plate_hash, status, amount_cents | One per stay. The source of the bill. |
| events and rollups | append-only log, then 5-minute rollups per lot and type | Raw events kept about 30 days. Rollups kept for years for dashboards and planning. |
-- Reserve one standard space in lot L from 10:00 to 10:30 (two 15-minute slots)
UPDATE capacity
SET reserved = reserved + 1
WHERE lot_id = :lot AND space_type = 'standard'
AND slot_start IN ('10:00', '10:15')
AND reserved < capacity;
-- rows changed must equal the number of slots (2), else ROLLBACK and return 409| Component | What it does |
|---|---|
| Lot gateway | A small box in each lot. Collects local MQTT messages, adds an order, buffers them on disk if the uplink is down, and sends them on. Also runs a local counter so the barrier still works offline. |
| MQTT broker cluster | Accepts device connections with a certificate each. QoS 1 acknowledgement means a message is not lost on the way in. Retained messages give a new subscriber the last state. |
| Event queue | A durable stream partitioned by lot id, so one lot's events stay in order. Lets the state service fall behind without losing anything. |
| State service | Applies each event to a space and its lot counter, but only if the sequence number is newer. Marks silent sensors UNKNOWN. Compares gate counts with sensor counts. |
| Counters and geo index | In-memory free counts per lot and type, and a cell index of lots. Answers “near me” without touching a database. |
| Reservation service | Decrements the capacity counters for each 15-minute slot in one transaction. Owns the no-oversell rule. Releases late holds. |
| Session and price service | Starts a session at entry and ends it at exit, and prices it from rules. Repairs lost events with timeouts and staff overrides. |
| Rollups and device health | Five-minute aggregates for dashboards, and a view of which devices have gone quiet, so a technician can be sent. |
The problem: Sensors repeat messages, send them late, go quiet and report wrong things. A message that arrives after a newer one can turn a taken space back into a free one. A dead sensor says nothing, which looks the same as 'nothing changed'. If we believe every message, the shown number drifts away from the truth.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Trust arrival order | Apply each message as it arrives. The last one wins. | Trivial. Fast. | A delayed old message overwrites a newer one. A repeated message after a reconnect can flip a space back. The visualizer shows the error growing. |
| Sequence numbers per device | Each device numbers its messages 1, 2, 3. The server keeps the last number it applied and ignores any message that is not higher. | Cheap, exact, and handles duplicates and reordering. No clocks needed. | The device must keep its counter across reboots (store it, or add a boot id). A lost message leaves a gap that nothing fills. |
| Device timestamps | Apply the message with the newest device time. | Needs no counter. | Device clocks drift and reset. Two messages in the same second tie. Use time only as a tie-breaker or for the billing record. |
| Heartbeats plus gate cross-checks | Sensors send a small heartbeat. Silence for two intervals marks the space UNKNOWN. Gate entries minus exits gives an independent total. | Catches dead sensors and lost messages that sequence numbers cannot see. | More traffic and a second source to maintain. The two sources will sometimes disagree, and you need a rule for that. |
These three fix three different mistakes, and none of them fixes the others. Sequence numbers fix old and repeated messages. Heartbeats fix quiet devices: a space we cannot vouch for becomes UNKNOWN, not FREE, so no driver is promised a space we cannot see. Gate counts fix lost messages: if the sensors say 26 free and the gates say 24, we trust the gates for the total and flag the lot.
Gate counters fix the total but not which space is free, so the map can still be wrong even when the number is right. Say that out loud. It is what a senior candidate adds.
| Problem | What goes wrong | What catches it |
|---|---|---|
| Old message arrives late | A taken space shows as free | Sequence number: drop anything not newer |
| Same message delivered twice | Harmless for a state, harmful for a counter | Apply states, not +1 or -1. Derive counts from states |
| Sensor dies | A space stays FREE or OCCUPIED for ever | Heartbeat: mark UNKNOWN after two missed beats |
| Exit message lost | Space looks taken, the bill never ends | Gate counts, a session timeout and a sweep |
| False reading (a bag, a bike) | A free space looks taken | Debounce for a few seconds and cross-check the gate total |
| Gateway offline | No events for a whole lot | Gateway buffers and replays in order, and the lot goes UNKNOWN meanwhile |
The problem: A search touches about 20 lots, so 5,800 searches a second at peak become about 116,000 counter reads a second. The answer must be quick and current within seconds, but it does not need to be exact. A stadium event can make one lot hot.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Query the database | SELECT the lots in a radius and count free spaces with a GROUP BY. | Simple. Always the latest committed state. | A heavy aggregate on every search. The database becomes the bottleneck and the write path pays for the read path. |
| Counters in memory plus a geo index | Keep free counts per lot and type in memory, updated by the stream. Find lots by geohash, S2 or H3 cell and read the counters. | Microseconds per lot. Scales with a cache tier. Holds only 10 MB of counters. | A few seconds stale. Needs a rebuild path if memory is lost. Two copies must agree on the same number. |
| Push availability to the client | Open a WebSocket or SSE for the lots the user is looking at, and push each change. | Feels live. No polling. | Many connections. Worth it for the few lots on screen, not for the whole city. |
| Precomputed city heatmaps | Recompute free percentages per map cell every few seconds and serve them from a CDN. | Very cheap at huge scale. | Coarse. Not the right answer for a driver choosing between two lots 200 metres apart. |
The data is tiny (10 MB of counters, 500 MB of spaces), so the answer is to keep it where reads are cheap. The geo index turns a location into a few cells, each cell lists its lots, and each lot has a counter. That is three hash lookups, not a query. Cells come from geohash, S2 or H3, which are the concept topics in the geo part of this course.
The counter is allowed to be 10 to 30 seconds old. Say "about 12 free, updated 12 seconds ago". We never use it to promise a space, because the reservation service does that. A hot lot at a stadium is fine: the counter is one number, so a thousand reads cost almost nothing, and we can add read replicas of the cache.
| Question | Answer |
|---|---|
| How is a location turned into lots? | Convert to a cell id at a fixed size (about the radius). Look up that cell and its neighbours. Check the real distance on the few results. |
| Why also look at neighbouring cells? | A point near a cell edge can have lots just across it. The boundary problem. |
| What if the counter memory is lost? | Rebuild from the spaces table, then catch up from the queue. Search shows 'unknown' for a few seconds. |
| How do we keep the counter and the table consistent? | The counter is derived. A periodic job recomputes it from spaces and fixes drift. It is a cache, not a source of truth. |
| What is shown if a lot is UNKNOWN? | The last known number, greyed, with its age, or hidden. Never a confident number for a dead lot. |
The problem: The invariant: no more reservations than spaces, for any 15-minute slot. Two drivers press Reserve on the last space at the same moment. A reservation also spans several slots, so it must take all of them or none. And some drivers never show up.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Reserve one specific space | The driver (or the system) picks space 41, and a row for that space and time window is locked. | Simple to picture. The driver knows exactly where to go. | Space 41 may be occupied by a car that overstayed. A broken sensor makes the space unusable. Overlap checks on time windows are awkward. |
| Reserve a count: a pool per lot, type and slot | For each 15-minute slot keep a capacity and a reserved count. Reserving subtracts one from every slot in the window, only if reserved is below capacity. | Constant-size, easy to make atomic, tolerates a bad space (assign a free one on arrival). Works with overlap and extension. | The space is only chosen on arrival, so the driver may not know where. Needs a hold-back for walk-ins. |
| Lock per lot | One lock for the whole lot while checking and writing. | Simplest to reason about. | Serialises every reservation in a lot. At a stadium that is a queue of 5,000 cars. Not needed when a conditional update does the job. |
| Allow overbooking by a percentage | Sell a few more reservations than spaces, because some drivers do not come. | Higher use of the lot. | Some drivers arrive to a full lot. Needs a refund or an alternative lot. A business rule, never a default. |
A counter is one conditional write per slot: reserved = reserved + 1 WHERE reserved < capacity. We update all slots of the window in one transaction and compare the changed-row count with the number of slots. If it is short, we roll back, so a driver never ends up with half a reservation. The visualizer shows the alternative, read the counter and then write it, selling five reservations for three spaces.
It is the same idea as the seat hold in Design Ticket / Hotel Booking, and simpler: there is no specific seat, so there is nothing to deadlock on. We keep part of the lot for walk-ins (say 30%), so a reservable pool of 140 out of 200 spaces cannot starve drivers who just turn up.
-- Cancel, or release a no-show after the grace period UPDATE capacity SET reserved = reserved - 1 WHERE lot_id = :lot AND space_type = :t AND slot_start IN (:slots) AND reserved > 0; -- Mark the reservation first (idempotent), then release once: UPDATE reservations SET status = 'RELEASED' WHERE reservation_id = :r AND status = 'ACTIVE'; -- only release if this changed 1 row
| Case | What the design does |
|---|---|
| Driver is late | Grace period (for example 15 minutes), then the reservation is released and a small fee may apply. |
| Driver stays past the end | The session keeps running at the walk-in price. The next slot may be oversold by one: handle by a hold-back, or move the next driver. |
| Arrives and the reserved type is full of overstays | Offer another space type or lot, nearby, and refund. A business policy, said aloud. |
| Request retried after a timeout | Idempotency key: same reservation returned, counters changed once. |
| Cancel arrives twice | The status change succeeds once, so the counter is given back once. |
The problem: A bill depends on two moments: the entry and the exit. Either message can be lost. Prices change with the length of the stay, caps, daily rules and occupancy. Time zones and daylight saving make 'two hours' ambiguous. And a licence plate, if we read it, is personal data.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Charge by the time the app says | The driver's phone starts and stops the timer. | No gate hardware needed. | A phone can lose battery or signal. Drivers can cheat. Not reliable alone. |
| Sessions from gate events | Entry starts a session, exit ends it, and the price is computed from the two server timestamps. | Reliable, auditable and independent of the driver's phone. | A lost entry or exit leaves a session open or missing. Needs repair rules. |
| Pay on entry, a flat fee | The driver pays a fixed amount when entering. | Very simple. No exit event. | Unfair for short stays. No overstay revenue. Only suits some lots. |
| Continuous metering by sensor | Charge for as long as the sensor says the space is occupied. | Works in street spaces with no gate. | Depends on sensors that lie. A false reading means a wrong bill. Use only with a driver-confirmed session. |
Money needs two timestamps we control: the server time when it received the entry and the exit, plus the device time as a cross-check. The price is computed from rules (blocks of 15 minutes, a daily cap, a higher rate when the lot is above 90% full) and stored in integer cents, never as a float. The same ideas as the payment case study: one idempotent charge per session, and an audit trail.
Lost events are expected. A missing exit closes the session after a timeout at a fixed maximum fee and flags it for review. A missing entry is priced as a flat fee, or from the sensor's first occupied time, and flagged. Staff can correct a session, and every change is logged. Time is stored in UTC, and the rule engine converts to the lot's zone only to decide which tariff applies, so daylight saving cannot give a driver 25 hours or 23 hours by accident.
| Stay | How it is priced |
|---|---|
| 3 h 20 min at 0.50 per 15 minutes | 14 blocks (rounded up) × 0.50 = 7.00, then the daily cap if lower |
| Overnight across the clock change | Priced from elapsed UTC time. The tariff zone only picks the rate bands, so no hour appears or vanishes |
| Exit scanned but no entry on record | Flat fee plus a review flag. Entry time from the first sensor reading if one exists |
| Car never exits (no event) | Close after the maximum stay at the maximum fee, then flag. Send a message to the driver |
| Disputed bill | Show entry and exit times, tariff and rule version. Staff can adjust. All changes are in an audit log |
| Tick | Shown | True | Error | Wrong spaces |
|---|---|---|---|---|
| 0 | 28 | 28 | 0 | 0 |
| 1 | 27 | 27 | 0 | 0 |
| 2 | 26 | 26 | 0 | 0 |
| 3 | 26 | 25 | +1 | 1 |
| 4 | 27 | 27 | 0 | 0 |
| 5 | 26 | 27 | -1 | 1 |
| 6 | 25 | 27 | -2 | 2 |
| 7 | 25 | 28 | -3 | 3 |
| 8 | 25 | 28 | -3 | 3 |
| 9 | 25 | 27 | -2 | 4 |
| 10 | 24 | 26 | -2 | 4 |
| 11 | 25 | 27 | -2 | 4 |
| 12 | 24 | 26 | -2 | 4 |
A simplified model with fixed data and no random numbers. Sensor reports say “occupied” or “free” plus a sequence number, so an exact copy is harmless; the danger is an OLD report arriving after a NEWER one. The gate counter is assumed to be exact here; real gates drift too, so use them as a cross-check.
| Bottleneck | Fix |
|---|---|
| One stadium lot gets a flood of events and reads | Partition the queue by lot, but give very hot lots their own partition. Keep the counter a single number, so reads cost almost nothing, and add read replicas of the cache. |
| Search fans out to about 20 lots | Counters in memory next to the geo index, a short response cache per cell, and a cap on the number of lots returned. |
| MQTT connections: 50,000 gateways, or 10 million sensors | Prefer one gateway connection per lot over one per sensor. Shard brokers by region. Use keep-alives and a bounded reconnect backoff so a mass reconnect does not stampede. |
| A reconnect storm after an outage | Jittered backoff on every device and gateway, and a rate limit at the broker. The queue absorbs the replay and the state service catches up in order. |
| Capacity rows for 7 days ahead (134 million) | Create rows lazily for slots that are actually reservable, partition by city and date, and archive past slots. Keep the table small by design. |
| Operator dashboards over raw events | Read five-minute rollups from a time-series or columnar store, never the raw log, and cache the last hour. |
| Failure | How the design copes |
|---|---|
| A lot loses its network | The gateway keeps the barrier working from a local counter and buffers events on disk. The server marks the lot UNKNOWN after missed heartbeats and replays the buffer in order when the link returns. |
| A sensor dies, or a whole batch after a firmware update | Missed heartbeats turn those spaces UNKNOWN, not FREE. The lot total comes from gate counts, and a repair ticket is raised. Roll firmware out in small batches with a rollback. |
| The state service or the in-memory counters crash | Restart, rebuild counters from the spaces table, then catch up from the queue. Search shows ages, so a short gap is visible and honest. |
| The reservation database fails over | A synchronous replica takes over. In-flight reservations are in the database and survive. Writes pause for seconds, and clients retry with their idempotency key. |
| Entry and exit events arrive out of order or twice | Idempotent by (gate, seq). A session is created once. An exit before its entry waits briefly, then is repaired by the missing-entry rule. |
| A payment provider is down at exit | Let the car leave (the gate opens), record the amount due, and charge later with the same idempotency key. Never block the barrier on a slow card call. |
Devices report states with sequence numbers through a lot gateway to a queue. A state service drops old and repeated messages, marks silent sensors unknown, and keeps small in-memory counters beside a geo index, so search is fast and about 10 to 30 seconds old. Reservations are exact: a capacity counter per lot, type and 15-minute slot, decremented in one conditional update, never below zero. Billing runs on sessions with server times, integer cents and repair rules for lost events. Gate counts cross-check the total.
| Decision | What we gain | What it costs |
|---|---|---|
| Approximate free counts, exact reservations | A fast, cheap read path that scales to hundreds of thousands of reads a second. | A driver can arrive and find the lot full. We soften it with the age shown and a nearby alternative. |
| Reserve a count, not a specific space | Simple atomic update, tolerates a broken space, works with overlapping windows. | The driver does not know the exact space until arrival. |
| A gateway in every lot | The lot keeps working offline, and the cloud sees an ordered stream. | 50,000 boxes to deploy, secure and update. |
| Sequence numbers over timestamps | Exact ordering without trusting clocks. | Devices must keep a counter across reboots. |
| Hold back part of the lot for walk-ins | Reservations cannot lock out drivers who just turn up. | Some capacity may sit idle. |
| Mark silent sensors UNKNOWN | We never promise a space we cannot see. | Shown availability dips when sensors fail, even if the spaces are free. |
The part that makes this different from a plain booking system. Say early that devices are unreliable.
Show about 12 free quickly, and know when approximate is good enough.
The same shape as a seat booking, with a simpler unit. State the invariant first.
Where money, privacy and an interviewer's changing requirements show up.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| The lot has no sensors, only gates | Free count becomes entries minus exits, which is exact for the total but says nothing about which spaces are free. Reservations work the same. Drift is corrected by a nightly zero-reset. |
| Street parking with no gates and no sessions | Billing starts from an app check-in or a sensor event and ends at a check-out or sensor free. Enforcement matters more, so wardens' handhelds read the same occupancy and session data. |
| Add electric-vehicle charging | A second resource with its own capacity and reservation counters, a charger state machine, and billing by energy and time. The same patterns apply. |
| Reservations must name a specific space | Reserve a row per space and time window with a unique key on (space, window). Handle a blocked or broken space by moving the reservation to an equal space. |
| Many operators share one app | Add a tenant id to every table and key, per-tenant rate limits and prices, and keep each operator's data apart (see the multi-tenancy topic). |
| Add licence-plate recognition at the gates | A new event source feeding sessions without tickets. A confidence score and a human review queue for low-confidence reads, and a short retention with strict access. |
| Add predictions of free spaces in an hour | A batch or stream job on the rollups produces a probability per lot and hour, shown next to the live count. It never feeds reservations. |
| The interviewer asks for global exactness of the free count | Push back on the need. An exact count needs a synchronous round trip per event, which costs latency and availability for little benefit. Offer reservations as the exact path. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Jumps to boxes and does not ask how a space is detected. | Asks about sensors, reservations and freshness. | Separates the approximate count from the exact reservation, and asks about offline lots and licence plates. |
| Estimation | Guesses that the load is huge. | Computes events and searches a second. | Finds the load is small, that the live table is 500 MB, and that search fan-out drives the read traffic. |
| Device reliability | Trusts every message. | Mentions duplicates and sequence numbers. | Sequence numbers, states not deltas, heartbeats to UNKNOWN, gate cross-checks, and says the gate fixes the total but not the map. |
| Reservation correctness | Reads the count and then writes. | Uses a transaction or a lock. | Pool counters per slot, atomic conditional update with a changed-row check, no-show release, idempotency and a hold-back for walk-ins. |
| Billing | Multiplies hours by a rate. | Uses entry and exit times. | Server times in UTC, integer cents, repair rules for lost events, an audit log and a plate retention limit. |
| Trade-offs and operations | One design, no alternatives. | Compares MQTT with HTTP, or counters with spaces. | Explains stale versus exact, the cost of a gateway in every lot, security per device, and a simulator for testing. |
| Mistake | Do this instead |
|---|---|
| Trusting sensors as the single source of truth | Treat sensors and gates as two noisy sources. Use sequence numbers, heartbeats and a gate cross-check. |
| Applying messages in arrival order | Use a per-device sequence number and apply only a newer one. |
| Sending +1 and -1 instead of states | Send the state of the space and derive the count, so a duplicate is harmless. |
| Showing a dead sensor's space as free | Mark it UNKNOWN after missed heartbeats and never promise it. |
| Reading the capacity counter and then writing it | One conditional UPDATE, and check the changed-row count. |
| Reserving specific spaces for a short, ordinary booking | Reserve a count per slot and pick a space on arrival. |
| Blocking the barrier on the cloud or a card call | The gateway decides locally, and billing happens after, with an idempotency key. |
| Storing money as floats and local times | Integer cents and UTC elapsed time, with a tariff zone only to pick rate bands. |
The tiny publish-subscribe protocol the sensors use, with QoS levels and retained messages.
How a silent sensor or gateway is noticed, and why silence means unknown.
Turning a location into a cell id for the near-me search.
Making a retried reservation or exit event safe.
Why a reservation across several slots must be all-or-nothing.
The same no-oversell idea with holds, expiry and a flash sale.
Charging at exit, with an idempotency key and exact money.
Getting the driver to the lot, which we left out of scope.