SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a URL Shortener
  • Design Pastebin
  • Design a Rate Limiter
  • Design a Unique ID Generator
  • Design a Key-Value Store
  • Design a Scalable Parking System (Smart Parking)
System Design/Case Studies/Easy
Interview case study

Design a Scalable Parking System (Smart Parking)

Track free spaces in many lots, guide drivers to a spot, and never sell the same space twice.

⏱ 30 min readEasy case studyIntermediate22 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“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 checkWhy it matters
Distrusting the data sourceSensors 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 pathShowing “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 oversellingTwo 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 timeA 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 thinkingDevices 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.

TL;DRThe whole design in 60 seconds

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.

  • Devices talk to a gateway. Each lot has a small edge gateway that collects sensor and gate messages over MQTT, buffers them if the network drops, and forwards them in order with a sequence number per device.
  • The server trusts sequence numbers, not arrival order. An old or repeated message is ignored. A sensor that stops talking is marked UNKNOWN, never FREE.
  • Gate counters are the cross-check. Entries minus exits gives the total. When it disagrees with the sensors, the server corrects the total and flags the lot for a visit.
  • Availability is a small in-memory table of free counts per lot and per space type, plus a geo index. “Near me” is a cell lookup, filter and sort. It may be 10 to 30 seconds old.
  • Reservations are counters, not spaces. We reserve “one standard space in lot L from 10:00 to 11:00” by decrementing a capacity counter for each 15-minute slot, atomically, and never below zero. A real space is picked on arrival.
  • Billing runs on sessions. A session starts at entry and ends at exit. Lost events are repaired by timeouts and staff overrides, and the price is computed in whole cents.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4How we know a space is taken, reserve ahead or not, how fresh availability must be, and the scale.
2. Estimate3Device events per second, the size of the live table, read traffic and the reservation rate.
3. API and data5Device messages, the driver search and reserve calls, and the tables.
4. High-level design8Gateway, ingestion, state service, availability cache, reservation and billing.
5. Deep dives15Reliable ingestion, the read path, reservations, then pricing and billing.
6. Scale and failures7Dead sensors, an offline lot, a stadium event and device security.
7. Wrap up3Recap, trade-offs and what you would build next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: ask how the system knows a space is taken, whether drivers can book ahead, and how wrong the free count is allowed to be.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Show free spaces near a place, by lot and by space type, with a price
  • •Let a driver reserve a space for a time window and cancel it
  • •Track entries and exits, and bill each stay by its length
  • •Show operators live occupancy and history for each lot
  • •Detect broken sensors and gates and raise a repair ticket
Non-functional (how well)
  • •Fresh enough: free counts within about 10 to 30 seconds of reality
  • •Exact where it matters: a reservation is never sold twice, and a bill is exact to the cent
  • •Available: 99.95% for search, and a lot keeps working without the cloud
  • •Scalable: 10 million spaces, about 2,300 device events a second, and 10 times that at a stadium event
  • •Safe: devices authenticate, plates are retained briefly, and card data never touches our servers
Out of scope (say it)
  • •Turn-by-turn navigation to the lot (see Design Google Maps)
  • •Running the payment network itself (see Design a Payment System)
  • •Valet, electric-vehicle charging control and gate hardware design
  • •Licence-plate recognition models
🎤
Say it out loud
“Let me confirm the scope. We track about 10 million spaces in 50,000 lots, mostly with a sensor per space and counters at the gates. Drivers see free spaces near them, which may be 10 to 30 seconds old, and can reserve a space for a time window, which must be exact. We bill by the length of the stay, paying on exit. Navigation and the payment network are separate. Every lot has a gateway that keeps working if the network drops. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: device events a second, how big the live table is, how many drivers search, and how many reservation counters change each second. Which of these is the surprise?

Assumptions (say them first)

AssumptionValue
Lots and spaces50,000 lots, 10,000,000 spaces (200 per lot on average)
State changes per space5 a day (about 2 or 3 cars, each arriving and leaving)
Message sizeabout 100 bytes (ids, state, device time, sequence number)
Peak versus average10 times, at a stadium event or a rush hour
Drivers5,000,000 a day, 10 searches each
Reservations5% of drivers reserve once a day, for about 2 hours
Reservation slots15 minutes, counters for 7 days ahead, 4 space types
Sessions2.5 stays a day per space
Row sizesabout 50 bytes a space, 200 bytes a lot counter, 24 bytes a capacity row

The arithmetic, line by line

WhatMathsResult
State changes a day10,000,000 spaces × 550 million a day
Device events a second50,000,000 ÷ 86,400about 580 a second on average, 5,800 at a 10× peak
Ingest bandwidth at peak5,800 × 100 bytesabout 0.6 MB a second
Raw event log50,000,000 × 100 bytes5 GB a day, 150 GB for 30 days, about 1.8 TB a year
Live space table10,000,000 × 50 bytes500 MB (fits in memory with room to spare)
Live lot counters50,000 lots × 200 bytes10 MB
Driver searches a second5,000,000 × 10 ÷ 86,400about 580 a second, 5,800 at peak
Lot lookups a second5,800 × about 20 lots in each resultabout 116,000 counter reads a second at peak (a cache absorbs them)
Reservations a second5,000,000 × 5% ÷ 86,400about 3 a second, about 29 at peak
Capacity rows50,000 lots × 4 types × 96 slots a day × 7 days134 million rows, about 3.2 GB
Counter changes a second3 a second × 8 slots per 2-hour stayabout 23 a second, 230 at peak (small)
Sessions a day10,000,000 × 2.525 million a day, about 290 a second, 5 GB of billing records a day
Heartbeats from lot gateways50,000 gateways ÷ 60 secondsabout 830 a second
Operator rollups50,000 lots × 288 five-minute buckets × 50 bytesabout 720 MB a day, 263 GB a year
What the numbers tell us about the design
  • •The surprise is that the load is small. 580 device events a second is nothing for a stream. The difficulty is correctness and unreliable devices, not throughput.
  • •The live table is 500 MB. The whole picture of every space in the world fits in the memory of one machine, so the read path is a cache problem, not a database problem.
  • •Searches fan out: one search reads counters for about 20 lots, so 5,800 searches a second become about 116,000 counter reads a second at peak. That is why the counters live in memory next to the geo index.
  • •Reservations are rare (about 3 a second) and each touches only about 8 counters. This part is tiny, so we can afford strong consistency and a plain transactional database.
  • •The 30-day raw log is only 150 GB. Keep raw events briefly and keep five-minute rollups for years.
🎤
Say it out loud
“Let me do the maths. 10 million spaces changing state about 5 times a day is 50 million events a day, or about 580 a second, and 5,800 at a peak. That is tiny. The live table is 500 megabytes, so it fits in memory. A search reads counters for about 20 lots, so 5,800 searches become about 116,000 counter reads a second, which is why counters are cached beside the geo index. Reservations are about 3 a second. So the design is about distrusting devices and getting reservations exactly right, not about raw volume.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the message a sensor sends, the call a driver makes to find a lot, and the call that reserves one. Which field in the sensor message lets the server ignore an old report?

Endpoints

MethodPathRequestResponseNotes
PUTMQTT 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=standardnone200 { 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 header201 { 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}none204Gives the capacity back. Idempotent. Late cancellations may carry a fee.
GET/v1/lots/{lotId}/occupancy?from=&to=&step=5mnone200 { points: [{ ts, occupied, total }] }For operators. Read from the rollup store, never from the live path.

Data model

Table or storeKey fieldsWhy
lotslot_id, city, lat, lng, geo_cell, total_by_type, statusSmall and read-heavy. Cached everywhere. The geo cell is what the search uses.
spaceslot_id, space_id, type, state (FREE, OCCUPIED, UNKNOWN), last_seq, last_device_ts, last_heard_atOne 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_atThe hot table behind search. Rebuilt from spaces if lost.
capacitylot_id, space_type, slot_start, capacity, reserved (CHECK reserved <= capacity)One row per lot, type and 15-minute slot. The reservation counter.
reservationsreservation_id, driver_id, lot_id, type, start, end, status, idempotency_key (unique)The unique key makes a retry return the same reservation.
sessionssession_id, lot_id, entry_ts, exit_ts, ticket_id or plate_hash, status, amount_centsOne per stay. The source of the bill.
events and rollupsappend-only log, then 5-minute rollups per lot and typeRaw events kept about 30 days. Rollups kept for years for dashboards and planning.
The statement that carries the no-oversell rule
-- 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
📝Which store, and why
Reservations and capacity need transactions and a CHECK constraint, so a relational database (partitioned by city) owns them. The live occupancy is a small in-memory table fed by a stream: it can be rebuilt from the spaces table and is allowed to be a few seconds old. Raw device events go to an append-only log, and five-minute rollups go to a time-series or columnar store for dashboards. Three stores, each chosen for one job.
🎤
Say it out loud
“A sensor sends a status message with a device time and a sequence number, so the server can ignore old or repeated reports. A driver searches by location and gets lots with an approximate free count and its age. A reservation is a POST with an idempotency key that decrements a capacity counter for each 15-minute slot in one transaction, only where reserved is below capacity, and I compare the changed-row count with the number of slots. Spaces and sessions are tables, the live counters sit in memory, and raw events become five-minute rollups.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw it as two paths: a sensor event travelling in, and a driver's search travelling out. Where does the gateway sit, and which box is allowed to be a few seconds stale?
Smart parking: high-level design
📡Sensors and gatesone per space, one per gate
→↓MQTT
🧰Lot gatewaybuffers if offline
→↓TLS
🔌MQTT broker clusterauth per device
→↓stream
📨Event queuepartitioned by lot
State (fast, approximate)
🧠State servicedrop old, repeats, dead
⚡Counters in memoryfree by lot and type
🗺️Geo indexcells to lots
Reservations (exact)
🎫Reservation serviceatomic capacity counters
🗄️Transactional DBby city
⏱️No-show sweeperreleases late holds
Billing
🧾Session and priceentry to exit
💳Paymentsprovider, idempotent
Insight
📊Rollups5-minute, per lot
🛠️Device healthheartbeats, repairs
📱Driver appsearch, reserve, pay
→↓HTTPS
🚪API gatewayauth, rate limit
Devices talk to a gateway in each lot. Events flow through a queue to a state service that keeps small in-memory counters. Reservations and billing use a transactional database.
ComponentWhat it does
Lot gatewayA 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 clusterAccepts 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 queueA durable stream partitioned by lot id, so one lot's events stay in order. Lets the state service fall behind without losing anything.
State serviceApplies 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 indexIn-memory free counts per lot and type, and a cell index of lots. Answers “near me” without touching a database.
Reservation serviceDecrements the capacity counters for each 15-minute slot in one transaction. Owns the no-oversell rule. Releases late holds.
Session and price serviceStarts 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 healthFive-minute aggregates for dashboards, and a view of which devices have gone quiet, so a technician can be sent.
Write path (follow one request)
  1. A car parks. The space sensor sends “occupied” with its device time and the next sequence number. The lot gateway adds it to its local queue.
  2. The gateway forwards messages over TLS to the MQTT cluster with QoS 1. If the uplink is down it keeps them on disk and sends them in order when the link returns.
  3. The broker authenticates the device by its certificate and puts the message on the event queue, keyed by lot id.
  4. The state service reads the message. If its sequence number is not newer than the last one for that space, it drops it. Otherwise it updates the space and adjusts the lot counter.
  5. The new free count is written to the in-memory counters and published to anyone watching that lot (a driver looking at its page, an operator dashboard).
  6. In the background the event is also appended to the raw log and folded into the five-minute rollup. Gate counts are compared with the sensors every few minutes, and the total is corrected if they disagree.
Read path (follow one request)
  1. A driver opens the app. It sends its location, a radius and the space type it needs.
  2. The API gateway checks the token and the rate limit, then asks the search service.
  3. The search service turns the location into a few geo cells and lists the lots in them.
  4. For each lot it reads the free count from memory and the price from a small cache. Lots with nothing free are dropped.
  5. It sorts by distance, price and a free-space estimate, and returns a short list, each with the age of its number.
  6. If the driver chooses Reserve, that is a separate call to the reservation service, which does the exact check.
🎤
Say it out loud
“Here is the picture. Sensors and gates talk MQTT to a gateway in each lot, which buffers if the network drops and forwards to a broker cluster. Events go on a queue partitioned by lot to a state service that drops old or repeated messages by sequence number, marks silent sensors unknown, and keeps free counts in memory next to a geo index. Search reads only those. Reservations go to a separate transactional service that decrements a capacity counter for each slot, and billing runs on sessions, with payments done by a provider.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Ingesting sensor events you cannot trust

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.

OptionHow it worksGoodBad
Trust arrival orderApply 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 deviceEach 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 timestampsApply 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-checksSensors 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.
Pick
Sequence numbers per device for ordering, heartbeats for silence, and gate counts as the cross-check on the total

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.

ProblemWhat goes wrongWhat catches it
Old message arrives lateA taken space shows as freeSequence number: drop anything not newer
Same message delivered twiceHarmless for a state, harmful for a counterApply states, not +1 or -1. Derive counts from states
Sensor diesA space stays FREE or OCCUPIED for everHeartbeat: mark UNKNOWN after two missed beats
Exit message lostSpace looks taken, the bill never endsGate counts, a session timeout and a sweep
False reading (a bag, a bike)A free space looks takenDebounce for a few seconds and cross-check the gate total
Gateway offlineNo events for a whole lotGateway buffers and replays in order, and the lot goes UNKNOWN meanwhile
🧠Apply states, not deltas
A message that says “space 9 is occupied” is safe to apply twice. A message that says “one more car” is not. Send and store state, then compute the free count from the states. Duplicates then cost nothing.
📝MQTT QoS
QoS 0 may lose a message. QoS 1 is at least once, so duplicates happen and sequence numbers handle them. QoS 2 is exactly once on the wire but costs more round trips. With states and sequence numbers, QoS 1 is enough.
🎤
Say it out loud
“I would not trust arrival order. Each device numbers its messages, and the server only applies a message with a higher number than the last one it took, so late and repeated messages do nothing. We send states, not plus-one and minus-one, so a duplicate is harmless. A sensor that misses two heartbeats becomes unknown, not free. And gate entries minus exits is an independent total, which catches lost messages. It fixes the total, not which space is free, so I keep the map and the number apart.”
5.2

The read path: free spaces near me, fast

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.

OptionHow it worksGoodBad
Query the databaseSELECT 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 indexKeep 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 clientOpen 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 heatmapsRecompute 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.
Pick
In-memory counters and a cell index for search, with a short cache and push for the lot a driver is watching

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.

QuestionAnswer
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.
🎤
Say it out loud
“A search is three lookups: location to a few geo cells, cells to lots, lots to counters held in memory. The counters are only 10 megabytes. They are updated by the stream and may be 10 to 30 seconds old, so we show about 12 free with its age, and never promise a space from it. The counter is derived from the spaces table and rebuilt if lost. For a driver watching one lot I push updates over a WebSocket. The reservation service is what makes a promise.”
5.3

Reservations that never oversell

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.

OptionHow it worksGoodBad
Reserve one specific spaceThe 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 slotFor 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 lotOne 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 percentageSell 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.
Pick
A pool counter per lot, type and 15-minute slot, decremented in one conditional UPDATE, with a space chosen on arrival and a no-show timeout

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 and no-show give the capacity back
-- 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
CaseWhat the design does
Driver is lateGrace period (for example 15 minutes), then the reservation is released and a small fee may apply.
Driver stays past the endThe 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 overstaysOffer another space type or lot, nearby, and refund. A business policy, said aloud.
Request retried after a timeoutIdempotency key: same reservation returned, counters changed once.
Cancel arrives twiceThe status change succeeds once, so the counter is given back once.
💡Link the general pattern
The no-double-booking idea, holds and expiry are covered in Design Ticket / Hotel Booking. Here the pool counter is the simpler cousin, because the unit is a count of identical spaces.
🎤
Say it out loud
“The invariant is that reservations for a slot never exceed capacity. I keep a capacity and a reserved count per lot, space type and 15-minute slot. Reserving is one transaction that adds one to each slot in the window only where reserved is below capacity, and I check that the changed-row count equals the number of slots, rolling back otherwise. The space is picked on arrival, so one bad sensor does not strand a reservation. A no-show timeout gives the capacity back, a unique idempotency key makes retries safe, and 30% of the lot is held for walk-ins.”
5.4

Sessions, pricing and billing that stay exact

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.

OptionHow it worksGoodBad
Charge by the time the app saysThe 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 eventsEntry 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 feeThe 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 sensorCharge 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.
Pick
Sessions from gate events (or app check-in for street spaces), priced from server times in whole cents, with timeouts and a staff override to repair lost events

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.

StayHow it is priced
3 h 20 min at 0.50 per 15 minutes14 blocks (rounded up) × 0.50 = 7.00, then the daily cap if lower
Overnight across the clock changePriced from elapsed UTC time. The tariff zone only picks the rate bands, so no hour appears or vanishes
Exit scanned but no entry on recordFlat 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 billShow entry and exit times, tariff and rule version. Staff can adjust. All changes are in an audit log
⚠️Plates are personal data
Keep a plate (or a hash of it) only as long as needed to bill and handle disputes, restrict who can read it, and prefer tickets or app QR codes where possible. See the Data Privacy and GDPR Basics topic. This is an engineering design, not legal advice.
🎤
Say it out loud
“A bill needs two moments we control, so a session starts at the entry gate and ends at the exit gate, using server timestamps. The price comes from rules, in blocks, with a daily cap and a rate that rises when the lot is nearly full, and it is stored as integer cents. I store time in UTC so daylight saving cannot add or remove an hour. Lost events are normal: a missing exit closes at a maximum fee after a timeout, a missing entry gets a flat fee, and staff can correct either, with an audit log. Plates are kept briefly because they are personal data.”
VisualizerSensor reports against the truth, and the last three spacesPart 1: move the time slider and turn the three checks on one at a time to see which error each one removes. Part 2: reserve the last 3 spaces for 5 drivers, with and without an atomic step.
Part 1: what the app shows against what is true
Ignore old messages (check the device sequence number)
Check against the gate counters
Silent sensor becomes UNKNOWN (heartbeat)
Each box is a space as the SERVER sees it: green = free, grey = taken, amber = unknown. A red ring means the server is wrong about that space at this tick.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
space 44: car arrived
Shown to drivers
24
free spaces
Really free
26
the truth
Error now
-2
shown minus true
Wrong spaces now
4
on the map
Worst error in the run
3
final -2
The app shows 2 fewer free spaces than there really are, with 4 spaces wrong on the map. Drivers drive past a lot that has room. Turn on the checks one by one to see which mistake each one removes.
TickShownTrueErrorWrong spaces
0282800
1272700
2262600
32625+11
4272700
52627-11
62527-22
72528-33
82528-33
92527-24
102426-24
112527-24
122426-24
Part 2: the last 3 spaces for 10:00 to 10:15, and 5 drivers press “Reserve” together
How does the server take a space?
Driver 1: reserved
Driver 2: reserved
Driver 3: reserved
Driver 4: reserved
Driver 5: reserved
Capacity
3
spaces in the slot
Reservations accepted
5
of 5 requests
Oversold
2
more than capacity
Counter stored
2
last writer wins
All five drivers read “3 left” before anyone wrote, so all five are told yes and the counter ends at 2. Two drivers will arrive to find no space. The read and the write must be one step.

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.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Run the worst day. A stadium empties onto one lot, a gateway loses its network, a batch of sensors dies after a firmware update, and a rush hour doubles the traffic. What breaks first?

What breaks first, and the fix

BottleneckFix
One stadium lot gets a flood of events and readsPartition 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 lotsCounters 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 sensorsPrefer 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 outageJittered 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 eventsRead five-minute rollups from a time-series or columnar store, never the raw log, and cache the last hour.

What if a part fails?

FailureHow the design copes
A lot loses its networkThe 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 updateMissed 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 crashRestart, 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 overA 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 twiceIdempotent 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 exitLet 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.
What to monitor
  • •Free-count error: sensor-derived total minus gate-derived total, per lot (alert on a large or growing gap)
  • •Devices silent for more than two heartbeats, and the share of spaces in UNKNOWN
  • •Event queue lag and the age of the freshest counter per lot
  • •Reservation 409 rate, no-show rate and capacity used per slot
  • •Sessions open longer than the maximum stay, and sessions without an entry
  • •Search latency (p99) and cache hit ratio for the geo index
Security and abuse
  • •Every device has its own certificate and identity, so a stolen sensor can be revoked without touching the rest
  • •Authorise by topic: a device may publish only to its own lot and space, so one device cannot spoof another lot
  • •Signed firmware and staged rollouts, with a way to roll back and to see the version of every device
  • •Rate limits and sanity checks on reservations, to stop a script from reserving every slot of a lot
  • •Short retention for licence plates, hashed where possible, and access limited to billing and support

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
Approximate free counts, exact reservationsA 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 spaceSimple atomic update, tolerates a broken space, works with overlapping windows.The driver does not know the exact space until arrival.
A gateway in every lotThe lot keeps working offline, and the cloud sees an ordered stream.50,000 boxes to deploy, secure and update.
Sequence numbers over timestampsExact ordering without trusting clocks.Devices must keep a counter across reboots.
Hold back part of the lot for walk-insReservations cannot lock out drivers who just turn up.Some capacity may sit idle.
Mark silent sensors UNKNOWNWe never promise a space we cannot see.Shown availability dips when sensors fail, even if the spaces are free.
If we had more time, we would…
  • •Predict free spaces for the next hour from history (for example a dip before a match), and show a probability.
  • •Dynamic pricing tuned from occupancy and events, with limits.
  • •Camera-based plate recognition, with a short retention and a clear privacy review.
  • •Electric-vehicle charging as a second resource with its own reservations.
  • •A device simulator and replay tests that inject duplicates, delays, silence and a network drop.
🎤
Say it out loud
“To recap: devices send states with sequence numbers through a gateway to a queue, and a state service ignores old messages, marks silent sensors unknown and keeps small in-memory counters next to a geo index, so search is fast and a few seconds old. Reservations are exact, using a capacity counter per slot decremented atomically, and the space is chosen on arrival. Billing uses sessions and integer cents with repair rules. Next I would add prediction and a simulator that injects failures.”

Q&ACross-questions (22)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Trusting the devices

The part that makes this different from a plain booking system. Say early that devices are unreliable.

Reading availability fast

Show about 12 free quickly, and know when approximate is good enough.

Reservations and the last space

The same shape as a seat booking, with a simpler unit. State the invariant first.

Billing, scale and curveballs

Where money, privacy and an interviewer's changing requirements show up.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
The lot has no sensors, only gatesFree 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 sessionsBilling 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 chargingA 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 spaceReserve 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 appAdd 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 gatesA 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 hourA 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 countPush 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.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsJumps 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.
EstimationGuesses 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 reliabilityTrusts 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 correctnessReads 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.
BillingMultiplies 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 operationsOne 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.

AvoidCommon mistakes on this question

MistakeDo this instead
Trusting sensors as the single source of truthTreat sensors and gates as two noisy sources. Use sequence numbers, heartbeats and a gate cross-check.
Applying messages in arrival orderUse a per-device sequence number and apply only a newer one.
Sending +1 and -1 instead of statesSend the state of the space and derive the count, so a duplicate is harmless.
Showing a dead sensor's space as freeMark it UNKNOWN after missed heartbeats and never promise it.
Reading the capacity counter and then writing itOne conditional UPDATE, and check the changed-row count.
Reserving specific spaces for a short, ordinary bookingReserve a count per slot and pick a space on arrival.
Blocking the barrier on the cloud or a card callThe gateway decides locally, and billing happens after, with an idempotency key.
Storing money as floats and local timesInteger cents and UTC elapsed time, with a tariff zone only to pick rate bands.

Revise60-second revision sheet

  • ✔Two problems: counting free spaces is approximate and fast. Reserving a space is exact.
  • ✔Devices lie: sequence number per device, send states not deltas, heartbeats mean UNKNOWN, gate counts cross-check the total.
  • ✔Gate counts fix the total, not which space is free.
  • ✔Read path: counters in memory (10 MB) + geo cells. Search is three lookups. Show the age of the number.
  • ✔Scale: 580 events a second (5,800 at peak). Tiny. The search fan-out (about 20 lots) drives the reads.
  • ✔Reservation: capacity and reserved per lot, type and 15-minute slot. One conditional UPDATE, changed rows = slots, else roll back.
  • ✔No-shows: grace period, idempotent release, hold back about 30% for walk-ins.
  • ✔Billing: session from entry to exit, UTC, integer cents, repair rules for lost events, audit log.
  • ✔Offline lot: the gateway keeps the barrier working, buffers events and replays them in order.
  • ✔One line: “Be roughly right about what you can see, and exactly right about what you promise.”

Read these topics next

MQTT→

The tiny publish-subscribe protocol the sensors use, with QoS levels and retained messages.

Heartbeats→

How a silent sensor or gateway is noticed, and why silence means unknown.

Geohash→

Turning a location into a cell id for the near-me search.

Idempotency→

Making a retried reservation or exit event safe.

ACID Transactions→

Why a reservation across several slots must be all-or-nothing.

Design Ticket / Hotel Booking→

The same no-oversell idea with holds, expiry and a flash sale.

Design a Payment System→

Charging at exit, with an idempotency key and exact money.

Design Google Maps→

Getting the driver to the lot, which we left out of scope.

← Previous
Design a Key-Value Store
Next →
Design a Chat App