Distributed 64-Bit Key Generator and Multi-Level Parking System
Easy · System Design · Software Engineer · Technical Screen
Prompt
This interview covers two complementary design exercises.
Part 1 — Distributed 64-Bit Key Generator
Architect a library or service that mints globally unique 64-bit integer primary keys for database rows across a multi-region distributed architecture:
- Collision-free everywhere: Keys must never repeat across any database shard, host, or geographic region.
- High throughput: Sustain 100K–1M generated keys per second globally.
- Approximate time ordering: Newer keys should sort numerically higher than older keys so B-tree database indexes stay compact rather than suffering random page fragmentation.
- Elastic fleet growth: Scale smoothly across sharded databases and expanding fleets of generator nodes.
- Fault resilience: Guarantee uniqueness across process crashes/restarts, NTP clock drift or backward jumps, and network splits.
Part 2 — Multi-Level Parking Garage Platform (OOD + Backend)
Architect an object-oriented domain model and transactional backend for managing multi-story parking garages:
- Typed multi-floor inventory: Each garage spans multiple floors containing stalls categorized as
compact,large,EV, andhandicapped. - Arrival, billing, and departure: Issue a ticket when a vehicle enters, compute duration-based parking charges, and release capacity upon exit.
- Concurrency-safe allocation: Maintain accurate free-stall availability and strictly prevent concurrent arrivals from double-booking the same stall.
- External APIs: Support vehicle entry, vehicle exit, real-time availability queries, and optional advance reservations.
Scope & Expectations
- 64-bit key generator: Propose the exact 64-bit field allocation, explain how nodes acquire worker identities without manual config, detail clock-skew and rollback safeguards, and cover operational monitoring, node rotation, and migrations.
- Parking domain & APIs: Define the core object-oriented classes, entity relationships, HTTP API contracts, and persistent relational schema.
- Concurrency & consistency: Detail the locking, transactional, and idempotency mechanisms that prevent double-allocation on entry and erroneous stall release on exit.
Step-by-step walkthrough
Clarify requirements for both systems
This interview pairs two complementary problems: a distributed systems problem (generating globally unique 64-bit IDs at high speed without a central bottleneck) and a transactional backend + object-oriented problem (assigning parking spots safely under concurrency while keeping physical gates moving). Plan to spend roughly 25 minutes on the ID generator and 20 minutes on the parking lot.
Part 1: 64-bit ID generator requirements
- Global uniqueness: Every call to
next_id()returns a positive 64-bit integer that is guaranteed never to collide across any database shard, geographic region, or worker process — even across crashes, clock jumps, or network splits. - High throughput and tiny latency: Support 100,000 to 1,000,000 IDs per second globally with microsecond latency, which rules out making a network call for every single ID.
- Rough time ordering: IDs generated later should have larger numeric values than IDs generated earlier. Databases store primary keys in a B-tree index (a sorted tree of disk pages); inserting increasing keys appends cleanly to the rightmost page instead of splitting random pages across disk (index fragmentation).
- Automatic node scaling: Services can spin up or replace hundreds of containers automatically without humans editing worker-ID config files.
- Explicit assumptions: Up to 8 geographic regions, a lifespan of at least 50 years, internal database use (so encoding creation time inside the ID is acceptable), and rough ordering across machines (within ~100 ms) rather than strict global serialization.
Part 2: Parking lot management requirements
- Multi-level inventory: Multiple levels per lot, with four spot types:
compact,large,ev, andhandicapped. - Entry, pricing, and exit: Arriving vehicles receive a ticket and an assigned spot; departing vehicles pay a time-based fee and release the spot.
- Live availability and optional reservations: Signs and a mobile app query open spots by level and type; drivers can optionally pre-book capacity for a future time window.
- Zero double-allocation: Two entry gates acting at the exact same millisecond must never assign the same spot to two cars, and retried requests must be idempotent (repeating the exact same request produces the same single ticket rather than two tickets).
- Gate resilience and scale assumption: Physical barriers must respond in under 1 second and must never trap drivers if the cloud backend goes offline. Assume one operator manages 500 lots x 1,000 spots (5 levels x 200 spots) = 500,000 spots total.
- Global uniqueness: Every call to
Part 1: Back-of-the-envelope math and 64-bit layout
Why not use standard off-the-shelf keys? - A single database
AUTO_INCREMENTcounter requires a network round-trip on every insert and becomes a single point of failure across regions at 1,000,000 writes/sec. - Random 128-bitUUIDv4values need zero coordination, but they take 16 bytes instead of 8 bytes (doubling primary-key and foreign-key index size) and scatter inserts randomly across B-tree pages.Instead, we divide the 64 bits into fixed fields (inspired by Twitter's Snowflake design) so that time sits in the highest bits for sorting and location + counter sit in the lower bits for uniqueness:
+------+----------------------+---------------+---------------+------------------+ | Bit | 63 (1 bit) | 62..22 (41b) | 21..19 (3b) | 18..10 (9b) | 9..0 (10b) +------+----------------------+---------------+---------------+------------------+ | Role | Sign bit (always 0) | Timestamp(ms) | Region ID | Worker ID | Sequence number +------+----------------------+---------------+---------------+------------------+ | Cap | Positive int64 | ~69.7 years | 8 regions | 512 / region | 1,024 IDs / ms +------+----------------------+---------------+---------------+------------------+Let's verify every field against the numbers:
- Sign bit (1 bit, always
0): SQLBIGINTand Javalongare signed 64-bit integers (-2^63to2^63 - 1). Keeping bit 63 at0guarantees every ID is a positive integer. - Timestamp (41 bits): Stores milliseconds elapsed since a custom epoch (a fixed starting point in time, here
2026-01-01T00:00:00Z).2^41 - 1milliseconds is2,199,023,255,551 ms, which equals2,199,023,255.551 / (86,400 * 365.2425) = 69.7 years(lasting until September 2095). Placing time in the most significant bits makes newer IDs numerically larger. - Region ID (3 bits) + Worker ID (9 bits): Supports
2^3 = 8regions and2^9 = 512concurrent generator processes per region (4,096processes globally). Why 9 worker bits and 10 sequence bits instead of the classic 10/12 split? At 1,000,000 IDs/sec spread across 200 microservice containers, each container emits only ~5,000 IDs/sec. Modern microservice fleets run many processes at modest per-process rates, so having 4,096 total slots matters far more than letting a single process exceed 1,000,000 IDs/sec. - Sequence (10 bits): Counts from
0to1,023within a single millisecond on one worker, giving each worker a ceiling of1,024 * 1,000 = 1,024,000 IDs/sec.
Two practical edge cases to call out immediately: 1. JavaScript precision limit: Browser JSON parsers use IEEE-754 floating-point numbers, which only represent integers exactly up to
2^53 - 1. Because the timestamp is shifted left by3 + 9 + 10 = 22bits, IDs exceed2^53 - 1once the timestamp passes2^(53 - 22) = 2^31 ms(~24.9 days after the epoch). REST APIs must serialize 64-bit IDs as strings (for example,"18014398509481984"). 2. Range-partitioned databases: Databases that split tables by contiguous key ranges (such as CockroachDB or HBase without hash sharding) will route all monotonically increasing IDs onto the single highest range shard, creating a write hotspot. Use hash-based sharding (or hash prefixes) on those engines; hash-sharded PostgreSQL/MySQL setups are unaffected.- Sign bit (1 bit, always
Part 1: Worker ID leases and timestamp reservations
We run the ID generator as an in-process library inside each backend service container rather than a central RPC service. Generating an ID is pure CPU bit-shifting in memory (~50 nanoseconds, zero network hops, and no central ID server that can go down).
IdGenerator.next_id() -> int64 IdGenerator.next_ids(n) -> list[int64] (batch up to 1,024 IDs under one lock acquisition) parse_id(id_val) -> {timestamp_ms, region_id, worker_id, sequence} min_id_at(unix_ms) -> (unix_ms - EPOCH_MS) << 22 (turns "created >= t" into an index scan)How does a container get its
(region_id, worker_id)safely without manual config files? -region_id(0..7) comes from static deployment environment config, since a company adds cloud regions rarely and deliberately. -worker_id(0..511) is dynamically leased from a small 3-node regional etcd cluster (a strongly consistent key-value store powered by the Raft consensus protocol). Regions never talk to each other's etcd clusters.Here is the subtle distributed-systems trap: a lease alone does not prevent duplicate IDs! Suppose Container A holds
worker_id = 7on a 10-second lease, then freezes for 15 seconds during a long garbage-collection (GC) pause. While Container A is frozen, its lease expires and Container B claimsworker_id = 7. When Container A unfreezes for a microsecond before noticing its lease died, both Container A and Container B emit IDs forworker_id = 7in the same millisecond!We close this gap completely by pairing the ephemeral lease with a persistent timestamp reservation (a high-water mark, meaning the highest timestamp any owner of this slot has ever been allowed to touch). Each slot
whas two keys in regional etcd:/idgen/<region>/owner/<w> -> "{host, pid}" (ephemeral: attached to a 10-second lease) /idgen/<region>/reserved/<w> -> reserved_until_ms (persistent: epoch-relative ms, never deleted)Old owner A (paused) |--- allowed: [1000, 61000) ---| X cannot use >= 61000 without etcd! | New owner B (takes w=7) |--- allowed: [61000, 121000) ---> Time (epoch ms) --------> 1000 61000 121000Startup and background renewal work in five simple steps: 1. List free worker slots (no
owner/<w>key), sorted byreserved/<w>ascending (oldest high-water mark first, so recently crashed slots have time to cool down). 2. Atomically claim a slot in an etcd transaction: "Ifowner/<w>does not exist, create it attached to my 10-second lease and readreserved/<w>." Start a background keepalive every 3 seconds. 3. Readhigh_water_epoch_msfromreserved/<w>(0if never used). Previous owners used only timestamps strictly belowhigh_water_epoch_ms. If our clock has not reachedhigh_water_epoch_msyet, sleep until it does. 4. Before serving traffic — and every 1 second in a background thread whenever fewer than 40 seconds remain — extendreserved/<w>tonow_epoch_ms + 60_000inside an etcd transaction conditional on still owningowner/<w>. 5. On the hotnext_id()path, never call etcd; simply check in memory thatts_epoch_ms < self.reserved_until_epoch_ms.class LeaseLostError(Exception): pass class ReservationError(Exception): pass class WorkerLease: """Tracks one etcd worker slot and the epoch-ms window this process may emit.""" WINDOW_MS = 60_000 EXTEND_BELOW_MS = 40_000 def __init__(self, store, region_id: int, worker_id: int, lease_id: int, high_water_epoch_ms: int): self.store = store self.owner_key = f"/idgen/{region_id}/owner/{worker_id}" self.reserved_key = f"/idgen/{region_id}/reserved/{worker_id}" self.lease_id = lease_id # Earlier owners of this worker_id only emitted timestamps < high_water_epoch_ms self.high_water_epoch_ms = high_water_epoch_ms self.reserved_until_epoch_ms = high_water_epoch_ms self.lost = False def extend_if_needed(self, now_epoch_ms: int) -> None: """Run every 1s on a background thread; never called on the hot next_id() path.""" if self.reserved_until_epoch_ms - now_epoch_ms >= self.EXTEND_BELOW_MS: return # Never let reserved_until move backward even if now_epoch_ms stepped back new_limit = max(self.reserved_until_epoch_ms, now_epoch_ms + self.WINDOW_MS) # Atomic etcd compare-and-swap: succeeds ONLY if our lease_id still owns owner_key ok = self.store.put_if_owned( self.reserved_key, new_limit, self.owner_key, self.lease_id ) if not ok: self.lost = True return # Update in-memory ceiling ONLY after etcd durably commits new_limit self.reserved_until_epoch_ms = new_limit def check(self, ts_epoch_ms: int) -> None: if self.lost: raise LeaseLostError("worker slot lease was lost; restart to claim a fresh slot") if ts_epoch_ms >= self.reserved_until_epoch_ms: raise ReservationError("timestamp exceeds reserved etcd window; failing closed")Part 1: Architecture and lock-safe ID generation
Region 0 (us-east) Region 1 (eu-west) +------------------------------------------------------+ +------------------------------+ | Order Service Pod A Ticket Service Pod B | | Identical independent setup | | [IdGenerator r=0, w=7] [IdGenerator r=0, w=8] | | with its own 3-node etcd | | | | | | and worker slots 0..511 | | +------------+-------------+ | +------------------------------+ | | 3s lease keepalive | | | ~20s timestamp window renewal | Zero cross-region RPCs: | v | the 3-bit region_id guarantees | [ Regional etcd (3 nodes) ] | Region 0 and Region 1 IDs | | never overlap! | [ chrony NTP daemon on every host ] | +------------------------------------------------------+Inside a single process, how do we keep
(timestamp, sequence)strictly increasing even if two threads callnext_id()simultaneously or the OS wall clock steps slightly backward? We maintain a logical clock (self.last_epoch_ms):- Whenever the wall clock moves strictly ahead of
self.last_epoch_ms, we jumpself.last_epoch_msforward to match it and resetself.seq = 0. - Whenever two calls land in the same millisecond — OR the wall clock jumped backward so
now <= self.last_epoch_ms— we incrementself.seq. Ifself.seqpasses1,023, we rollself.last_epoch_msforward by 1 millisecond and resetself.seq = 0. - To keep logical time from drifting far into the future during an extreme burst or a big backward clock jump, we refuse to emit IDs if
self.last_epoch_ms - now > 1,000 ms.
import threading import time EPOCH_MS = 1_767_225_600_000 # 2026-01-01T00:00:00Z in Unix milliseconds TIMESTAMP_BITS = 41 REGION_BITS = 3 WORKER_BITS = 9 SEQ_BITS = 10 MAX_TIMESTAMP = (1 << TIMESTAMP_BITS) - 1 MAX_SEQ = (1 << SEQ_BITS) - 1 MAX_AHEAD_MS = 1_000 # Logical clock may lead wall clock by at most 1 second class ClockBehindError(Exception): pass def current_epoch_ms() -> int: return time.time_ns() // 1_000_000 - EPOCH_MS class IdGenerator: def __init__(self, region_id: int, worker_id: int, lease: WorkerLease): assert 0 <= region_id < (1 << REGION_BITS) assert 0 <= worker_id < (1 << WORKER_BITS) self.node_bits = (region_id << WORKER_BITS) | worker_id self.lease = lease self.lock = threading.Lock() # Start right before high_water_epoch_ms with a full sequence so the very first # call advances to at least high_water_epoch_ms (never touching an older owner's range) self.last_epoch_ms = lease.high_water_epoch_ms - 1 self.seq = MAX_SEQ def next_id(self) -> int: with self.lock: now = current_epoch_ms() if now > self.last_epoch_ms: self.last_epoch_ms = now self.seq = 0 else: # Same millisecond OR wall clock stepped backward: advance sequence on logical time self.seq += 1 if self.seq > MAX_SEQ: self.last_epoch_ms += 1 self.seq = 0 if self.last_epoch_ms - now > MAX_AHEAD_MS: raise ClockBehindError( f"wall clock is {self.last_epoch_ms - now} ms behind logical time" ) if self.last_epoch_ms < 0 or self.last_epoch_ms > MAX_TIMESTAMP: raise OverflowError("epoch timestamp out of 41-bit range") # Verify our in-memory etcd reservation covers self.last_epoch_ms self.lease.check(self.last_epoch_ms) timestamp_shift = REGION_BITS + WORKER_BITS + SEQ_BITS return ( (self.last_epoch_ms << timestamp_shift) | (self.node_bits << SEQ_BITS) | self.seq )- Whenever the wall clock moves strictly ahead of
Part 1: Clock skew, rollbacks, partitions, and operations
Computer clocks are synchronized over the network using NTP (Network Time Protocol, typically run via the
chronydaemon). Two things go wrong in real fleets: clock skew (Host A and Host B disagree by a few milliseconds) and clock rollback (a host's clock jumps backward after an NTP step or VM live migration).- Small clock rollback (<= 1 second): Handled transparently by
self.last_epoch_ms. The generator keeps counting forward from its last timestamp without pausing or colliding. - Large clock rollback (> 1 second): Raises
ClockBehindError(fail closed — stopping rather than risking corrupt timestamps). The instance fails its readiness probe, drains from the load balancer, and pages on-call while healthy sibling pods take the traffic. To prevent rollbacks in the first place, configurechronyto slew the clock (gently speed up or slow down the tick rate) instead of stepping backward, and use leap-second smearing. - Runaway fast clock: If a host's clock jumps 1 day into the future, extending its etcd reservation would push that slot's
high_water_epoch_msforward by 24 hours. To prevent poisoning a slot, the background renewal checkschronylocal offset and refuses to extend if NTP offset exceeds500 ms. - Failure matrix:
- Process crash / reboot: 10 s etcd lease expires; next owner starts at
reserved/<w>, so even if the rebooted host's clock rolled back, zero timestamps repeat. - Regional etcd outage < 40 s:
next_id()keeps running at full speed inside its pre-reserved 40–60 s window. - Regional etcd outage > 60 s: Reservations expire and generators fail closed rather than risk duplicate worker ownership.
- Cross-region network partition: Zero impact because regions share nothing at runtime.
- Process crash / reboot: 10 s etcd lease expires; next owner starts at
Operational playbook: - Monitoring: Alert on
chronyclock offset > 100 ms, anyClockBehindErrororLeaseLostError, active worker slots > 70% of 512 in a region, and any primary-key unique constraint error in databases. - Graceful rotation: On cleanSIGTERM, a pod stops issuing IDs, lowersreserved/<w>down toself.last_epoch_ms + 1(still guarded by its lease), and revokes its lease so the next pod during a rolling deploy can reuse the slot immediately without waiting up to 60 seconds. - Migrations: Switching fromAUTO_INCREMENTrequires zero backfill because even 1 day after the epoch,(86_400_000 << 22)is~3.6 * 10^14, far above legacy sequential IDs. If we ever need more than 512 workers per region, we either run one local sidecar generator per physical host (shared by all containers on that host) or pick a future cutover timestampTafter which all nodes switch to a new lower-bit split while keeping the 41 timestamp bits in place.- Small clock rollback (<= 1 second): Handled transparently by
Part 2: Parking lot scale and object-oriented model
Now let's shift to the parking lot system. First, check the numbers for 500 lots x 1,000 spots = 500,000 spots:
Peak entries 500 lots x 4 entry gates x (1 car / 10 s) = 200 entries/sec across all lots Peak exits ~200 exits/sec across all lots Availability 500 lots x 5 levels / 5 s sign refresh = 500 req/s + ~2,000 mobile req/s = 2,500 reads/s Storage 500,000 spots x 3 turnovers/day = 1.5M tickets/day x 300 B = ~450 MB/day (~165 GB/yr)200 writes/sec and 165 GB/year fit easily on one PostgreSQL primary with a synchronous standby! The real engineering challenges are preventing double-allocation when gates act concurrently and keeping barriers working when a garage loses internet.
Core entities and relationships:
ParkingLot (1) ---- (*) Level (1) ---- (*) Spot [spot_id, level, spot_type, rank, status, ticket_id] ParkingLot (1) ---- (*) Gate [entry or exit barrier + plate camera + local controller] ParkingLot (1) ---- (*) RateCard [per spot_type: free_minutes, hourly_cents, daily_cap_cents] Spot (1) ---- (0..1) Active Ticket (*) ---- (1) Vehicle [plate, size, is_ev, has_permit] Ticket (1) ---- (*) Payment [idempotent payment attempts]Each spot carries an integer
rank(walking distance to the elevator/exit, lower is closer). A pure compatibility function maps each arriving vehicle to allowed spot types in preference order (for example, vans requirelarge, while an EV car prefersev, thencompact, thenlarge). Notice the core invariant in the in-memory object model below: finding the best free spot and claiming it must happen inside one atomic critical section.import threading from dataclasses import dataclass from enum import Enum from typing import Optional class SpotType(Enum): COMPACT = "compact" LARGE = "large" EV = "ev" HANDICAPPED = "handicapped" class VehicleSize(Enum): MOTORCYCLE = 1 CAR = 2 VAN = 3 @dataclass class Vehicle: plate: str size: VehicleSize is_ev: bool = False has_permit: bool = False @dataclass class Spot: spot_id: str level: int spot_type: SpotType rank: int # Lower rank = closer to exit/elevator ticket_id: Optional[str] = None out_of_service: bool = False @dataclass class Ticket: ticket_id: str plate: str spot_id: str entry_at: float exit_at: Optional[float] = None fee_cents: Optional[int] = None status: str = "ACTIVE" # ACTIVE -> PAID -> CLOSED def allowed_types(vehicle: Vehicle) -> list[SpotType]: """Return compatible spot types in best-match order.""" if vehicle.size == VehicleSize.VAN: return [SpotType.LARGE] choices: list[SpotType] = [] if vehicle.has_permit: choices.append(SpotType.HANDICAPPED) if vehicle.is_ev: choices.append(SpotType.EV) choices.append(SpotType.COMPACT) choices.append(SpotType.LARGE) return choices class ParkingLot: def __init__(self, lot_id: str, spots: list[Spot], id_gen): self.lot_id = lot_id self.spots = spots self.id_gen = id_gen self.tickets: dict[str, Ticket] = {} self.lock = threading.Lock() def enter(self, vehicle: Vehicle, now: float) -> Optional[Ticket]: # Finding a free spot and marking it taken MUST be a single atomic step with self.lock: spot = self._best_free_spot(vehicle) if spot is None: return None ticket_id = str(self.id_gen.next_id()) ticket = Ticket(ticket_id=ticket_id, plate=vehicle.plate, spot_id=spot.spot_id, entry_at=now) spot.ticket_id = ticket_id self.tickets[ticket_id] = ticket return ticket def _best_free_spot(self, vehicle: Vehicle) -> Optional[Spot]: for target_type in allowed_types(vehicle): best_spot = None for spot in self.spots: if spot.spot_type != target_type or spot.ticket_id is not None or spot.out_of_service: continue if best_spot is None or spot.rank < best_spot.rank: best_spot = spot if best_spot is not None: return best_spot return NoneAn in-memory
threading.Lock()works inside a single Python process, but vanishes if the server restarts and fails across multiple stateless API servers. Next, we move this exact invariant into PostgreSQL.Part 2: REST APIs and relational schema
Every mutating gate or payment request carries an
Idempotency-Keyheader (<gate_id>:<local_event_seq>). If a gate sends an entry request, the network drops the HTTP response, and the gate retries 500 ms later, the backend returns the stored201response instead of allocating a second spot. Allticket_idvalues use our 64-bit generator from Part 1 serialized as strings.POST /v1/lots/{lot_id}/entries Idempotency-Key: gate-3:98412 { gate_id, plate, vehicle_size, is_ev, has_permit, reservation_id? } -> 201 { ticket_id: "1801...", spot: { spot_id, level, number, type }, entry_at } -> 409 { error: "LOT_FULL_FOR_VEHICLE" } POST /v1/tickets/{ticket_id}/quote -> 200 { fee_cents, valid_until } (15-min exit grace window) POST /v1/tickets/{ticket_id}/payments Idempotency-Key: pay-attempt-uuid { amount_cents, method } -> 200 { payment_id, status: "PAID" } POST /v1/lots/{lot_id}/exits Idempotency-Key: exit-1:44109 { gate_id, ticket_id, plate? } -> 200 { open_barrier: true } | 402 { fee_cents } GET /v1/lots/{lot_id}/availability?type=ev -> 200 { as_of, levels: [ { level: 1, type: "ev", free_spots: 14 }, ... ] } POST /v1/lots/{lot_id}/reservations { spot_type, start_at, end_at, plate } -> 201 { reservation_id } DELETE /v1/reservations/{reservation_id}PostgreSQL tables and safety-net constraints:
spot PK spot_id lot_id, level, number, spot_type, rank, status ('FREE' | 'HELD' | 'OCCUPIED' | 'OUT_OF_SERVICE'), ticket_id NULL, reservation_id NULL INDEX (lot_id, spot_type, status, rank) ticket PK ticket_id lot_id, plate NULL, spot_id NULL, entry_at, exit_at NULL, status ('ACTIVE' | 'PAID' | 'CLOSED'), fee_cents NULL, offline BOOL -- Partial unique indexes act as an unbreakable database-level safety net: UNIQUE (spot_id) WHERE status <> 'CLOSED' AND spot_id IS NOT NULL UNIQUE (lot_id, plate) WHERE status <> 'CLOSED' AND plate IS NOT NULL payment PK payment_id (ticket_id, amount_cents, status, provider_ref, idempotency_key UNIQUE) rate_card PK (lot_id, spot_type) (free_minutes, hourly_cents, daily_cap_cents, lost_ticket_cents) reservation PK reservation_id (lot_id, spot_type, plate, start_at, end_at, status) reservation_slot PK (lot_id, spot_type, slot_start) (reserved_count, reservable_capacity) -- 15-min buckets idempotency_log PK idempotency_key (response_status, response_json, created_at) -- 24h TTLNotice why the partial unique index (an index enforced only on rows matching a
WHEREfilter) checksstatus <> 'CLOSED'rather thanstatus = 'ACTIVE': a driver who pays at a walk-up kiosk transitions their ticket fromACTIVEtoPAID, but their car is still parked in the spot until they scan out at the exit gate (CLOSED). Filteringspot_id IS NOT NULLalso allows unassigned offline tickets to coexist safely.Part 2: Architecture and concurrent spot assignment
Entry/Exit Gates Walk-up Kiosks Mobile App Level LED Signs (camera, printer, barrier, | | ^ local SQLite + ID pool) | | | push / poll | HTTPS + Idempotency-Key | | | +------------+------------+----------------+ | v | [ API Gateway (TLS, auth, rate limits) ] | | | v | [ Parking Service (stateless, 3+ replicas) ] | | | | | v v v | [ PostgreSQL Primary ] [ Redis Cache (2s TTL) ] [ Payment ] | [ + Sync AZ Standby ] availability counts [ Gateway ] | | | +---> [ Transactional Outbox -> Event Stream ] -------------+- Reads vs. writes: All state-changing decisions (entry, payment, exit, reservation) hit the PostgreSQL primary. Availability queries hit Redis (refreshed via a transactional outbox — an event table written in the same DB transaction as the ticket change — with a 2-second TTL). Signs can safely lag by 2 seconds; spot allocation never reads from Redis.
Deep dive: Concurrent entry without lock convoys (
FOR UPDATE SKIP LOCKED)Suppose Gate 1 and Gate 2 both admit standard cars at the exact same instant. Both want the lowest-rank free compact spot (
L1-01):Without SKIP LOCKED: Gate 1 locks L1-01 ---> Gate 2 BLOCKS waiting on L1-01 ---> fails, retries! With SKIP LOCKED: Gate 1 locks L1-01 ---> Gate 2 SKIPS L1-01, locks L1-02 immediately in parallel!BEGIN; SELECT spot_id FROM spot WHERE lot_id = :lot_id AND spot_type = ANY(:allowed_types) AND status = 'FREE' ORDER BY array_position(:allowed_types, spot_type), rank LIMIT 1 FOR UPDATE SKIP LOCKED; -- If no spot_id was returned, ROLLBACK and return HTTP 409 (lot full for this vehicle). UPDATE spot SET status = 'OCCUPIED', ticket_id = :ticket_id WHERE spot_id = :spot_id AND status = 'FREE'; INSERT INTO ticket (ticket_id, lot_id, plate, spot_id, entry_at, status, offline) VALUES (:ticket_id, :lot_id, :plate, :spot_id, now(), 'ACTIVE', false); COMMIT;Why database row locks beat a Redis distributed lock here: a Redis lock has a TTL that can expire mid-GC-pause (letting two servers believe they hold the lock), whereas a PostgreSQL row lock lives for the exact lifetime of the transaction modifying the row.
Deep dive: Safe concurrent exit
When a paid car scans out at the exit gate (stays inside
free_minutesare markedPAIDwith0cents), we close the ticket and free the spot in one atomic CTE (Common Table Expression):WITH closed AS ( UPDATE ticket SET status = 'CLOSED', exit_at = now() WHERE ticket_id = :ticket_id AND status = 'PAID' RETURNING ticket_id, spot_id ), freed AS ( UPDATE spot SET status = 'FREE', ticket_id = NULL FROM closed WHERE spot.spot_id = closed.spot_id AND spot.ticket_id = closed.ticket_id ) SELECT ticket_id FROM closed;Look at all three bugs this single statement prevents: 1. If the ticket is unpaid (
status = 'ACTIVE'),closedmatches zero rows,freeddoes nothing, andSELECTreturns empty -> backend returns402 Payment Requiredwithout accidentally freeing the occupied spot. 2. If a duplicate or delayed exit webhook arrives 10 minutes later after another car has already parked in that spot,spot.ticket_id = closed.ticket_idis false (andclosedis empty), so we never wipe out the new car's spot. 3. If the ticket was issued offline (spot_id IS NULL),closedstill closes the ticket andSELECT ticket_id FROM closedstill returns 1 row so the barrier opens cleanly.Optional reservations: Pre-booking a specific physical spot hours ahead wastes inventory while the spot sits empty. Instead, reservations book type capacity across 15-minute
reservation_slotbuckets (UPDATE reservation_slot SET reserved_count = reserved_count + 1 WHERE ... AND reserved_count < reservable_capacity, locking buckets in chronological order so overlapping requests cannot deadlock). Walk-in entries reserve a buffer for reservations starting within 2 hours, and 15 minutes beforestart_ata background worker holds a concrete spot (status = 'HELD') viaSKIP LOCKED(falling back to a larger compatible spot or refunding proactively if earlier walk-ins overstayed).Part 2: Fee calculation, offline gates, and reconciliation
Fee calculation: Always compute fees in integer cents (never floating-point numbers, which suffer from
0.1 + 0.2 != 0.3rounding bugs) and always use the server's clock (or synchronized monotonic duration) rather than trusting client input. Below is a standard rate policy: first 15 minutes free, then 300 cents per started hour, capped at 2,500 cents per 24-hour day.import math def compute_fee_cents( entry_s: float, exit_s: float, free_minutes: int, hourly_cents: int, daily_cap_cents: int, ) -> int: elapsed_s = max(0.0, exit_s - entry_s) total_minutes = math.ceil(elapsed_s / 60.0) if total_minutes <= free_minutes: return 0 full_days, remaining_minutes = divmod(total_minutes, 24 * 60) fee = full_days * daily_cap_cents started_hours = math.ceil(remaining_minutes / 60.0) fee += min(started_hours * hourly_cents, daily_cap_cents) return feeQuick verification with
free_minutes=15, hourly_cents=300, daily_cap_cents=2500: -10 min->0 cents(within free window) -61 min->2 started hours->600 cents-10 hours(600 min) ->min(3000, 2500)->2,500 cents(daily cap) -25 hours(1,500 min) ->1 full day (2500) + 1 started hour (300)->2,800 centsOnce a driver pays at a kiosk,
valid_until = now + 15 minutesgives them time to walk to their car and drive to the exit gate; if they linger pastvalid_until, the exit gate charges only the incremental difference.Failure handling and scaling:
- Garage loses internet (offline gate mode): A physical barrier must never trap cars. Notice a crucial cross-part insight: an offline gate controller cannot run its own Part 1 ID generator indefinitely, because its 10-second etcd lease and 60-second timestamp reservation expire within a minute! Instead, while online, each gate keeps a local SQLite stash of ~2,000 pre-generated 64-bit ticket IDs (~5.5 hours of cars at 1 car every 10 seconds) plus a cached
rate_card. When offline, the gate pops a pre-allocatedticket_id, prints an unassigned ticket (spot_id = NULL, signs switch to "Follow level indicators"), opens the barrier, and queues events locally to replay idempotently once connectivity returns. - Drivers parking in the wrong spot: Overhead ultrasonic/camera sensors emit occupancy events. A background reconciliation worker moves a mismatched ticket to the spot where the license plate was actually seen and frees the originally assigned spot; lots without spot sensors can run in count-only mode (tracking free counts per level/type rather than assigning exact stalls).
- Scaling to 10,000+ lots: Because no transaction ever spans two parking lots,
lot_idis a zero-coordination shard key when a single PostgreSQL primary eventually outgrows hardware.
- Garage loses internet (offline gate mode): A physical barrier must never trap cars. Notice a crucial cross-part insight: an offline gate controller cannot run its own Part 1 ID generator indefinitely, because its 10-second etcd lease and 60-second timestamp reservation expire within a minute! Instead, while online, each gate keeps a local SQLite stash of ~2,000 pre-generated 64-bit ticket IDs (~5.5 hours of cars at 1 car every 10 seconds) plus a cached
End-to-end summary of key trade-offs
- In-process library + etcd timestamp windows vs. central ID server: Zero network hops on
next_id()and immunity to GC-pause split-brain, in exchange for managing host clocks (chrony) and failing closed if etcd stays down past 40–60 seconds. - 9 worker bits / 10 sequence bits vs. 10 / 12: Supports 4,096 concurrent containers across 8 regions (at 1.02M IDs/sec each), matching modern multi-pod deployments.
- PostgreSQL
FOR UPDATE SKIP LOCKED+ partial unique indexes vs. Redis locks: Parallel non-blocking spot assignment whose lock lifetime matches the exact DB transaction, backed by schema constraints that make double-allocation impossible. - Pre-allocated ID stash at gates vs. cloud-only gates: Keeps physical entry/exit barriers working smoothly through internet outages at the cost of deferred occupancy reconciliation.
- In-process library + etcd timestamp windows vs. central ID server: Zero network hops on
Intuition & how it works
Think of the two halves of this prompt as solving two opposite coordination problems. For the 64-bit ID generator, imagine 4,000 festival booths printing numbered wristbands with no phone lines between booths: if every wristband stamps (current millisecond | region | booth number | per-millisecond counter), two booths can never print the same number because their booth numbers differ, and a single booth never repeats itself as long as its clock or counter moves forward. For the parking lot, imagine two entry kiosks clicking "pick best seat" on the same seating chart at the exact same millisecond: instead of letting both kiosks read the same free stall and collide, the database locks the first stall for Gate 1 while letting Gate 2 immediately skip that locked row and grab the next best stall.
Naive designs break down quickly in both systems. For IDs, a single AUTO_INCREMENT database table requires a cross-network round-trip on every write and becomes a single point of failure at 1,000,000 IDs/sec, while random 128-bit UUIDs take twice the storage (16 bytes vs. 8 bytes) and scatter inserts across random B-tree pages (the sorted tree structure databases use for indexes), hurting disk cache locality. For the parking lot, checking free spots in application memory before writing to the database lets concurrent gates double-book the same spot, and requiring live cloud connectivity on every entry traps drivers behind closed barriers whenever garage internet drops.
Trace four concrete events end to end to see how both designs work together:
1. Worker startup and fast ID generation: Container #7 in Region 0 boots, leases worker_id = 7 in regional etcd (a strongly consistent key-value store), reads the slot's high-water mark (the highest timestamp a previous owner could have used, say 1000 ms), and reserves [1000 ms, 61000 ms). Every next_id() call packs (41-bit timestamp | 3-bit region | 9-bit worker | 10-bit sequence) in memory in ~50 nanoseconds with zero network calls.
2. Simultaneous car entries: Two EVs arrive at Gate 1 and Gate 2 of Lot 42 at the exact same instant. Inside PostgreSQL transactions using FOR UPDATE SKIP LOCKED (a row-locking clause that skips rows locked by other active transactions instead of waiting), Gate 1 locks stall L1-01 while Gate 2 skips L1-01 and locks L1-02 in parallel, each receiving a string-encoded 64-bit ticket_id.
3. Payment and atomic exit: Car 1 leaves after 61 minutes (first 15 minutes free, 300 cents per started hour -> 600 cents), pays at a kiosk (ACTIVE -> PAID), and scans at the exit gate, where one SQL statement flips PAID -> CLOSED and frees L1-01 only if L1-01 still belongs to that ticket.
4. Internet outage at the garage: Lot 42 loses cloud connectivity; Gate 1 pops an unused ID from its local pool of 2,000 pre-allocated 64-bit IDs, prints an unassigned offline ticket, raises the barrier immediately, and replays queued events with an idempotency key (a unique request token ensuring retries never create duplicate records) once the link recovers.
Key trade-offs
- Bit-budget allocation (41 time / 3 region / 9 worker / 10 sequence): Every bit added to one field comes out of another within 63 usable positive bits. Giving 12 bits to
(region + worker)supports 4,096 concurrent containers while still allowing ~1.02M IDs/sec per container and ~69.7 years of timestamps; a centralized ID service with fewer processes would shift bits from worker to sequence. - Embedded library vs. central ID microservice: Generating IDs inside each application process eliminates network latency and removes a central point of failure on writes, at the cost of assigning a
worker_idper container and monitoring NTP (Network Time Protocol) clock health across all hosts. - Hard uniqueness (fail closed) vs. 100% write availability: On a backward clock jump larger than 1 second or an etcd outage longer than the remaining 40–60 second reservation window, a worker stops generating IDs rather than risking a duplicate primary key.
- Time-ordered 64-bit IDs vs. random keys: Time-ordered keys keep B-tree inserts sequential and enable
id >= min_id_at(t)time-range scans, but they expose approximate creation timestamps (so public-facing URLs may still want an opaque token) and require hash sharding on range-partitioned databases to avoid write hotspots. - Database
FOR UPDATE SKIP LOCKEDvs. application or distributed locks: A PostgreSQL row lock is tied to the exact transaction modifying the stall and works across any number of stateless servers, whereas an in-memory lock fails across replicas and a Redis distributed lock can expire during a garbage-collection pause. - Assigned stalls vs. level/type headcount only: Assigning a specific stall (
L1-01) guides drivers directly to an open spot, but requires camera or sensor reconciliation when drivers park in the wrong stall; count-only mode avoids sensor hardware at the cost of less driver guidance. - Capacity-bucket reservations vs. locking a physical spot hours early: Booking 15-minute capacity counts keeps stalls open for walk-ins before the reservation window starts, at the cost of holding a physical stall 15 minutes prior to arrival and maintaining a small walk-in safety buffer.
Common mistakes
- Trusting the OS wall clock to move only forward: NTP steps and VM live migrations can jump system time backward; without a non-decreasing logical clock (
last_epoch_ms), two calls milliseconds apart can emit the exact same timestamp and sequence. - Assuming an etcd lease alone prevents duplicate worker IDs: A process paused by garbage collection can wake up briefly after its lease expired and emit IDs at the same time as the new slot owner; persistent timestamp high-water marks (
reserved_until_epoch_ms) are what keep old and new owners' ranges disjoint. - Mixing Unix timestamps with custom-epoch timestamps: Shifting a full Unix millisecond timestamp (
~1.77 * 10^12) left by 22 bits overflows 64 bits; every bit-packed timestamp and reservation check must consistently subtractEPOCH_MSfirst. - Returning raw 64-bit integers in JSON to web browsers: JavaScript numbers silently round integers larger than
2^53 - 1(~24.9 days after the epoch); always serialize 64-bit IDs as strings in JSON APIs. - Using bit 63 (the sign bit): Setting the top bit produces negative numbers in SQL
BIGINTand Javalong, breaking range comparisons and sorting. - Checking free spots with
SELECTand updating in a separate unlocked step: Under concurrent gate traffic, two requests read the same free stall and double-assign it. - Enforcing uniqueness only on
status = 'ACTIVE'tickets: A ticket paid at a walk-up kiosk hasstatus = 'PAID'while the car is still physically sitting in the spot; partial unique indexes must coverstatus <> 'CLOSED'. - Freeing a spot unconditionally on exit: Updating
spotwithout verifying thatticketactually transitioned fromPAIDtoCLOSED(and thatspot.ticket_idstill matches) lets unpaid exit attempts or delayed duplicate webhooks free a stall now occupied by a new vehicle. - Running a live etcd-leased ID generator on an offline gate: Once internet drops, the gate's lease expires in 10 seconds and its timestamp reservation expires within 60 seconds; gates need a pre-fetched local pool of IDs instead.
Follow-up questions
- When would you choose database sequences, pre-allocated ID blocks, or 128-bit UUIDv7 keys over a custom 64-bit Snowflake-style ID? Central
AUTO_INCREMENTsequences add a cross-network round-trip and single point of failure on writes, whereas pre-allocated ID blocks (where each pod claims ranges of 10,000 integers from a database counter) eliminate clock dependence at the cost of coarse time ordering across pods and gaps on restarts. When 128-bit keys are acceptable,UUIDv7gives millisecond ordering with zero worker-ID coordination, unlike purely randomUUIDv4. Whenever a schema mandates 64-bit integers at up to 1M writes/sec, packing(timestamp | region | worker | sequence)cuts primary- and foreign-key index size in half while keeping inserts sequential. - How does the parking backend stay accurate when a driver parks in a different stall than the one printed on their ticket? Ultrasonic stall sensors or overhead plate cameras stream occupancy events into a background reconciliation worker. If Ticket
Twas directed to StallAyet its license plate appears in StallB, the worker atomically reassignsTto StallBand marks StallAfree again (redirecting any newly arriving driver via digital signs or mobile push ifBhad just been assigned). For garages lacking per-stall sensors where drivers routinely pick their own spot, running in count-only mode — tracking remaining headcount per floor and stall category rather than assigning specific stall IDs — avoids phantom occupancy bugs altogether. - What changes when scaling the parking platform from a few hundred garages to tens of thousands of locations globally? Because every operational row (
spot,ticket,rate_card,reservation) belongs to exactly onelot_idand no transaction spans two garages,lot_idserves as a natural, zero-coordination horizontal shard key. A cachedlot_id -> shardrouting map lets busy airport garages run on dedicated regional PostgreSQL primaries while grouping smaller garages onto shared clusters. Globally unique ticket and payment IDs keep working across every shard with zero changes thanks to Part 1's 64-bit generator.
Follow-up questions
- When would you choose database sequences, pre-allocated ID blocks, or 128-bit UUIDv7 keys over a custom 64-bit Snowflake-style ID?
- How does the parking backend stay accurate when a driver parks in a different stall than the one printed on their ticket?
- What changes when scaling the parking platform from a few hundred garages to tens of thousands of locations globally?
Similar questions
- Optimal Single Buy-and-Sell Gain
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency