Build a Live Bike Rental Platform: Tracking, Holds and Unlocks
System DesignModel answerLast updated
Design a bike rental backend where riders see nearby bikes live, hold one, unlock it, and end the trip, covering telemetry ingestion, geospatial lookup and race-free reservations.
You are asked to design the backend for a city-scale bike rental service. A rider opens the mobile app, sees bikes close by on a map, holds one for a short time, unlocks it, rides, and finishes by locking it. The platform must always know where each bike is and which state it is in.
Assumptions:
- Every bike has a smart lock with GPS and a cellular modem. It reports position and lock status and can receive an unlock command.
- Whether bikes return to docks or can be parked anywhere in a service zone is up to you to clarify. Point out which parts of your design depend on the answer.
- Payments are mostly out of scope. You only need to start and stop billing for a trip.
Questions you may want to ask first: docked or free-floating, how long a hold lasts and whether one rider may hold several bikes, the target scale (bikes, cities, peak concurrent trips), and how fresh and accurate map positions must be.
Part 1: Requirements and core flows. List functional and non-functional requirements and rough load estimates. Sketch the components, data model, bike state machine and APIs for find, reserve, unlock, ride and return.
Part 2: Location tracking and the write path. Pick a location reporting rate and defend it. Describe how updates travel from the bike to a rider's map, and how you stop the update volume from overwhelming your database. Cover offline bikes and out-of-order messages.
Part 3: Reservations, unlocking and contention. Two riders try to hold the same bike in the same second. Explain how exactly one wins, how holds expire, and how unlock and trip start/end stay consistent when the bike's connection is flaky.
Hints
Hint 1
Separate the data into two kinds: slow-changing transactional state (bike status, reservations, trips) and fast, disposable telemetry (positions). They deserve different stores and different guarantees.
Hint 2
For the reservation race, think of a single conditional write on the bike's row (compare-and-set on status or version) rather than a distributed lock held across services. Add an expiry timestamp so a hold cleans itself up.
Hint 3
Assume every message to or from a bike can be lost, duplicated or delayed. Give each command a unique ID, make handlers idempotent, and define what the server believes when the bike never answers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and estimates
Functional
- Riders: see nearby available bikes, hold one, unlock, ride, lock to end, see the receipt.
- Devices: report position, lock state and battery; accept unlock/lock commands.
- Operations: see fleet health, flag low-battery or stuck bikes, mark bikes out of service.
Non-functional
- Correctness first for holds, trips and billing: a bike is never held or ridden by two people, and a trip is never billed twice.
- Map freshness: a few seconds is fine for available bikes; a rider's own held bike benefits from tighter updates.
- Unlock latency: under about 3 seconds at p95 from tap to physical unlock.
- Availability: the map degrades gracefully (slightly stale) rather than failing.
Rough numbers (assume 100k bikes, 30% active at peak): idle bikes ping every 60 s, which is about 1.2k writes/s. Riding bikes (30k) ping every 5 s, which is about 6k writes/s. Total is roughly 7-8k telemetry events/s, which is trivial for a stream but harmful if each hit a relational primary. Map queries might be 5-10x that read rate, served from memory. Reservations and unlocks are only tens per second per city.
Entities and states
Bike(id, status, version, last_pos, last_seen, battery, hold_expires_at, held_by)Reservation(id, bike_id, rider_id, created_at, expires_at, state)Trip(id, bike_id, rider_id, start_ts, end_ts, start_pos, end_pos, state)- Bike state machine:
AVAILABLE -> RESERVED -> IN_USE -> AVAILABLE, withOUT_OF_SERVICEreachable from any state.
APIs: GET /bikes/nearby?lat&lon&radius, POST /reservations, POST /trips (unlock), POST /trips/{id}/end, plus a device channel (MQTT or similar) for telemetry and commands.
2. Location tracking and the write path
Ping rate. Use an adaptive rate: about 60 s when idle and parked (or only on lock state change plus a heartbeat), 5 s while riding, and 2-5 s for a bike a rider is walking toward. Faster means fresher maps but more battery drain and cellular cost; slower means worse map accuracy and theft tracking. Adaptive reporting gets most of the benefit at a fraction of the cost. For docked systems, the dock itself reports presence, so idle pings can be even rarer.
Pipeline.
- Bikes publish to an MQTT/IoT gateway (TLS, per-device credentials).
- The gateway writes to a partitioned log (Kafka) keyed by bike ID, so per-bike ordering holds.
- Stream consumers do three things independently:
- Update an in-memory geospatial index (Redis GEO, or a geohash/H3 cell to set of bikes mapping) holding only available bikes plus last position.
- Append raw points to a time-series/columnar store for trip replay, analytics and theft investigation.
- Emit state changes (not every ping) to the transactional DB, for example only when
last_seencrosses a threshold or the bike enters or leaves a zone.
- Map queries hit the geo index only: find cells covering the radius, fetch bikes, filter to
AVAILABLE.
Protecting the database. The transactional DB holds only state transitions and a periodically coalesced last_pos. Raw pings never touch it. Batch writes and keep only the latest position per bike per flush window.
Offline and out-of-order data. Each message carries a device timestamp and a monotonically increasing sequence number. Consumers apply a position only if the sequence is newer than what they hold. A bike not seen for N minutes is marked STALE and hidden from the map, so riders do not walk to a ghost. Devices buffer points while offline and upload them on reconnect; these go to history but do not override a newer live position.
Partitioning. Shard the geo index and stream partitions by city or region (and by H3 cell for large cities). This also keeps failures local.
3. Reservations, unlock and contention
Exactly one winner. Use an atomic conditional update on the bike record:
UPDATE bike
SET status='RESERVED', held_by=:rider, hold_expires_at=now()+interval '5 min', version=version+1
WHERE id=:bike AND status='AVAILABLE';
If one row is affected, the rider won; zero rows means someone else did, so return 409 and show alternatives. This is optimistic concurrency and needs no lock held across network calls. Alternatives: SELECT ... FOR UPDATE (correct but holds row locks, fine at this contention level), or Redis SET NX PX (fast, but then Redis and the DB can disagree, so the DB must remain the source of truth). A distributed lock service adds failure modes without benefit here. Also enforce a per-rider limit with a unique constraint or counter.
Expiry. Store hold_expires_at and treat an expired hold as available at read time (status='AVAILABLE' OR hold_expires_at < now() in the conditional update). A background sweeper (or delayed queue message) tidies up status and notifies the rider. Correctness never depends on the sweeper running on time.
Unlock with an unreliable device.
- The rider calls unlock with an idempotency key. The server verifies the hold belongs to them and creates a
TripinSTARTING. - The server sends a command with a unique
command_idand a short TTL to the bike. - The bike executes at most once per
command_id(it remembers recent IDs) and replies with an ack including lock state. - On ack, the server moves the trip to
ACTIVE, the bike toIN_USE, and starts billing from the bike's unlock timestamp. - On timeout, retry the same command a limited number of times, then fail the trip, release the bike to
AVAILABLEorOUT_OF_SERVICE, and show the rider an error. No billing starts without an ack. - A reconciliation job compares trip state with the bike's reported lock state; a bike reporting unlocked with no active trip is flagged, and the reverse is corrected.
Ending a trip. The rider taps end, or the bike reports lock closed inside a valid zone (or dock). The server closes the trip on the first valid signal and is idempotent for repeats. If the bike is unreachable, keep the trip ENDING_PENDING and tell the rider the bike has not confirmed. Billing can use the last confirmed position and time, with a cap and a grace period; on reconnect the buffered lock event finalizes the trip, and any difference is adjusted. Outside a valid zone, apply a fee or require the rider to move the bike.
Free-floating versus docked
Docked systems simplify end-of-trip validation and idle telemetry; free-floating needs geofencing, stronger anti-theft pings and more map clutter control (clustering at low zoom).
Observability
Track unlock success rate and latency, hold conflict rate, map data age (p95 of now - last_seen), stream consumer lag, and stuck trips by state.
Common mistakes
- Writing every GPS ping to the primary database.
- Using a distributed lock for reservations instead of a conditional write.
- Relying on a cleanup job for hold correctness.
- Treating unlock as fire-and-forget without ack, idempotency or reconciliation.
- Starting billing before the bike confirms it unlocked.
- Not stating requirements first, so ping rate and consistency choices look arbitrary.