AlgoViz

Design a parking lot

medium 90 min

Model a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.

Watch lesson4:48

Many gates and floors

Splitting the lock, and the new problems

The point: split a lock along the line where the data is already split. Here that is the level. Then say what you gave up: the exact total.

Design

The level earns its class

When a level becomes a class

1 to n1 to nParkingLot- levels: List<Level>+ enter(vehicle, gate)+ leave(ticketId)Level- lock: Lock- free: Map<Size, Queue>+ claim(smallest): Spot?+ release(spot)Spot+ level: int

1/3One lock per level

In the small design a level is a number on the space. Now it owns a lock and its own free spaces. It has state and behaviour, so it has earned a class.

usesowns (dies together)implements

Python
from collections import dequefrom dataclasses import dataclassfrom threading import Lock@dataclass(frozen=True)class Spot:    id: str    level: intclass Level:    """Now a level is a class: it has its own lock and its own free spaces."""    def __init__(self, number: int, spot_count: int) -> None:        self.number = number        self._lock = Lock()        self._free = deque(Spot(f"{number}-{i}", number) for i in range(1, spot_count + 1))    def claim(self) -> Spot | None:        with self._lock:            return self._free.popleft() if self._free else None    def release(self, spot: Spot) -> None:        with self._lock:            self._free.appendleft(spot)    def looks_free(self) -> int:        return len(self._free)          # a hint for the order, never a promiseclass Lot:    def __init__(self, levels: list[Level]) -> None:        self._levels = {level.number: level for level in levels}    def claim(self, gate_level: int) -> Spot | None:        order = sorted(self._levels.values(), key=lambda l: (l.looks_free() == 0, abs(l.number - gate_level)))        for level in order:            spot = level.claim()        # decides, with that level's lock only            if spot:                return spot        return None    def release(self, spot: Spot) -> None:        self._levels[spot.level].release(spot)lot = Lot([Level(0, 1), Level(1, 1), Level(2, 1)])print([lot.claim(gate_level=0).id, lot.claim(gate_level=2).id, lot.claim(gate_level=2).id, lot.claim(gate_level=0)])
The order of levels uses a hint (looks_free, read without a lock). The decision uses the lock. A wrong hint costs one more try, never a wrong answer.
Edit and run it in your browser

Policies

Which level first?

OrderGoodBad
Lowest firstSimple, short walksAll gates fight for level 0
Nearest to the gateGates on different levels never meetLevel 0 fills first anyway
Emptiest firstSpreads cars and locksLonger drives; every gate runs to the same emptiest level
Round robinSpreads evenly, no readingIgnores distance
Random of two, take the emptierSpreads nearly as well as emptiest, without the herdHarder to explain to a driver

New problems

What splitting breaks

  1. 1

    The total is no longer one moment

    Adding five levels while cars move may show a total that never existed. Fine for a sign. If it must be exact, take all locks in level order, or keep one counter with its own lock.

  2. 2

    A space can be missed

    A gate looked at level 0 (full), then a car left it, then the gate looked at levels 1 to 4 (full) and said full. One space was free. Try once more before saying no, or accept it: the next car gets it.

  3. 3

    The plate check spans levels

    It is not a fact of one level. Keep it in its own concurrent set with an atomic add: if (!inside.add(plate)) refuse. If no space is found, or something fails, remove it again.

  4. 4

    Deadlock becomes possible

    Two locks held by two threads in two orders. Rule: never hold two level locks, and if you must, always lowest first.

How do you spread the work of many gates?

BreaksA lock for each gate
How
Every gate has its own lock and calls the same pool.
Limit
It protects nothing that is shared.
Choose when
Only for the gate's own hardware.
WorksOne lock
How
As in the base design.
Limit
In theory a bottleneck. In numbers: 0.00085% busy.
Choose when
Until a measurement says otherwise.
StrongA lock for each level
How
Level owns pool and lock; hints choose the order; the plate set is separate.
Limit
Totals are soft, a space can be missed, more to test.
Choose when
Levels are already separate in the data, or claims do more work than a pop.

Beyond

When one process is not enough

StepTruth lives inClaim is
One machine in the boothMemory, with tickets on diskA pop under a lock
Gates are separate machinesA databaseOne conditional update, check the row count
The network to the database failsEach level's controller has its own spacesLocal pop; totals are sent later
Many car parksOne database for each, one service for searchThe same, per lot. Search shows hints
The last row belongs to a system design round: see load balancing and sharding for the ideas. The claim stays local to one lot.