← Back to practice catalog

System design interview guide

Parking Lot System Design

TL;DR:

Picture a busy mall garage on a Saturday afternoon, with several entry lanes and a ticket machine at each one. Two cars reach two different lanes at the same moment, and each machine looks at its list of free spots and offers Spot 12 to both drivers. One driver parks and the other finds a car already there. The software that decides which spot each car gets, keeps track of every stay, and charges the driver when the car leaves is called a parking lot system, and it has to make sure one spot is never given to two cars and one stay is never charged twice.

Overview diagram for Parking Lot System Design

Problem statement

Design the software behind a garage gate: when a car arrives, give it a spot that fits and a ticket; while it is parked, track the stay; when it leaves, charge once and free the spot. Drivers also see a spots-left sign that can update quickly, but the gate itself must never hand the same space to two cars, and a second tap on Pay must never bill twice.

Introduction

The problem: a mall garage on a Saturday

Picture a mall garage on a Saturday afternoon. It has four entry lanes, and each lane has a ticket machine that prints a ticket with a spot number on it. Cars arrive every few seconds, and every driver expects two simple things: a spot of their own, and a fair bill when they leave. Most of the time nothing goes wrong, because most cars arrive a comfortable distance apart.

Then two cars reach two different lanes at almost the same moment. Both machines look at their list of free spots, and both see Spot 12 at the top. Both machines print “Spot 12.” One driver parks there, and the other drives up the ramp to find a car already in the space, an angry argument, and a garage attendant called over to sort it out. The same kind of thing happens at the exit. A driver taps Pay, the card reader is slow, the screen times out, the driver taps again, and the card is charged twice for one visit.

The software behind those machines is called a parking lot system. It decides which spot each car gets, keeps track of how long each car has stayed, charges the driver on the way out, and updates a sign that tells new arrivals how many spots are left.

Why teams bother with a parking lot system

You have probably used one without thinking about it, which is exactly the point. When it works you take a ticket, park, pay, and leave. Behind each of those steps there is a reason the garage operator cares.

Trust and safety. Two cars in one spot is more than an inconvenience. It leads to arguments, blocked aisles, and sometimes damaged cars, and the operator is the one blamed.

Money. A garage earns its income when drivers pay on the way out. A double charge creates refunds and support calls, and a missed charge is income that is simply gone.

Traffic flow. A line of cars waiting at a gate backs up onto the street. If a gate takes ten seconds to answer instead of two, the queue outside gets noticeably longer at busy times.

Using the space well. An empty spot earns nothing, and a sign that says “full” when there are free spots turns customers away. A sign that says “free” when there are none sends drivers circling.

Staff time. Every wrong ticket and every stuck gate needs an attendant. Fewer mix-ups means fewer people needed at the gates.

What problem are we solving?

Put simply, the system has to answer one question at the entry gate and a different one at the exit gate.

At entry: “Which spot, if any, is free for this vehicle, and who owns it from now on?”

At exit: “What does this stay cost, has it been paid, and can the spot now go back to the pool?”

The input at entry is a vehicle arriving, with a type such as motorcycle, car or truck. The output is a ticket that names a spot, or a clear message that the garage is full. The input at exit is a ticket, or a plate number if the ticket is lost. The output is a fee, a payment, an open gate, and a spot that is free again. A sign near the entrance shows how many spots are left on each floor.

Success means three things. Every car in the garage has a spot of its own. Every stay is charged exactly once, for the time it really lasted. And the gates stay quick even on the busiest afternoon. Before we choose any technology we need to be precise about what the system must do and how well, because every design choice later in this page has to earn its place against those requirements.

This page is in the system design interview guides hub.

How to approach

In an interview you do not start by drawing boxes. You start by turning a short, vague prompt into a clear contract: which vehicles and spots exist, what the system must do, how well it must do it, and what is out of scope. Only then do you size the problem, make the design decisions one at a time, and draw the result. The list below is the order this page follows.

How to design a parking lot system in an interview

  1. Clarify the problem: vehicle and spot types, how a spot is chosen, when payment happens, whether reservations exist, how big the garage is, and how exact the sign must be.
  2. Write the functional requirements (what the system does) and the non-functional requirements (how fast, how safe, how big).
  3. Estimate the size: cars per day, cars per minute at the peak, number of spots, and how often the sign is read.
  4. Make the design decisions in order: who owns the truth about each spot, how a spot is claimed, how a spot is chosen, how a gate retry is handled, how a ticket moves through its life, how the exit charges once, how the sign gets its number, and how many garages fit together.
  5. Draw the picture those decisions produce, then walk one car in and one car out through it.
  6. Go deeper where the interviewer pushes: the exact claim step, retries, lost tickets, sensors that disagree with the records, and one production failure.

Clarifying questions (say these in the room)

In a real interview the prompt is only a few words: “Design a parking lot.” Before you design anything, ask questions until the problem is clear. Each answer below changes the design, which is why it is worth asking.

You: “Which vehicle types and spot types do we support, and are there special spots such as electric charging or accessible bays?”

Interviewer: “Motorcycle, car and truck. Spots are compact, regular and large, with a few charging and accessible spots.”

That answer forces you to separate two ideas. Physical fit is whether the vehicle can physically be parked in the spot (a car does not fit a compact bay). Policy is whether the vehicle is allowed there (a charging bay is kept for electric cars unless you declare an overflow rule). Keeping those two apart makes the rules much easier to explain.

You: “When we say ‘nearest available spot’, nearest to what: the main entrance, a zone the driver picks, or the lowest floor?”

Interviewer: “Define a policy. Consistency matters more than the exact choice.”

Now you can name a rule, for example the same zone first, then the lowest floor, then the lowest spot number. A rule like that only decides the order in which spots are offered. It does not change the fact that one spot must end up with exactly one car.

You: “Does the driver pay on exit or on entry, and is there a grace period before billing starts?”

Interviewer: “Pay on exit, with a short grace period.”

That fixes the order of the exit story: work out the fee at the moment of leaving, take the payment, then open the gate and free the spot. It also tells you the fee depends on how long the car stayed, so the entry time must be recorded reliably.

You: “Do we need reservations, or only walk-in cars? Can attendants override what the system decides?”

Interviewer: “Walk-in is required, reservations are optional, and attendants can override.”

Overrides become a proper, recorded action for attendants, not a footnote. Reservations stay optional, so you can mention them without designing them in full.

You: “Roughly how big is one garage, and how many cars arrive at the busiest time?”

Interviewer: “About a thousand spots, a few entry lanes, and a handful of cars a minute at the peak. The operator runs maybe a few hundred garages.”

These numbers feed the capacity estimate in the next section. They also tell you early that a single garage is a small problem in terms of raw traffic, so the hard part will be correctness and not speed.

You: “How exact does the spots-left sign need to be? Can it be a few seconds behind, as long as the gate itself never hands out a spot that is taken?”

Interviewer: “A few seconds behind is fine for the sign. The gate must never lie.”

This is the most useful answer in the whole conversation, because it says the sign and the gate have different accuracy needs. You will use that difference in a design decision later.

You: “I want to leave turn-by-turn navigation inside the garage, building a card payment network, and license-plate camera accuracy out of scope, so we can focus on spot contention, tickets and paying once. Does that match what you want?”

Interviewer: “Yes, focus on assignment and entry and exit.”

If the interviewer later asks about row locks, cache brands, or splitting many garages, you do not need to answer yet. Park those until the design decisions, where each one has a natural place.

Functional requirements

Functional requirements describe what the system does. From the answers above, a parking lot system must:

  1. Assign a compatible spot at entry and issue a ticket. The system looks at the vehicle type and the policy, picks a spot the vehicle can use, and gives the driver a ticket with the spot and a short direction.
  2. Track each stay from entry to exit. A ticket has a lifecycle, and the system must always know whether a stay is still open, paid, or finished.
  3. Work out the fee at exit. The fee comes from the entry time, a grace period, a rounding rule, and a policy for lost tickets or a maximum daily charge.
  4. Take the payment, then open the gate and free the spot. The spot must return to the pool after payment, and only once.
  5. Show how many spots are left. A sign or an app shows counts by floor and spot type.
  6. Support special spots and optional reservations. Accessible and charging bays have policy rules, and a reserved spot is held for a driver who has not arrived yet.
  7. Let attendants correct mistakes. An attendant can mark a spot out of service, release a spot, or look up a stay by plate when a ticket is lost, and every such action is recorded.

Non-functional requirements

Non-functional requirements describe how well the system must do its job. They are the numbers and promises that shape the design.

  1. Correctness of assignment. Two cars must never receive the same spot. Everything else in this page bends around this one promise, because a double assignment is visible to the driver and costs the operator trust.
  2. Fast gates. The gate should answer in under about two seconds, so the line of cars keeps moving. A slow card reader or a slow email must not hold up the next car.
  3. Safe retries. Gates, card readers and phones repeat requests when a network is slow. A repeated entry must not create a second ticket, and a repeated payment must not charge twice.
  4. Honest displays. The spots-left sign may be a few seconds behind. It must never be the thing that decides who gets a spot.
  5. Scale where it matters. One garage has thousands of spots and several lanes, and an operator may have hundreds of garages. A busy mall must not slow down every other garage.
  6. Recoverability and audit. When the payment provider is down or a sensor is wrong, a person must be able to fix the situation, and what they did must be written down.

Out of scope (and why you park these)

Write a short out-of-scope list on the board so the interviewer sees you can bound the problem.

Turn-by-turn navigation inside the garage. Showing a driver the way to spot 214 is a product feature. The interesting engineering question is giving spot 214 to exactly one car.

Building the card network or the secure card vault. You need payments that are safe to repeat, but you do not need to design a company like a card processor in this round.

Perfect camera recognition of every bay. A plate reader may exist at the gate. The design assumes the gate gets a vehicle id or a plate string, and focuses on matching a stay to a car and handling lost tickets.

City-wide routing between garages. Searching for parking near me can be a read-only service across garages. Giving out a spot always happens in the garage that owns it.

That is the requirements stage. If you want to practice it before reading on, try the requirements stage on Practice System Design (about 5–10 minutes), then come back for the sizing and the decisions.

Minute pacing (about 40 minutes)

MinutesFocus
0–5Clarify the problem; write functional and non-functional requirements; agree out of scope
5–12Capacity, then the design decisions and the high-level boxes
12–25One car in and one car out, then the claim step in depth
25–35Signs versus truth, failures, scale across garages
35–40One production story and questions

In the room (how you open): “I’d start by agreeing what the garage must do: which vehicle and spot types exist, how a spot is chosen, when the driver pays, whether reservations matter, how big it is, and how exact the sign has to be. I’ll write those down as requirements, size the problem, and then make the design decisions one at a time, so every box I draw has a reason.”

If you remember one thing: Ask first, write the requirements down, and only then design.

Capacity estimation

The requirements said a garage is small in traffic but strict about correctness, so the next step is to put rough numbers on it. That tells us whether we need a large distributed system or one careful database, and where the real difficulty is. These numbers are estimates to anchor the conversation, and you should say so out loud.

InputEstimateWhy it matters
Vehicles per day~2,000 for a busy garageA modest number of writes per day, so correctness matters more than raw speed
Peak arrival rate~5 cars a minute across all lanes, about one every 12 secondsLow compared to a flash sale, yet two cars still land inside the same few milliseconds often enough to double-assign
Spots per garage~1,000The list of spots is tiny, a few hundred kilobytes, and fits easily in one database
Stay records~2,000 a day, a few hundred bytes eachUnder a gigabyte a year per garage, so storage is not the problem
Sign and app readsMany, as often as every few secondsReads far outnumber claims, so the sign should read a small stored count
Exit payment bursts~10 a minute at the evening peakSafe repeats matter far more than fast fee arithmetic
Garages per operator50–500Each garage is its own unit, so there is no single row for the whole city

What the numbers imply

  • Correctness beats throughput. At five cars a minute any database is fast enough, so the design effort goes into never assigning one spot twice.
  • Counts are cheap and claims are precious. The sign can read a tiny stored count many times a second, while the act of giving out a spot is rare and must be exact.
  • Gate retries are normal. On weak networks a small share of requests, perhaps one to three in a hundred, will arrive twice, so entry and payment must be safe to repeat from day one.
  • One garage is small, a city is not. One database per garage is realistic. Across a few hundred garages the work must be split by garage, so a busy mall cannot slow the rest.

Checkpoint: What is the busiest write rate in this estimate, and why does it not need a large cluster?

If you remember one thing: You do not need national-scale queues, but you do need exact assignment when two lanes pick the same free spot.

Design decisions

We now know what the system must do and roughly how big it is. Now we choose. Each decision below answers one question the requirements raised, and each one rules out an easier idea that would not survive those requirements. Read them in order, because every decision builds on the one before it.

Decision 1: Who owns the truth about each spot?

The requirements said every lane must work from the same picture of the garage. The simplest idea is that each entry machine keeps its own list of free spots in its own memory. It is fast, it needs nothing else, and for a garage with one lane it would be exactly right.

It breaks as soon as there are two lanes. Lane A and lane B each hold their own list, and neither one hears when the other hands out a spot. Both lists say Spot 12 is free, so both machines offer it. That directly breaks the requirement that two cars never receive the same spot.

There are three ways out. The machines could keep telling each other what they handed out, but every message adds delay and there is always a moment when the lists disagree. You could make one lane the boss and send every request through it, but then that lane going down stops the whole garage. Or you could keep one record of every spot in a single place that every lane asks. We choose the last option, because it leaves exactly one place where the answer to “who owns Spot 12?” can be found. That place is a database, a program that stores records on disk and lets many callers read and change them safely. It is the source of truth for the garage: when anything else disagrees with it, the database wins.

Decision 2: How do we claim a spot so two lanes cannot both take it?

Once the truth lives in one database, the obvious way to use it is in two steps. The lane reads “is Spot 12 free?”, sees yes, and then writes “Spot 12 is now taken by this car.” The trouble is the gap between the two steps. If lane B reads in that gap, before lane A has written, it also sees “free”, and both write.

t0  Lane A reads Spot 12 status = AVAILABLE
t0  Lane B reads Spot 12 status = AVAILABLE
t1  A writes OCCUPIED     B writes OCCUPIED
    two tickets, one physical space

So reading and writing must happen as one indivisible step, where nothing can slip in between. The database offers this through a transaction, which is a group of steps that either all happen or none of them do. Inside a transaction we can also lock a row, meaning other transactions that want to change that row have to wait or step aside until we finish.

There are three ways to build the claim. We could lock the whole garage while one car claims, which is correct but makes all lanes queue behind each other. We could read, write, and retry if someone else changed the row first (called optimistic retry), which works but wastes effort exactly when the last spots are fought over. Or we could lock just the one spot row we want, and tell the other lanes to skip over any row that is already locked and take the next free one. That last choice is what the database calls FOR UPDATE SKIP LOCKED, and it spreads the lanes across different spots instead of lining them up. We choose it, and as a second safety net we add a rule to the data that says a spot can have at most one active stay, so even a bug cannot create two. The step-by-step version is in the deep dive.

Decision 3: Which spot do we offer?

Claiming a spot answers “how do we take one”, but not “which one”. The simplest answer is the first free spot in the table. That fails the requirement about vehicle types: a truck could be sent to a compact bay, and an ordinary car could be sent to an accessible spot.

So the choice has two layers. First, physical fit narrows the list to spots the vehicle can use: a motorcycle can use compact, regular or large, a car can use regular or large, and a truck can use only large. Second, policy narrows it further: accessible spots need a permit, and charging spots are for electric cars unless the garage allows overflow. Then a written ordering rule, such as the same zone first, then the lowest floor, then the lowest spot number, puts the remaining spots in order.

The important point is what policy does not do. It does not decide who wins a race. It only produces an ordered list of candidates, and the claim from Decision 2 then takes one candidate from the top of that list in one step. We keep physical fit and policy separate, because a physical rule is fixed while a policy rule changes whenever the operator changes its mind.

Decision 4: What happens when a gate sends the same request twice?

Gates, card readers and phones sit on networks that sometimes lose the reply. The entry request may succeed in the database, but the reply never reaches the gate. The gate waits, times out, and sends the request again. The simplest idea is to treat the second request as a new car. That creates a second ticket for one car, and one more spot looks taken.

The fix is for the gate to attach a unique label to each request, called an idempotency key, which is an id that lets the server recognise “this is the same request again”. For entry it might look like entry:{gate_id}:{request_id}. The server stores the key together with the ticket it created. When the same key arrives again, the server does not claim another spot. It returns the ticket it already made. Without this, an attempt to retry safely would still double-book, so the key is as important as the claim itself.

Decision 5: How does a ticket move through its life?

A ticket is not just a receipt. It is a record that changes over time, and the garage must always know what state a stay is in. The simplest idea is a single “paid” flag. That cannot represent a car that has entered but not paid, or a car that has paid but not yet driven out, and it lets a spot be freed at the wrong time.

So we make the ticket a small state machine, meaning a record that can be in one of a few named states and can only move along allowed paths. The states are OPEN when the car has entered, PAID when the fee has been confirmed, and CLOSED when the car has left and the spot has been freed. The paths only go forward, and a backward move needs an attendant, with a record of who did it and why. The spot goes back to the pool only on the move to CLOSED. That rule is what stops a spot from being given to a new car while the previous car is still parked there.

Decision 6: How do we charge exactly once at exit?

At exit the driver taps Pay. The simplest idea is to calculate the fee, send the charge to the card provider, and trust the answer. That fails the requirement that a retry must not charge twice, because a timeout looks exactly like a failure even when the charge went through.

The fee comes first. We calculate it from the server's clock, not the gate machine's clock, because a gate clock can be wrong and each gate could disagree. The rule is the time since entry, minus the grace minutes, rounded by a stated rule, with a daily cap for lost tickets. We calculate it once, store the amount and the version of the pricing rules on the stay, and reuse that stored amount on any retry. Then we send the charge to the provider with an idempotency key built from the stay itself, so the provider and our own records both recognise a repeat. Only after the provider confirms does the stay move to PAID and then CLOSED. Opening the gate before money clears is a product choice (pay later), and if it is allowed the unpaid amount must be recorded as a debt.

Decision 7: How does the sign know how many spots are left?

The sign must show a number quickly, and many people and screens read it. The simplest idea is to count the free spots in the database every time a screen asks. That would work for one screen, but it makes every sign refresh a read on the same database the gates depend on.

So we keep a small stored count for each floor and spot type, in a fast store called a cache (a small, quick copy of data kept near where it is read). The signs read the count, not the spot table. The count is derived from the spot table, so it can be rebuilt at any time, and it is rechecked on a schedule and whenever a spot changes state. It may be a few seconds behind, and the requirement said that is acceptable for the sign. What it must never do is decide who gets a spot. The gate always does a real claim on the database, so a count that says “0 left” means “probably full”, and a count that says “20 left” can never hand the same spot to two cars.

Decision 8: How do many garages fit together?

An operator may run hundreds of garages. The simplest idea is one big database and one big list of spots for the whole city. That fails the scale requirement: a busy mall on a Saturday would compete for the same rows and the same locks as every quiet garage.

Since a car only ever parks in one garage, nothing about assigning a spot in Garage A depends on Garage B. So we split by garage id, giving each garage its own set of spot and stay records, and its own database space or partition. A search such as “parking near me” can read across garages, but giving out a spot always happens in the garage that owns it. Operator-wide things such as reports and billing summaries are collected afterwards, not while a car waits at a gate.

Putting the decisions together

Taken together, the eight decisions are the design. Each garage keeps one authoritative record of its spots and stays. An entry request carries an idempotency key and asks for a compatible spot, ordered by policy. The database claims one spot in a single step and opens a ticket in the OPEN state. At exit, the fee is computed once from server time, the payment is made with a key built from the stay, and only then does the ticket move to PAID and CLOSED and the spot become free. The sign reads a small count that is rebuilt from the spot records. Garages are separate units, so one busy mall does not slow another.

In the room (a fuller opening you can actually say): “I’d keep one authoritative record of every spot in each garage, and I’d never let a gate keep its own free list. On entry, the gate sends a request with an idempotency key and a vehicle type. I’d build a list of compatible spots in policy order, then in one short transaction lock one candidate row, skipping rows another lane has already locked, mark it occupied, and open a ticket in the OPEN state with the server’s time. If the same key comes back, I return the same ticket. On exit I compute the fee once from server time, charge with a key built from the stay so a repeat charges nothing, then move the ticket to PAID and CLOSED and free the spot exactly once. The spots-left sign reads a cached count that I rebuild from the spot records, so it can lag but never assigns anything. Each garage is its own unit, so a busy mall cannot slow the others.”

The next section draws these decisions as one picture and shows who owns what.

High-level architecture

The decisions above were made one at a time. This section puts them on one page as a picture: which boxes exist, who owns what, and how a car's request travels through them. The deeper mechanics come later, so keep this at the level of a map.

What breaks if you merge everything

One program that assigns a spot, charges a card, updates the LED signs, emails a receipt and writes analytics, all while the car waits at the gate, means the driver waits for the slowest step. A card provider that is slow to answer should not stop the next car from entering.

The design also fails if each entry lane keeps its own list of free spots in memory, which Decision 1 ruled out. Lane A and lane B can both believe Spot 12 is free. Caching “20 regular spots left” without a way to rebuild it from the real spot records produces angry drivers who cannot find an open bay.

What works: separate claim, display, and payment

From the driver's point of view, entering means the gate prints a ticket with a real spot, and leaving means Pay works once and the barrier opens. Behind that, the design splits three jobs that must not share one slow path: claiming a spot for exactly one car, showing a fast spots-left number on the signs, and talking to the card provider. Each box below owns one of those jobs.

Who owns what:

  • Entry/Exit API. The door the gates talk to. Every request carries a unique label so a timeout retry is recognised as the same request (an idempotency key). It checks the vehicle type and the parking policy, then asks the parking service to claim or release a spot.
  • Parking service. Owns the rules for which spots a vehicle may use, how a ticket moves from open to paid to closed, and how the fee is calculated.
  • Authoritative database. The one place that truly knows who is in each spot and which stays are still active. The claim that assigns a spot runs here as one short all-or-nothing step (a transaction).
  • Availability cache. A small, fast copy of free counts per floor and spot type for the LED signs and apps. Those counts are rebuilt from the real spot rows and may be a few seconds behind.
  • Payment service. Sends the charge to the card provider, confirms success, and keeps payment records that are safe to send again after a timeout. It does not decide who owns a spot.
  • Attendant / admin API. The recorded tools staff use when something goes wrong: mark a spot out of service, free a spot by hand, or open a stay by plate when a ticket is lost.
[ Entry/Exit Gate ] --> [ Entry/Exit API ] --> [ Parking service ] --> [ DB (truth) ]
        |                      |                      |
        |                      |                      +--> [ Cache: free counts ]
        |                      |
        +--> [ Sensor events ]  +--> [ Payment provider ] --> [ Payment records ]
                                          (async confirm OK)

In the room: Draw the split. The database owns “who is in spot 12”, and the cache owns “how many regular spots are left on floor 2”. Entry always claims on the database, and signs may read the cache.

If you remember one thing: Assign against the truth, and display from a copy that is rebuilt from the truth.

Core design approaches

The picture shows what exists. Interviewers also want to hear that you looked at alternatives, so this section compares the choices that came up in the decisions. The tables below give the plain idea of each option, when it fits, and what to watch for.

Spot selection policies

PolicyPlain ideaGood whenWatch out
Nearest to entranceMinimize walking from a fixed gateSingle main entrance, simple UX“Nearest” undefined, so ask which entrance
Lowest floor firstFill lower levels before upperStructures where upper levels are premiumMay cluster traffic on one floor
Zone-basedDriver picks zone A/B/C; assign inside zoneLarge airports or stadiumsEmpty zones while others full, so you need an overflow rule
Type pool only“Any regular spot” without naming an id until the ticketFast gates, simple signsDriver needs clear directions after the claim

Whatever policy you pick, selection chooses candidates and one transaction claims exactly one row. A policy never replaces the claim.

Single garage vs many garages

ModelPlain ideaGood whenWatch out
Single garage serviceOne database partition per garageMall, airport terminalHot rows only within that garage
Multi-garage operatorMany garages, shared billing and reportingCity operator, chain garagesDo not centralize all spot rows on one shard
Federated searchA read-only aggregator across garagesApp shows “parking near me”Entry and exit writes still happen in the garage that owns the spot

Interview land: “Split the inventory by garage id. Browsing across garages is a read path, and a claim is always in the garage that owns the spot.”

Reservation vs walk-in

ModelPlain ideaGood whenWatch out
Walk-in onlyClaim an AVAILABLE spot at entrySimple interview scopeEvening rush races on the last spots
Hold then arriveRESERVED with an expiry until the driver checks inCharging or accessible spots are scarceExpired holds need a cleanup job
Mixed poolsA reserved pool and a walk-in poolOperators need bothPolicy for taking reserved spots when the garage is nearly full

For walk-in contention, use the same atomic claim as the last-slot booking in the vaccine booking guide: one transaction, one winner. For reservations, the move from RESERVED to OCCUPIED at check-in uses the same locking pattern.

If you remember one thing: Policy picks the candidates, and the database picks the one winner.

Data model

The decisions said what must be true, and now we need somewhere to keep it. You do not need a giant diagram, just enough tables to make the promises enforceable by the database itself, so that a bug in the application cannot break them.

Core entities

EntityKey fieldsRole
ParkingLotlot_id, name, address, pricing configThe split boundary
Floorfloor_id, lot_id, levelGroups spots
Spotspot_id, floor_id, type, status, featurescompact/regular/large; AVAILABLE/OCCUPIED/RESERVED/OUT_OF_SERVICE; EV, accessible
Vehiclevehicle_id, plate, typemotorcycle/car/truck
ParkingSessionsession_id, vehicle_id, spot_id, entry_time, exit_time, status, fee_amount, pricing_version, versionThe ticket: OPEN, then PAID, then CLOSED
Paymentpayment_id, session_id, amount, status, idempotency_key, provider refsSettlement that is safe to repeat
EntryRequestLog (optional)idempotency_key, session_id, gate_idRecognizes gate retries

Compatibility (physical fit)

Physical fit is simply “will this vehicle fit in that bay?” A motorcycle can use a compact, regular, or large spot. A car can use regular or large. A truck can use large only.

On top of fit comes policy: whether the vehicle is allowed there. Accessible spots need a permit flag, and charging spots are for electric vehicles unless the garage says ordinary cars may overflow into them.

Rules the database should enforce

  1. At most one active stay per spot. Use a partial unique index on spot_id for stays that are not yet CLOSED, meaning OPEN or PAID. A spot stays taken until the car has actually left.
  2. At most one active stay per vehicle. A car cannot be in two places, so use a unique index on vehicle_id where the stay is active.
  3. A ticket only moves forward. OPEN, then PAID, then CLOSED. A backward step needs an attendant action that is recorded.
  4. A payment is safe to repeat. The same idempotency_key returns the same outcome, and the provider's reference is unique.

The object-oriented class diagram should mirror these rules rather than replace them.

If you remember one thing: Four rules drive every table and API: one spot per stay, one stay per vehicle, a ticket that only moves forward, and a payment that is safe to repeat.

Detailed design

We know what is stored, so we can put it in motion. This section follows the two journeys you would draw on the whiteboard: a car entering and getting a ticket, then later paying and leaving. The goal is to make clear who decides, what becomes permanent, and what the gate shows at each step. After the two journeys comes the API view, which shows what the gates, the sign and the attendants actually call.

Entry flow (allocate a spot)

When a vehicle reaches the entry lane, the driver needs one thing that feels instant: a ticket, or an on-screen message, that names a real parking spot. Behind that moment the system does three careful jobs. First, it recognizes the vehicle type and any preferences the product allows, such as a floor, an accessible spot or a charging spot. Second, it picks a spot that is large enough and allowed by policy. Third, it claims that spot for this vehicle alone, so a second lane cannot be told the same spot is free.

The gate sends the request with an idempotency key—a unique label for this one entry attempt, for example entry:{gate_id}:{request_id}—so the server can recognise “this is the same request again.” That matters because flaky networks and double-taps are normal at barriers. If the same key arrives again, the service returns the same session and spot that already succeeded and never invents a second open stay for one physical entry.

Once the request is new, the parking service builds a short list of candidate spots: matching the vehicle type, available (or reserved for this reservation id), not out of service, ordered by the policy agreed earlier. Then it starts one database transaction that both locks and updates.

Inside that transaction the service asks the database for one available row using a locking read (FOR UPDATE SKIP LOCKED). That phrase means “lock this free row for me, and if another lane has already locked it, skip it and try another”. That is why two gates never wait on each other for the same row. When a free spot is found, the service marks it occupied, inserts a stay in the OPEN state with a server-side entry timestamp, and only then commits. The ticket returned to the gate includes session_id, spot_id, the floor, and short driving instructions.

If every candidate is gone or locked by others, the service returns a clear “garage full” message and never a made-up spot. The sign may still show a stale free count, and that is fine, because entry always tries a real claim and trusts the transaction, not the sign. There is a second style that some teams prefer: insert the OPEN stay and let a unique rule (“only one active stay per spot”) reject a double insert, then retry with the next candidate. Either story works in an interview, as long as you can show why two cars cannot both win.

  1. The gate sends the vehicle type and an idempotency key.
  2. A repeated key returns the existing ticket.
  3. The service lists candidate spots in policy order.
  4. One transaction locks a spot, marks it occupied and opens the stay.
  5. The gate prints the ticket, or the service says the garage is full.

Exit and payment flow

Exit is a different story with its own states. The driver presents the ticket (session_id), or a plate lookup is used if the ticket is lost. The service loads that stay. If the stay is already paid and closed, it returns the previous outcome, because payment confirmation messages also retry and charging twice for one visit destroys trust.

If the stay is still open, the service computes the fee from server time, not from the phone or gate clock. That means the duration since entry, minus the grace minutes, rounded by the product rule (per minute or per started hour), with a stated rule for lost tickets and daily caps. The fee is calculated once and the amount and the version of the pricing rules are stored on the stay, so a mid-day rate change does not silently change a stay that already has a quote.

Payment is sent to the card provider with its own idempotency key, built from the stay itself, such as pay:{session_id}. Only after the provider confirms success does the stay move to PAID and then CLOSED, and only then does the spot become AVAILABLE again. Opening the gate before money clears is a product choice (pay later), and if you allow it you must track the unpaid amount as an explicit debt. Do not casually free the spot and hope the payment finishes later unless you are ready to explain that debt model.

Receipts and analytics can leave asynchronously after the critical path is safe. The driver's mental model stays simple: ticket in, pay once, gate opens once, spot frees once.

Availability reads

Screens that say “47 free spots” belong to the display path, not the claim path. They read stored counts or a summary table refreshed every few seconds. That lag is fine for a human driving past a board. It is not fine for the entry call, which must always attempt a real claim. In the room, say: “Signs can be slightly wrong, and entry can never assign a ghost spot.”

In the room (spoken): “On entry I claim one compatible spot in a single database transaction, create an open stay with server time, and return a ticket. Retries reuse the same idempotency key so I never open two stays for one gate request. On exit I compute the fee once from server time, charge once with a key built from the stay, then close the stay and free the spot, never the reverse unless we explicitly support pay-later.”

API design: what gates, signs and attendants call

The parking lot system has a small, state-driven API. It covers three things: the calls the gates make, what each response contains, and the calls that attendants and signs use.

The internal calls. Inside the parking service, two functions do the real work. Given a vehicle type and an idempotency key, the first returns a ticket or a “full” answer. Given a ticket and a payment key, the second returns a receipt or an error.

EndpointRole
POST /v1/entryAllocate a spot and create an OPEN stay; requires an Idempotency-Key
POST /v1/exitCompute the fee and start or confirm payment
POST /v1/payments/confirmConfirm payment for a stay, safe to repeat
GET /v1/availabilityCounts by floor and spot type (may be a few seconds old)
POST /v1/spots/{spotId}/overrideAttendant action: mark OUT_OF_SERVICE or force AVAILABLE (recorded)
GET /v1/sessions?plate=Lost-ticket lookup (rate-limited and recorded)

What the sign and apps receive. GET /v1/availability returns counts and takes a few filters.

ParamRole
lotIdWhich garage
floorIdOptional filter
spotTypecompact / regular / large
featuresev, accessible
Gate → POST /v1/entry (Idempotency-Key)
  → parking.allocateSpot(txn: SKIP LOCKED)
  → createSession(OPEN)
  → 201 { session_id, spot_id, floor }

Gate → POST /v1/exit
  → computeFee(session)         (once; stored on the stay)
  → payments.confirm(key = pay:{session_id})
  → session PAID → CLOSED; spot AVAILABLE
  → 200 { receipt }

Status codes and errors. A 409 means no compatible spot, so the garage is full. A 402 means payment is required before the gate opens. A 404 means the stay is unknown. A 429 means the gate or the lookup is being rate-limited. A repeated Idempotency-Key returns the same body as the first success, so a retrying gate cannot tell the difference and does not need to.

The attendant API. The override call is an audited action for a person with the right role. It records who acted, when, and why, because an attendant who frees a spot with a car still in it is exactly the kind of mistake you will need to trace later.

If you remember one thing: Entry assigns, exit settles, and payment confirms safely on repeat, so three calls drive one lifecycle.

Deep dive: the questions an interviewer asks next

You have drawn the design and walked the car in and out. This is the point where a good interviewer starts digging, and the questions usually come in a fairly predictable order, because each answer raises the next one. Read this section as that conversation. Each question is followed by an answer you can give, and a hint of where the interviewer is likely to go next. When the next question is obvious from what you just said, you can lead with that answer instead of waiting to be asked.

“Two cars arrive at the same instant. Walk me through what could go wrong.”

Start with the version without the one-step claim, because it is the clearest way to see why the claim is needed.

t0  Lane A reads Spot 12 status = AVAILABLE
t0  Lane B reads Spot 12 status = AVAILABLE
t1  A writes OCCUPIED + inserts session SA
t1  B writes OCCUPIED + inserts session SB
    two tickets, one physical space

Both lanes read “Spot 12 is free” before either one wrote, so both believed they could take it. Other things go wrong in the same way. The gate times out after the commit and retries /entry without an idempotency key, which produces two stays for one car. An exit confirmation retries, which produces a double charge, or a double release that frees a spot while a car is still parked there.

Where it goes next: the interviewer will ask what the fixed version looks like.

“What does the fixed version actually do?”

The fix puts the read and the write inside one transaction, and locks the one row that is being claimed.

BEGIN
  SELECT spot_id FROM spots
    WHERE lot_id = ? AND type compatible AND status = AVAILABLE
    ORDER BY policy
    LIMIT 1
    FOR UPDATE SKIP LOCKED
  IF no row → ROLLBACK → 409 garage full
  UPDATE spots SET status = OCCUPIED
  INSERT parking_sessions (spot_id, status=OPEN, entry_time=utc_now())
  COMMIT → return ticket

To see the race closed, imagine lane A and lane B running this at the same moment. A's transaction locks Spot 12. B's transaction asks for the first free row and finds Spot 12 locked, so it skips it and locks Spot 13 instead. Each lane gets its own spot, and neither waits for the other. If only one spot is left, lane B finds no free unlocked row, rolls back and returns 409 immediately instead of waiting.

Pair the claim with three safety nets: an Idempotency-Key on entry so a retry returns the same stay, a unique rule that allows only one active stay per spot, and a payment that is safe to repeat.

Two entry lanes racing for Spot 12: naive read-then-write assigns both; FOR UPDATE SKIP LOCKED plus one OPEN session per spot yields one winner

Figure: The sign may say “1 left”, but the claim on the primary database decides the single winner.

Where it goes next: the interviewer will ask why you did not simply lock the whole garage.

“Why not lock the whole garage, or the whole floor, while one car claims?”

Because each larger lock fails against the gate-speed requirement.

  • Locking the whole garage is correct, but it makes every lane queue behind every other lane, and a slow claim holds up all of them.
  • Locking a floor helps a little, but a popular floor on a Saturday still becomes one queue.
  • Reading and retrying (optimistic retry) works, but at the end of the day, when only a few spots remain, many lanes retry on the same few rows, and the retries add load exactly when the garage is busiest.

Locking just the one row, and skipping rows that are already locked, spreads the lanes over different spots and costs one short transaction.

Where it goes next: the interviewer may offer the simpler idea of a unique rule only.

“Could a unique rule do the job without any locking?”

Yes, and it is the second style mentioned earlier. The service inserts an OPEN stay for the chosen spot, and the database refuses the insert if the spot already has an active stay. When the insert is refused, the service tries the next candidate. It is simpler to reason about, but it costs a failed insert for every collision, so under heavy contention the row lock with SKIP LOCKED is smoother. Many teams use both: the lock for the normal path and the unique rule as a last line of defense that makes a double assignment impossible even if the application has a bug.

Where it goes next: “What if the gate retries after the commit?”

“The gate times out after the commit and tries again. What happens?”

The first request already succeeded, so the retry must not claim a second spot. The idempotency key solves it: the service stores key → session_id in the same transaction as the claim. When the retry arrives with the same key, the service finds the stored stay and returns the same ticket. Because the key is saved with the claim and not afterwards, there is no moment where the stay exists and the key does not.

Where it goes next: “And the same thing at payment?”

“How do you stop a double charge when the card reader retries?”

A timeout does not mean the charge failed, so the service never decides by guessing. It computes the fee once and stores the amount and pricing version on the stay. Then it sends the charge with a key built from the stay (pay:{session_id}), and the provider treats a second request with that key as the same charge and returns the first result. Our own payment record also keeps a unique idempotency_key and the provider reference. If a retry arrives for a stay that is already PAID, the service returns the earlier receipt without calling the provider again. The spot is released only on the move to CLOSED, which happens once.

Where it goes next: “Why is the sign allowed to be wrong, and how wrong can it get?”

“The sign says 20 free but the garage feels full. How did that happen, and how do you contain it?”

The sign reads a stored count, and a stored count can drift from the spot records. Out-of-service spots may still be counted as free, an attendant override may not have updated the count, or a sensor may have lagged. The defence is to derive the count only from the spot status, rebuild it on a schedule (for example hourly) and on every state change, and alert when the stored count and the derived count differ by more than a set amount. Entry never depends on the count, so even a wrong sign can only send a driver to a garage that then says “full”, and it can never put two cars in one spot.

Where it goes next: “What if the sensor and the database disagree?”

“A sensor says a spot is empty, but the database says a paid stay is still open. Who is right?”

Neither one automatically. Treat sensor messages as hints that can arrive twice or late, not as the truth. The database reflects who legally holds the spot, which is whoever has an active stay. If the two disagree, the system flags it for an attendant to check, and does not silently overwrite a paid stay. A reconciliation job compares the sensor stream with the stay records and opens a ticket for a person when they differ, and the team tracks how often they differ per floor.

Where it goes next: the interviewer may now leave the core path and ask about product edge cases.

“What about a lost ticket, a reservation, or a valet?”

A lost ticket is a lookup by plate that finds the active stay, with a daily cap on the fee and a recorded attendant approval. A reservation holds a spot with an expiry. The same claim code handles both, moving RESERVED to OCCUPIED for a reservation and AVAILABLE to OCCUPIED for a walk-in, and a scheduled job returns expired holds to the pool. Valet is a different entry channel that uses the same claim call from an attendant's app, with the car keys tracked separately. It is the same pool of spots, not a second garage with its own copy.

Say it in the interview: “One short transaction locks one candidate spot, skips rows another lane holds, marks it occupied and opens the stay with server time. The key for the request is stored with the stay, so a repeat gets the same ticket. The sign reads a rebuilt count and never assigns anything.”

Scale and hot rows are covered in Scaling the system, and the checks on payment and drift are in Observability and Bottlenecks and tradeoffs.

If you remember one thing: The deep dive is a conversation. Read then write is the red flag, one transaction with a row lock is the fix, and each answer is something you could say before they ask.

Key challenges

The deep dive showed that the core step is simple once it is a single transaction. What makes a real garage hard is everything around that step. The table lists the hard parts, what a driver sees when each one goes wrong, and what to say about each in the interview.

ChallengeWhat users see if it goes wrongWhat to say in the interview
Double assignmentTwo cars, one spot; arguments and liabilityRow lock or a unique active stay per spot; never read then write across separate requests
Gate retriesDuplicate tickets; inflated occupancyAn Idempotency-Key on entry mapped to the stay
Stale availability“20 free” but the garage feels fullCounts derived from spot state; rebuild and alert on drift
Payment retryA double charge at exitA payment key built from the stay, plus a unique provider reference
Policy vs fitA truck in a compact spot, or a petrol car in a charging baySeparate physical fit from policy flags
Lost ticketA long exit line and arbitrary feesPlate lookup, a daily cap, and a recorded manual override
Sensor driftThe database says empty and the bay is occupiedReconcile and ask an attendant; never let a sensor blindly overwrite

Correct spot assignment matters more than a clever pricing engine. Drivers forgive a slow sign, but they do not forgive two tickets for one space or a double charge.

Scaling the system

Those hard parts get worse as the number of cars and garages grows, so the next question is what happens when the system gets bigger. You do not have to wait for the interviewer to ask. Right after you finish the design, say the scaling story yourself, then be ready for the follow-ups.

What you can say upfront: “One garage is a small problem in raw traffic, so I’d keep each garage’s spots and stays together in one database, split by garage id. A busy mall then competes only with itself, and a city of garages is just many independent units. Inside a garage, the row lock with skip-locked spreads the lanes over different spots instead of lining them up behind one counter. Signs and apps read a stored count or a read copy, while entry and exit always write to the garage’s main database, so a claim never uses stale data. Slow work such as receipts, rebuilding counts and expiring reservations runs in the background after the claim commits.”

That one paragraph answers most of what follows. Here are the follow-ups, in the order they usually come.

Interviewer: “The operator buys fifty more garages. What do you change?”

You: “Very little, and that is the point of splitting by garage id. Each new garage gets its own spot and stay records, and no existing garage's claim depends on it. A search across garages is a read path that gathers answers from each one. Reports and billing summaries are collected afterwards, not while a car waits at a gate.”

Interviewer: “Saturday afternoon, all four lanes are busy. Doesn't the lock make them queue?”

You: “Not for different spots. Each lane locks a different row, so they run side by side. The skip-locked rule means a lane never waits for a row someone else holds, it just takes the next free one. The real queue only appears when the garage is nearly full and every lane scans the same few rows, which is why I would index the candidate query and stop early when the stored count says there is nothing left.”

Interviewer: “Can the sign read from a replica to take the load off?”

You: “Yes for the sign, and no for the claim. A read copy lags behind the main database by a short time, which is fine for a count shown to a passing driver. A claim on a lagging copy could hand out a spot that was just taken, so entry and exit always write to the main database of that garage.”

Interviewer: “What about hot rows inside one garage?”

You: “The popular floor creates contention on many rows, not one. Because each lane takes a different row, the load is spread out. I would watch the claim time and the rate of ‘garage full’ answers per garage, because a jump in full answers while real occupancy is low points to a drifting count or a policy filter that is too narrow, not a real capacity limit.”

Interviewer: “Is multi-region needed?”

You: “Rarely. A garage lives in one place, so its data lives in one region. Operator dashboards can combine data from regions a little later, because a report that is a minute old harms no one.”

If you remember one thing: Split by garage, write on the main database, read from copies, and do slow work after the commit.

Failure handling

Scaling answers “what if there is more of everything”. This section answers “what if something breaks”. Again, say it first. Failures in a garage come from the database, the card provider, the sensors and the people at the gates, and what impresses an interviewer is that each answer was decided before the failure happened.

What you can say upfront: “Every failure has a decision made in advance. If the database is slow or the claim cannot complete, I close new entry rather than guess at a free spot, because a closed gate is annoying but two cars in one spot is a safety and liability problem. If the card provider is down, the stay stays open, the spot stays occupied, and an attendant can let the car out with a recorded override. If the sign cache is lost, I rebuild it from the spot records and entry keeps working. Time always comes from the server, never from the gate machine. Every override is written down with who, when and why.”

The follow-ups are about the details of those decisions.

Interviewer: “The database is slow at entry. What does the driver see?”

You: “A gate that waits, and a queue that grows behind it. I keep the transaction short, give the claim a timeout, and make the retry safe with the idempotency key, so a request that actually succeeded but looked slow does not create a second ticket. I never commit the spot without the stay, so there is no half-finished state to clean up. If the database is unhealthy and I cannot be sure of the claim, new entry fails closed.”

Interviewer: “The card provider is down and cars are lining up at exit.”

You: “The stay stays OPEN and the spot stays OCCUPIED, because we only free a spot after a confirmed payment. An attendant can open the gate with a recorded override, which creates a debt that is collected later. That keeps the line moving without pretending the money arrived.”

Interviewer: “The sign cache is wiped.”

You: “Signs go blank or show a wrong number, but entry still works, because it claims on the main database and never reads the cache. I rebuild the counts from the spot table and then keep them fresh with the state-change events.”

Interviewer: “A sensor sends the same event three times.”

You: “I remove duplicates using the sensor id and event id, and I compare the result with the stay records, so a flickering sensor cannot flip a spot's status back and forth.”

Interviewer: “The clock on a gate machine is wrong.”

You: “It cannot change a fee, because the entry time is taken from the server in UTC. The gate's clock is stored only as extra information.”

Interviewer: “An attendant frees a spot while a car is still in it.”

You: “That is a human mistake, so the override is recorded with who and why, and an optional sensor alert can tell the attendant that the bay still looks occupied. The reconciliation job also compares the sensor stream with the stay records, so a bay that still reports a car while no active stay exists is flagged for a person. Without that check, the next car could be sent to an occupied bay, and a driver would be the one to report it.”

ScenarioWhat the user seesWhat to build
Database slow at entryGate spinner; queue backs upShort transaction; timeout with a safe retry using the idempotency key; never commit a spot without a stay
Payment provider downCannot exit automaticallyAttendant override with a recorded debt; stay stays OPEN; spot stays OCCUPIED
Duplicate sensor eventFlickering spot statusRemove duplicates by sensor id and event id; reconcile against stay records
Cache lostSigns blank or wrongRebuild counts from the spot table; entry still works from the main database
Clock skew on a gate deviceWrong feeServer UTC for entry time; device clock is advisory only
Attendant frees an occupied spotSpot looks free while a car is presentRecorded override; optional sensor alert

If you remember one thing: When assignment correctness is uncertain, fail closed on new entry rather than guess a free spot.

Observability (what you measure)

Once the garage is live, you need a way to tell whether it is healthy, and that takes more than one number. Do not watch only the success rate of the entry API. That misses double assignments and a sign that has drifted away from the truth.

SignalWhy it matters
entry.claim latency p99 (how long the slowest 1 in 100 claims take)The gate's speed promise; long transactions block lanes
entry.conflict / 409 rateSeparates a truly full garage from stale policy or drift
spot.double_open_sessionsShould always be zero, so alert at once
cache.count_drift per floorThe absolute difference between the stored count and the count derived from spots
payment.duplicate_idempotency_hitsShows retries being absorbed safely, or a bug if it jumps
exit.payment_failure_rateCard provider or network pain at the evening peak
override.count by attendantOperational load and distrust of sensors

Alert ideas: any spot with two active stays; drift above the threshold for ten minutes; a payment confirmation with no matching OPEN stay; a spike in entry retries that arrive without idempotency keys.

If you remember one thing: Measure promises that were broken (a double stay, a negative free count), not only whether the HTTP call succeeded.

Security and abuse

A parking system hands out something of value—a spot and a gate opening—so this section covers how to keep it honest after the design is in place. Gate devices and attendant tools must prove who they are before they can create a ticket or free a spot, so a random caller on the network cannot mint stays. Entry and plate-lookup calls should be rate-limited so nobody can scan for open stays. The unique request labels on entry should be hard to guess and tied to one gate. Payment calls use the same sign-in as the exit kiosks, and tokens from the card provider stay encrypted at rest. Attendant overrides need the right role and a record that cannot be quietly edited afterwards, showing who acted, when, and why. Prefer stay ids over full card numbers or plates in searchable logs. Stolen gate credentials need a fast revoke-and-replace path that does not disturb the garage's spot and stay records.

Cost awareness

Every choice so far also has a price, and interviewers like to hear that you noticed. Every double booking wastes attendant time, refunds and trust. Every stale “20 free” sign wastes circling traffic and complaints, which is an operator cost more than a computing cost. Keeping the sign count in a cache is cheap, and rebuilding it regularly is cheaper than the cost of drivers blocking aisles. Payment retries without idempotency create support tickets that cost more than the parking fee. Splitting by garage means one very busy mall does not force a city-wide database upgrade. Sensor events cost storage, so sample them and remove duplicates rather than writing every flicker to the main path.

Green Dashboard. Angry Users. The Production Mindset System Design Interviews Expect.

Everything so far describes how the garage should work on a good day. This section is about what happens on a bad day, told as short stories from the people who carry the pager (the on-call engineers). Textbooks teach boxes and arrows. On-call teaches something else: the dashboard can look fine while drivers are furious.

Four nightmares that look fine on a dashboard:

What the dashboard showsWhat is actually happening
Entry API success is 100%Signs are showing “20 free” while every level is packed
Entry API success is 100%Gate retries are creating duplicate tickets
Payments are succeedingThe same stay was charged twice and refunds are piling up
Fees look normalA gate with a wrong clock is producing negative or odd durations

Scene 1: Availability says 20 free, but the garage feels full

The moment: It is a Saturday rush. The LED signs show open spots, and drivers circle for twenty minutes. Attendants radio that level 3 is packed.

The trap: The small free-count numbers shown on the signs drifted away from what the database knew. Spots marked out of service were still counted as free, attendant overrides did not refresh the counts, and sensors lagged, so occupied bays still looked open on the board. The metric that lied was the entry success rate, because entry never reads the sign and can look perfectly healthy while drivers circle.

What to build: Build every free count only from each spot's real status in the database, rebuild those counts on a schedule and whenever a spot changes, and alert when the stored number and the rebuilt number drift apart. Keep the gate claiming on the main database so the sign stays a hint for drivers, never the thing that hands out a spot.

Scene 2: Gate retries create duplicate stays

The moment: One vehicle has two printed tickets. Occupancy is off by one, and there is a billing dispute at exit.

The trap: The first entry call already saved the stay, but the network reply never reached the gate. The gate timed out and sent POST /entry again with no unique request label (no idempotency key), so the backend treated it as a new car and opened a second stay for the same vehicle.

What to build: Require every entry call to carry an idempotency key, and store that key with the stay in the same step as the claim, so a retry returns the first ticket instead of inventing a second one. Also enforce a database rule that a vehicle can have only one active stay at a time, as a last line of defence.

Scene 3: A double charge at payment confirmation

The moment: A card is charged twice for one stay. The support queue spikes, and finance runs manual refunds.

The trap: After a slow card reader, the confirm call was sent again. The card provider treats repeats as normal, but on our side each retry created a brand-new charge row, so one stay was billed twice.

What to build: Work out the fee once, store that amount on the stay, and send the charge with a key built from the stay so a replay returns the same receipt. Keep the provider's reference unique on our payment record, and free the spot only after payment has clearly succeeded.

Scene 4: Clock skew breaks pricing

The moment: A receipt shows a negative duration, and a fee jumps at the daylight-saving change. A driver argues at the kiosk.

The trap: The entry time written on the stay came from the gate machine's own clock, and receipts mixed local time zones, so a slow or wrong gate clock produced nonsense durations and odd fees around daylight-saving changes.

What to build: Take every stay timestamp from the server's clock in UTC, keep the gate's device time only as extra notes for debugging, and add tests that cover the daylight-saving boundaries so fee math stays stable.

In the interview: Pick one scene and tell it like a short story: what people felt, which metric lied, and one fix such as a state machine, an idempotency key or a unique rule, not just “we would monitor it”.

Bottlenecks and tradeoffs

Those stories all trace back to a small number of choices where you cannot have both things you want. Interviewers listen for whether you can name the tension, say what breaks, and pick a side on purpose. Here are the three that matter most for a parking lot system.

Exact occupancy vs fast displays

The tension — Drivers want instant sign updates, but exact per-spot truth on every sign is expensive and is still a few seconds stale.

What breaks — Treating the display count as the source of truth for assignment.

What teams do — Claim on the main database, keep approximate counts for the boards, and reconcile all the time.

Say in the interview — “Signs lag, and entry never lies.”

Row lock contention vs garage-full latency

The tension — FOR UPDATE SKIP LOCKED spreads lanes over rows, but when the garage is truly full, every lane scans the candidates and fails.

What breaks — Long entry latency at 99% occupancy if the candidate query has no index.

What teams do — Index (lot_id, type, status), stop early when the derived count is zero, and keep transactions tiny.

Say in the interview — “Index the candidate query, and fail fast when policy says full.”

Pay on exit vs pay on entry

The tension — Exit payment matches the real stay length, while entry prepayment speeds up the exit but makes refunds messy.

What breaks — Releasing the spot before payment on exit if confirmation is slow, so another car is assigned while the first one is still parked.

What teams do — Pay on exit by default with a payment that is safe to repeat, and optional prepayment with an explicit “spot held until paid” policy.

Say in the interview — “I release the spot only after payment succeeds, unless an attendant's pay-later is explicit.”

If you remember one thing: The bottleneck is usually correctness under retry, not requests per second.

Interview tips

You now have a full design and the tradeoffs behind it, so the last thing to practice is defending it when the interviewer pushes back. These five are the pushes that come up most after you finish the design:

“Nearest available spot”

In the room

You might say: “When a car arrives, we give it the nearest free spot.”

Interview Push: “Nearest to what: the main entrance, the elevator, or the driver's chosen zone?”

Land here: “Nearest” is not a feeling; it is a written ordering rule you agree with the interviewer—same zone first, then the lowest floor, then the lowest spot number, or walking distance from a fixed entrance. That rule only sorts the candidates. The claim still takes exactly one spot in one short database step.

Source of truth for availability

In the room

You might say: “We keep the free spots in a fast cache so the gates answer quickly.”

Interview Push: “Two entry lanes both see Spot 12 free. Who wins?”

Land here: Who is in Spot 12 lives in the database, claimed in one all-or-nothing step or protected by a unique rule of one active stay per spot. The fast cache only powers the displays; those counts can lag a few seconds but must be rebuilt from real spot status. Signs never assign a spot—entry does.

Concurrency and locks

In the room

You might say: “We put a lock around the assignment.”

Interview Push: “What exactly is locked: a spot, a floor, or the whole garage?”

Land here: Lock only the one spot you are about to take, and tell other lanes to skip a row that is already locked and try the next free one (SELECT … FOR UPDATE SKIP LOCKED). As a safety net, also enforce one active stay per spot in the database. Pair both with a unique request label on entry so a gate retry returns the same ticket instead of opening a second stay.

Pricing and time

In the room

You might say: “The fee is the hours stayed times the hourly rate.”

Interview Push: “What about a grace period, rounding by minute or by hour, and a lost ticket?”

Land here: Say the fee rules out loud: grace minutes before billing starts, how you round (per minute or per started hour), and a daily cap when a ticket is lost. Take stay times from the server's UTC clock, not the gate machine. Work out the fee once, store it on the stay, and key the payment on that stay so a retry charges the same amount again—not a second, different one.

Overrides and messy reality

In the room

You might say: “The sensors always tell us whether a spot is free.”

Interview Push: “A spot shows available but a car is physically there. Now what?”

Land here: Give attendants a recorded override path—mark a bay out of service, force-release a spot—with who acted, when, and why written down. Treat sensor messages as hints that may arrive twice or late, and compare them to the stay records instead of pretending the hardware is always right.

After each push, name one real mechanism, such as a row lock, an idempotency key, a unique rule or a reconciliation job, not “we'll handle it”.

What should stick

After working through the requirements, the decisions and the depth sections, you should be able to explain:

  1. Rules first — One active stay per spot, one charge per exit, and a ticket that only moves forward, stated before any class diagram.
  2. Truth vs display — The database owns who is parked, and signs and caches can lag and are rebuilt from the truth.
  3. Claim in one step — Two cars must not both win the same spot, so lock one candidate row and skip rows another gate already holds.
  4. Retries must be safe — Entry and payment retries must not create duplicate tickets or charges.
  5. The messy world is normal — Sensors drift, attendants override, and tickets get lost, so design recorded paths to fix them.

Tell it in the room: “I define the vehicle and spot rules first. Entry claims one compatible spot in one transaction and opens a stay. Exit computes the fee once from server time, pays once, then releases the spot. Availability displays use cached counts rebuilt from spot state, never the other way around.”

Key Takeaways

  • Keep one authoritative record of every spot per garage; a private free list at each gate lets two cars receive the same spot.
  • Claim a spot in one transaction by locking a single candidate row and skipping rows another lane holds, backed by a unique rule of one active stay per spot.
  • Treat the ticket as a state machine, OPEN then PAID then CLOSED, and free the spot only when the stay closes.
  • Make entry and payment safe to repeat with idempotency keys, and compute the fee once from server time.
  • Let signs read counts rebuilt from spot status; they can lag, but entry always claims on the database.
  • Split inventory by garage id so a busy mall never slows the rest of the city.
  • Measure broken promises (double stays, count drift, duplicate payments), not only whether requests succeeded.

Quick revision notes

The problem in your own words. A parking lot system decides which spot each arriving car gets, tracks the stay, and charges once on the way out. The hard part is that several lanes must never give the same spot to two cars, and a retried request must never create a second ticket or a second charge.

The design in one breath. Each garage keeps one authoritative record of its spots and stays. Entry carries an idempotency key, lists compatible spots in policy order, and in one transaction locks one candidate row, skipping rows another lane holds, marks it occupied and opens a stay with server time. Exit computes the fee once, charges with a key built from the stay, moves the ticket to PAID and CLOSED, and frees the spot once. Signs read counts that are rebuilt from the spot records.

The choices you must be able to defend. A row lock with skip-locked on the normal path and a unique rule as the safety net. Counts for signs and claims on the database for assignment. Pay on exit with a stored fee. When the database is unsure, close new entry instead of guessing. Split inventory by garage id.

The numbers worth remembering. About 2,000 cars a day and about 5 a minute at the peak for one busy garage, about 1,000 spots, a gate answer in under about 2 seconds, and 50 to 500 garages per operator, all estimates. One to three in a hundred requests may arrive twice on weak networks.

The mistakes that cost points. Reading “free” and writing later in a separate step, letting a gate keep its own free list, trusting the sign for assignment, retrying a payment without a key, taking times from the gate clock, and freeing a spot before the payment is confirmed.

Frequently asked follow-ups

  • How do you assign a spot without double booking?
  • How do you handle concurrency at multiple entry gates?
  • Walk through entry and exit with payment.
  • How do you show availability when the lot is almost full?
  • How does this scale to many independent parking lots?

Deep-dive questions and strong answer outlines

How do you assign a spot without two cars taking the same space?

I would not read “spot is free” and update later in a second request. Inside one short database transaction, pick a compatible candidate spot, lock that row with SELECT … FOR UPDATE SKIP LOCKED, flip status to OCCUPIED, and insert a ParkingSession with status OPEN. The second lane skips the locked row and tries the next candidate—or returns “lot full” if none remain. Optionally enforce a partial unique index: only one OPEN session per spot_id. Pair with an Idempotency-Key on entry so gate retries do not create two tickets for one vehicle.

How do multiple entry lanes coordinate on the same lot?

Each lane calls the same entry API backed by one authoritative database for that lot. Allocation is row-level, not “each gate keeps its own free list.” Fast “spots remaining” signs read from cached counters rebuilt from spot state, but the claim always hits the primary. If two lanes race, one transaction wins; the other gets the next spot or a clear “full” response. For very large garages, shard by lot_id so one mall does not serialize the whole city.

Walk through entry and exit with payment.

Entry: vehicle type and optional preferences → find compatible AVAILABLE spots → atomic claim → create OPEN session with server UTC entry_time → return ticket (session_id, spot_id, directions). Require Idempotency-Key so a timeout retry returns the same session. Exit: lookup by session_id or plate (lost ticket) → compute fee from entry_time with stated grace and rounding rules → create/confirm Payment with idempotency key → on success transition session OPEN → PAID → CLOSED → release spot to AVAILABLE exactly once. Do not release the spot before payment succeeds unless you explicitly allow pay-later with attendant override.

How do you handle a full lot signal at the gate?

The gate needs a fast answer, but “full” must be honest enough. Maintain derived counters per floor and spot type from the spot state machine (AVAILABLE, OCCUPIED, RESERVED, OUT_OF_SERVICE). Entry still does a real claim in a transaction—cached zero means “probably full,” not a guarantee. Reconcile counters hourly or on state change events; alert when abs(cached − derived) exceeds a threshold. Stop admitting when no compatible spot can be claimed, not only when a stale counter says zero.

How does this scale to many parking lots?

Shard by lot_id: each garage (or operator region) has its own service boundary and database partition. Cross-lot search is a read aggregator; entry and exit writes stay on the lot that owns the spots. Hot rows appear per popular lot at peak, not one national inventory row. Multi-lot operators share payment and reporting asynchronously; they do not merge spot assignment into one global counter.

AI feedback on your design

After a practice session, InterviewCrafted summarizes strengths, gaps, and interviewer-style expectations—similar to a written debrief. See a static example report, then practice this problem to get feedback on your own answer.

FAQs

Q: Is this only an object-oriented design question?

A: Many interviews start with entities and state machines—that is fair. At InterviewCrafted depth, treat it as system design with concurrency: invariants, transactional assignment, idempotent gates, and how displays relate to truth. Say your classes aloud, then show the database mechanism that stops two cars in one spot.

Q: How do reservations work alongside walk-in entry?

A: Reservations hold a spot (or a spot type pool) with a TTL before arrival. Walk-in entry claims from AVAILABLE spots not held or expired. Use the same atomic claim path for both: RESERVED → OCCUPIED on check-in, or AVAILABLE → OCCUPIED for walk-in. A nightly job frees expired holds back to AVAILABLE. In the interview, separate hold inventory from walk-in inventory early so flash walk-in traffic does not steal reserved EV spots without policy.

Q: What if IoT sensors disagree with the database?

A: Treat sensor events as at-least-once hints, not the sole source of truth. The database reflects legal occupancy (ticket OPEN). If a sensor says occupied but DB says AVAILABLE, flag for attendant review—do not silently overwrite paid sessions. Reconciliation jobs compare sensor streams to session rows and open override tickets. Good teams measure divergence rate per floor.

Q: How does valet parking fit?

A: Valet is a parallel queue state machine: vehicle checked in at curb, spot assigned by attendant app using the same atomic claim API, keys tracked separately. Payment may happen at return, not at garage exit gate. Scope it as a different entry channel sharing spot inventory—not a second parking lot with duplicate spot rows.

Q: Should availability boards show exact spot numbers or only counts?

A: Counts per floor and type are enough for most garages and are cheaper to cache. Showing “Spot 214” on a sign is optional and increases stale display risk. If you show specific spots, treat it as a hint; entry still claims atomically. Say aloud which UX you picked and how often boards reconcile.

Q: What about dynamic pricing by hour or demand?

A: Store a pricing rules version on the session at entry (or re-rate at exit with a declared policy). Fee calculation uses server UTC timestamps, grace minutes, rounding rules, and a max-day cap for lost tickets. Compute the fee once, store the amount and pricing_version on the session, and key the payment on the session itself, so a retry after a rule change replays the same amount instead of charging a second, different one.

Practice interactively

Open the practice session to use the canvas and stages, then review AI feedback.