Pooled Rideshare Dispatch: Matching, Booking and Live Tracking
System DesignModel answerLast updated
Design a backend that pools riders into shared vehicles, matches within 2 seconds at 10k requests/s, prevents double-booking, and streams vehicle positions to riders.
Design a Pooled Ride Dispatch Platform
You are building the backend for a ride-hailing product where several riders heading in roughly the same direction can share one vehicle. Describe how you would design it.
What the system must do
- Request a ride. A rider submits a pickup point, a drop-off point, and the number of seats needed.
- Find a vehicle. The system looks for a vehicle that can take the new rider without pushing any rider already on board past their promised latest arrival time.
- Reserve. Seat and vehicle are claimed together as one atomic step. A ride moves through these states: Requested, Matched, PickingUp, EnRoute, DroppedOff.
- Live tracking. Riders see their assigned vehicle's position update in real time.
- Cancellation. A rider may cancel at any point before drop-off, and the freed capacity must be reusable.
Non-functional targets
- Speed: a match decision within 2 seconds.
- Correctness: no seat is ever sold twice, even when several requests race for the same vehicle.
- Scale: 10,000 ride requests per second and millions of vehicles online.
- Privacy: exposed location data must follow masking or obfuscation rules.
What to cover in your answer
- Overall architecture and the communication protocols you pick (for example gRPC, WebSockets, a message bus).
- How vehicle positions are stored and queried spatially (geohash, H3, quadtree, spatial DB, and so on).
- The matching logic, including how seat capacity and detour limits are enforced.
- The data model for ride state and how you handle concurrent bookings.
- Failure handling and the main trade-offs you made.
Hints
Hint 1
Do the arithmetic first: millions of vehicles reporting every few seconds produces far more writes than 10k ride requests per second. Let that split the design into a heavy tracking path and a smaller, strongly consistent booking path, and shard both by city or region.
Hint 2
Treat matching as a two-stage funnel: a cheap spatial lookup returns a few dozen nearby candidates, then for each one you try inserting the new pickup and drop-off into its existing stop list, checking capacity and every rider's deadline, and only call an exact routing engine on the best few.
Hint 3
The contended object is the vehicle's ordered stop plan. Put a version number on it and commit with a compare-and-set in the same transaction that writes the ride row; on conflict, re-evaluate that vehicle or fall back to the next candidate instead of taking a distributed lock.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
- Requests: 10k/s at peak, with a 2 s p99 match budget.
- Vehicles: about 2M online, each reporting every ~4 s, so roughly 500k location writes/s. Tracking traffic dominates, not bookings.
- Pooling limits (assumed, state them aloud): at most 4 seats, about 6-8 planned stops per vehicle, pickup ETA under ~8 min, and a detour cap such as "no more than 1.4x the direct trip time or +10 min, whichever is smaller".
- Consistency: strong for seat and plan assignment; eventual for tracking and analytics.
- Key insight: nearly everything is city-local, so partition by region. A request in one city never needs data from another.
2. Interfaces
POST /rideswith origin, destination, seats and an idempotency key (retries return the same ride).GET /rides/{id}andPOST /rides/{id}/cancel.- Riders get updates over a WebSocket (push notification as fallback).
- Vehicles hold a long-lived bidirectional gRPC stream: telemetry up, route-plan updates down.
- Internal synchronous calls use gRPC; state changes and tracking flow through Kafka topics.
3. Data model
- Ride: id, rider, region, origin, destination, seats, status, vehicle_id, latest_arrival, version.
- VehiclePlan (the contended record): vehicle_id, capacity, status, ordered
stops[](ride_id, PICKUP or DROPOFF, location, ETA),version. - RideEvent: append-only log of transitions for audit and replay.
State machine: Requested -> Matched -> PickingUp -> EnRoute -> DroppedOff, with Cancelled and Unmatched as exits. Each transition is a conditional update (WHERE status = :expected), so duplicate or out-of-order events become harmless no-ops.
Store: a strongly consistent, horizontally scalable database (Spanner, CockroachDB, or Postgres sharded by region). Every write includes an outbox row in the same transaction; a relay publishes it to Kafka so downstream consumers (notifications, pricing, analytics) never miss an event.
4. Architecture
- Tracking path: vehicles -> ingest service -> Kafka (
key = vehicle_id) -> in-memory geo index and a tracking fan-out service -> WebSocket gateways -> riders. - Booking path: rider -> API gateway -> ride service -> regional matcher -> geo index, routing/ETA service, trip store.
- The tracking path never touches the booking database, so a location storm cannot slow down reservations.
5. Geospatial index
- Use H3 hexagons at resolution 8-9 (~0.5 km). Neighbor distances are uniform, avoiding geohash edge artifacts. A quadtree also works; Redis GEO is fine at smaller scale.
- Each regional shard holds two in-memory maps:
cell -> vehiclesandvehicle -> {position, free seats, plan summary}. - 500k writes/s globally is only tens of thousands per second for a large city, which a few replicas absorb.
- Query: take the k-ring around the pickup cell, growing k until ~50-100 candidates with enough free seats are found. Include vehicles heading toward the pickup, not just the closest ones.
- The index is a cache derived from the stream, so a crashed node recovers in seconds by replaying.
6. Matching
- Retrieve candidates (~10 ms).
- Insertion search: for each candidate with stops s1..sn, try every pickup slot i and drop-off slot j >= i (O(n^2), n <= 8). Reject an insertion if:
- occupancy exceeds capacity anywhere along the route;
- any existing rider's arrival would pass their deadline;
- the new rider's wait or detour exceeds the caps.
- Score feasible insertions: added vehicle time + alpha x delay imposed on existing riders + beta x new rider's wait.
- ETA accuracy: prune with a cheap estimate (haversine x road factor, or a cached cell-to-cell time matrix), then call the routing engine only for the top ~10 insertions.
- Fallback: if nothing is feasible, offer a solo ride or mark Unmatched and retry shortly.
Budget: ~100 candidates x ~30 insertions = ~3k cheap evaluations plus ~10 routing calls, comfortably under 500 ms.
7. Concurrency
Two matchers may choose the same vehicle simultaneously. Use optimistic concurrency on VehiclePlan:
UPDATE vehicle_plan SET stops = :new, version = version + 1
WHERE vehicle_id = :vid AND version = :read_version;
-- same transaction: insert ride (Matched) and outbox event
- Zero rows updated means another match won. Re-read that plan and re-run the insertion, or move to the next-best candidate. Cap at 2-3 retries to protect the latency budget.
- Why not distributed locks: extra round trips and lease-expiry failure modes, while per-vehicle contention is low.
- Lower contention further: route all matching for a region or H3 parent cell to one single-writer matcher partition so most conflicts serialize in-process; CAS remains the safety net at borders.
- Duplicate submissions: a unique constraint on the idempotency key returns the existing ride.
- If drivers must accept: hold the insertion as
PENDINGwith a ~15 s TTL, then confirm or expire and release the seats.
8. Cancellation
Cancel is another conditional transition. Remove that rider's pickup and drop-off stops from the plan (CAS again), recompute ETAs for the remaining riders, and push the new route to the vehicle. If the rider is already on board, the vehicle may need to complete the drop-off or an unscheduled stop; charge policy is a product decision. Freed seats immediately re-enter the index.
9. Tracking and privacy
- The fan-out service sends a vehicle's position only to riders currently assigned to it, via a rider-to-vehicle subscription map.
- Throttle to 1 update every 1-2 s and send deltas.
- Privacy: never reveal other riders' exact pickup or drop-off points to a co-rider; show only the next relevant stop. Snap or coarsen positions before pickup, reveal precise location only for the assigned vehicle, apply retention limits to location history, and restrict internal access.
10. Failure modes and trade-offs
- Matcher crash mid-booking: the transaction either committed or did not; idempotency keys make the client retry safe.
- Stale geo index: acceptable, because the CAS and a final feasibility check on the real plan catch it.
- Region failover: replicate the trip store synchronously within a region's zones; rebuild the geo index from Kafka.
- Trade-off: greedy insertion is fast but not globally optimal. Batching requests for a 1-2 s window and solving a small assignment problem improves efficiency at the cost of latency.
Common mistakes
- Sizing for 10k RPS and ignoring the 500k/s location stream.
- Using a global lock or a single database for all cities.
- Checking deadlines only for the new rider, forgetting riders already on board.
- Putting tracking traffic through the transactional store.
- Skipping idempotency, which creates duplicate rides on retry.