Skip to main content

Ride Sharing Platform

1. Executive Summary​

A ride-sharing platform matches riders with nearby drivers in real time, manages trip lifecycle (request → match → pickup → dropoff → payment), and optimizes supply positioning. Principal-level design covers geospatial indexing, matching algorithms, location streaming, ETA estimation, surge pricing, and consistency under concurrent driver acceptance.

This chapter designs an Uber/Lyft-class system handling millions of concurrent drivers, 1M+ ride requests per hour peak, and sub-second match latency in dense urban markets. Geohash/quadtree indexes, dispatch service with optimistic locking, and explicit degradation during GPS outages are core interview topics.

2. Why This Topic Matters​

Ride-sharing interviews test real-time systems, geospatial data structures, and marketplace dynamics:

  • Nearest-neighbor search at scale with moving points.
  • Double-booking prevention when two riders match one driver.
  • Location update throughput (GPS every 1–4 seconds × millions).
  • Surge pricing coupling supply/demand signals.
  • Trip state machine reliability.

Production failures include wrong matches, pricing riots from surge bugs, and safety incidents from stale driver locations. Review System Design Methodology and Notification Platform.

3. Problems Being Solved​

ProblemSolution
Find nearby driversGeospatial index; radius query
Fair matchingBatching; scoring (ETA, rating, fairness)
Real-time locationWebSocket + stream processing
Prevent double assignTransactional driver lock
ETA accuracyRouting engine + traffic ML
Surge pricingSupply/demand ratio per geofence
Trip trackingTrip state machine + location history
PaymentsIntegrate payment platform post-trip

4. Assumptions and System Model​

Functional:

  • Rider requests ride with pickup/dropoff.
  • System matches driver; both see ETA and route.
  • Live trip tracking; cancel before/after match.
  • Rating and fare calculation at end.
  • Driver go online/offline; accept/reject offers.

Non-functional:

  • Match latency p99 < 3 s in urban core.
  • Location ingest 5M updates/sec global peak.
  • Trip state durability 99.999%.
  • GPS staleness > 30 s disqualifies driver from match.
AssumptionImplication
Drivers move continuouslyIndex must support frequent updates
Match is competitiveAtomic driver reservation
City-scale partitioningShard by geohash region
Network flakinessIdempotent trip APIs
Safety criticalStale location rejection

5. Essential Terminology​

TermDefinition
GeohashHierarchical spatial encoding string
QuadtreeRecursive spatial subdivision
H3Uber's hexagonal hierarchical geospatial index
DispatchService assigning rides to drivers
Supply heatmapDriver density per area
Surge multiplierPrice factor when demand > supply
GeofencePolygon region for pricing/rules
ETAEstimated time of arrival
Trip state machineREQUESTED → MATCHED → PICKUP → ONTRIP → COMPLETE
Offer timeoutSeconds driver has to accept
Ghost driverStale GPS showing available but not

6. Core Mechanism​

6.1 Architecture​

Figure 1: Location stream feeds geospatial index; dispatch queries nearby available drivers.

6.2 APIs​

POST /v1/trips { pickup, dropoff, ride_type }
→ { trip_id, status: SEARCHING }

GET /v1/trips/{id} (poll or WS push)

POST /v1/drivers/location { lat, lng, heading, ts }
POST /v1/drivers/status { online|offline }

POST /v1/drivers/offers/{id}/accept
POST /v1/drivers/offers/{id}/reject

WS /v1/stream → trip updates, driver location to rider

6.3 Data Model​

Trip:

trip_id, rider_id, driver_id?, status, pickup, dropoff,
fare_estimate, surge, created_at, matched_at

Driver state (Redis):

driver_id → { lat, lng, heading, status, trip_id?,
last_update_ts, vehicle_type }

Geospatial index:

  • Redis GEO / custom H3 cell → set of available driver_ids.
  • Updated on each location tick if status=available.

6.4 Deep Dives​

Matching algorithm:

  1. Rider requests trip; trip service creates SEARCHING record.
  2. Dispatch queries GEO: drivers within 3 km radius, status=available, fresh GPS.
  3. Score candidates: score = w1/ETA + w2*rating - w3*idle_time.
  4. Send offer to top driver; 15 s timeout.
  5. On accept: atomic SET driver status=busy IF available (Lua script).
  6. On reject/timeout: next candidate.

Figure 2: Dispatch offers sequentially with atomic driver lock on accept.

Location ingest scale:

  • 2M drivers × 0.5 Hz = 1M updates/sec.
  • Partition stream by geohash prefix.
  • Consumers update GEO index and trip tracking only.
  • Drop updates for offline drivers immediately.

Surge pricing:

  • Divide city into H3 cells (resolution 7–8).
  • Every 5 min: surge = f(demand_requests / supply_drivers) per cell.
  • Cap surge (e.g., 3×) for regulatory compliance.
  • Cache multipliers in Redis; pricing service reads at trip start.

Figure 3: Per-cell supply/demand ratio drives surge multiplier.

ETA service:

  • Precomputed road graph per metro.
  • Real-time traffic overlay from historical + live probes.
  • Cache route pickup→rider and rider→dropoff on match.

7. Step-by-Step Walkthrough​

7.1 Happy path match​

  1. Rider requests downtown SF pickup.
  2. GEO returns 8 drivers within 2 km; top ETA 4 min.
  3. Driver accepts in 8 s; lock succeeds.
  4. Rider sees driver approach on map via WS location stream.

7.2 Double-booking prevention​

  1. Two dispatch workers offer same driver (race).
  2. First accept sets busy; second accept fails lock.
  3. Second trip re-dispatches to next driver.

7.3 No drivers available​

  1. GEO returns empty within expanding radius (3→5→8 km).
  2. Trip stays SEARCHING; rider sees high ETA estimate.
  3. Surge may increase to attract supply.

7.5 Scheduled ride dispatch​

  1. User books airport ride for 6 AM tomorrow.
  2. Trip stored SCHEDULED; dispatch triggers at T-30 min.
  3. At trigger: transition to SEARCHING; normal match flow.
  4. No driver locked until dispatch window—avoids stale assignment overnight.

7.6 Pool ride detour constraints​

  1. Rider A and B share route with 10% detour cap.
  2. Match engine solves constrained optimization—NP-hard at scale; heuristic greedy in production.
  3. ETA shown includes pickup order; dynamic re-route on new pool member.

7B. Fraud and Safety Signals​

SignalAction
GPS teleport > 100 km/minExclude from match; fraud review
Payment chargeback historyRequire prepay
Driver rating < 4.0Lower match priority—not hard block without policy
Rider cancel rate > 50%Surge prepay or throttle

Safety architecture crosses engineering, legal, and ops—principal owns cross-functional requirements traceability.

10A. Dispatch Queue Depth​

During demand spike, requests queue rather than fail:

Queue depth 5000 × avg wait 30s → user-visible delay
Max queue policy: expand radius + surge + show honest ETA
Reject new requests only when queue &gt; 15 min estimated wait

Honest ETA reduces cancel rate—product metric tied to dispatch architecture.

PhaseKey decisions
Requirementsreal-time match, tracking, pricing
Scale1M loc/sec; city shard
APIstrip CRUD; driver location stream
DataRedis driver state; trip DB
Deep divesatomic lock; geospatial index

8. Invariants and Guarantees​

PropertyGuarantee
One active trip per driverEnforced by lock
Trip state monotonicValid transitions only
Fare lockSurge at request time or pickup—policy explicit
Location freshnessStale drivers excluded
Idempotent trip createclient_request_id dedup

9. Failure Scenarios​

ScenarioMitigation
Dispatch overloadQueue; expand match radius gradually
GEO index staleStream lag alert; fallback smaller radius
Driver accept timeoutOffer next; max 5 attempts
Payment failure post-tripTrip complete; billing retry + collections
Regional outageFailover dispatch region; read-only mode
Surge calculation bugCircuit breaker; cap multiplier

10. Performance Characteristics​

1M rides/day/city × 10 cities = 10M rides/day
Peak hour 3× → ~3500 rides/min/city
Match query: GEO radius &lt; 50 ms
Location write: 1M/sec sharded across 50 Kafka partitions
WebSocket fanout: 500K concurrent trip watchers

11. Scalability Limits​

LimitMitigation
Dense downtown GEO queryH3 cell pre-aggregation
Hot geofence surgePrecompute; local cache
Trip DB writesShard by city_id
WS gateway connectionsHorizontal scale; sticky sessions

12. Operational Considerations​

  • Metrics: match time, cancel rate, supply/demand ratio, GPS staleness %.
  • Alerts: zero supply cells; dispatch queue depth.
  • Runbooks: disable surge; manual driver reassign.
  • City launch playbook: seed supply incentives.

13. Security Considerations​

  • PII minimization in location logs.
  • Rider/driver phone number masking.
  • Fraud detection: GPS jump, emulator patterns.
  • Background check integration for drivers (compliance).
  • Rate limit trip requests per rider.

14. Cost Considerations​

Location ingest and map API calls dominate variable cost. Batch routing requests. Use open map data where licensed. Surge caps reduce regulatory risk vs revenue. Incentives to balance supply are marketing cost, not infra.

15. Production Implementations​

SystemNotes
UberH3 index public; microservices architecture
LyftSimilar dispatch patterns
DiDiHigh-scale emerging market constraints
GrabMulti-modal expansion

Note: Specific algorithms proprietary; patterns from public engineering talks.

16. Alternatives and Tradeoffs​

ApproachProsCons
Batch matching (5 s window)Global optimumHigher latency
Greedy nearestFastSuboptimal fleet util
Redis GEOSimpleLimited at huge scale
H3 / geohash cellsScalableTuning resolution
Central dispatchConsistentSingle region bottleneck
Peer-to-peer offer broadcastDecentralizedChaos at scale

16A. Driver Incentive vs Dispatch Architecture​

Surge pricing affects rider price; separate driver incentive bonuses (quest, heat map) affect supply without always raising rider fare—regulatory and PR sensitivity. Architecture: incentive service writes to driver app feed; pricing service writes rider estimate—decouple to avoid accidental 10× rider charge when boosting driver pay.

16B. Simulation and Load Testing​

Pre-launch city simulation:

  • Inject synthetic GPS streams at target driver density
  • Generate ride requests Poisson distribution peak hour
  • Measure match time p50/p99 vs supply
  • Chaos: kill GEO shard; verify graceful degradation

Simulation does not replace live pilot—human behavior differs—but catches order-of-magnitude capacity errors.

| "GPS always accurate" | Urban canyon, staleness | | "One DB for locations" | Stream + in-memory index | | "Surge is greedy only" | Supply incentive function | | "Match is instant globally" | City-sharded dispatch |

18.1 Accessibility and Inclusive Design​

Ride-sharing UX must serve users with disabilities: screen reader support for trip status, option to share trip with trusted contact, audio turn-by-turn. Engineering architecture enables via structured trip state API—not only graphical map. Regulatory jurisdictions increasingly mandate accessibility features; treat as non-functional requirement in launch checklist alongside p99 match latency.

18. Principal Architect Perspective​

  • Atomic driver lock is safety-critical—test race conditions.
  • Location pipeline is highest throughput component—design first.
  • Surge needs governance caps and audit trail.
  • ETA errors drive cancellations—monitor MAPE.
  • Degrade gracefully when routing API down—haversine fallback.

19. Architecture Review Exercise​

Scenario: MySQL query SELECT * FROM drivers WHERE distance < 3km every request.

Review: Replace with GEO index; in-memory driver state; partition by city.

20. Whiteboard Explanation​

"Drivers stream GPS to a partitioned Kafka topic. Consumers maintain an H3-cell index of available drivers in Redis with last-update timestamps. Rider trip request hits dispatch, which queries neighboring cells, scores by ETA, and offers sequentially. Accept uses atomic Redis Lua to set driver busy. Trip state in durable DB. WebSocket pushes driver location to rider. Surge pricing reads precomputed supply/demand ratios per H3 cell. Stale GPS excludes drivers from matching."

21. Interview Questions​

  1. Design Uber. — Signals: geo index, dispatch, location stream. Red flags: SQL distance scan.
  2. Geohash vs quadtree? — Signals: update cost, query shape. Follow-up: H3 benefits.
  3. Prevent double booking? — Signals: atomic lock, transaction.
  4. Scale location updates? — Signals: Kafka partition, batch index update.
  5. Matching algorithm? — Signals: ETA scoring, not just distance.
  6. Surge pricing design? — Signals: per-cell ratio, caps, audit.
  7. Driver rejects offer? — Signals: next candidate, timeout.
  8. Rider cancels after match? — Signals: state machine, driver release.
  9. ETA how computed? — Signals: routing graph, traffic.
  10. Shard by city? — Signals: geo locality, regulations.
  11. Ghost driver problem? — Signals: staleness threshold.
  12. Trip idempotency? — Signals: client_request_id.
  13. WebSocket vs poll? — Signals: WS for live map; poll fallback.
  14. Peak NYE dispatch? — Signals: pre-position supply, queue, surge.

21B. Extended Interview Question Deep Dives​

Q15 (Principal): City council caps surge at 2×; engineering has 5× in config.

Strong signals: Geo-fenced rule engine; config per market; audit trail; graceful clamp without error; test in staging with legal matrix. Red flags: "Surge is pure algorithm." Rubric: 5/5 includes regulatory config layer separate from demand ratio formula.

Q16 (Principal): Driver app offline 5 minutes mid-trip—rider sees frozen map.

Strong signals: Stale driver exclusion from new matches but trip in progress uses last known + "connection lost" UX; WS reconnect backoff; trip state durable in DB not Redis alone.

  1. Multi-stop trips. — Ordered waypoints; dynamic re-route.
  2. Regulatory data residency. — Trip data per country shard.

22A. Production Low-Level Design (Interview + Game Day)​

Dispatch LLD: location data plane (Kafka → geo index) vs trip control plane (durable DB + offer state machine).

Context diagram​

Step-by-step flow:

StepAction
1–2GPS → Kafka → hot geo index
3–4Trip request → nearby available drivers
5–6Offer / accept; push state to rider

Production stack​

LayerChoiceRole
Location busKafka by geohash/cityAbsorb 1M updates/sec
Driver stateRedisAvailable/busy + last GPS
Geo indexH3 cell → driver setSub-50ms match
Trip storePostgres / SpannerSource of truth
Offer lockRedis LuaPrevent double book
Maps / ETARouting cacheScore candidates
RealtimeRegional WSRider map

API + schema​

POST /v1/trips { pickup, dropoff, ride_type, idempotency_key }
POST /v1/drivers/location { lat, lng, ts, heading }
POST /v1/drivers/offers/{id}/accept
WS /v1/stream
EntityFields
tripstrip_id, rider_id, driver_id?, status, surge, pickup, dropoff
offersoffer_id, trip_id, driver_id, expires_at, status
Redis driver:{id}lat, lng, status, last_ts, trip_id?
Redis h3:{cell}SET of available driver_ids

Idempotency: create trip with client key; accept uses atomic SET driver busy IF available.

Happy-path sequence​

Failure path — accept race​

Observability + SLO​

SLIIdea
Match latencyp99 < 50–100ms geo query
Time-to-assignp95 < 30s
Double-assign rate0
Stale GPS exclusionfreshness < N seconds

22B. Game Day Playbooks​

Catalog​

IDDrillInjectSignal
GD-1City GPS flood5× location rateKafka lag; index delay
GD-2Accept stampede100 threads same driverZero double book
GD-3Redis geo flushFlush shardRebuild from stream
GD-4Surge 50× bugBad configHard cap; refunds
GD-5Routing API down5xx mapsHaversine fallback
GD-6WS region outageKill WS poolPoll fallback

GD-2 — Accept stampede (detailed)​

FieldDetail
InjectParallel accept on one driver
Detectdouble_assign_total must be 0
MitigateAtomic Lua / DB constraint
VerifyExactly one ASSIGNED winner
LearnRace test in deploy gate

GD-3 — Redis geo flush (detailed)​

Pass criteria: trip DB still source of truth; in-progress trips unaffected; match SLO recovers < RTO target.

23. Strong Answer Example​

Question: "How to find nearby drivers in 50 ms?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—precomputed H3/GEO index in memory, not SQL ORDER BY distance.

Figure A: PRACTICE map — walk the board in this order.


Student interview script (PRACTICE)​

P — Problem framing​

"Match must return candidates in tens of milliseconds. Scanning all drivers—or hitting the trip DB—fails at city scale. The hot path is a city-sharded in-memory geospatial index (H3 cells or Redis GEO) updated from the location stream, filtered by freshness and vehicle type, then scored by ETA."

R — Requirements​

TypeRequirement
FRNearby available drivers for pickup
NFRp99 lookup ~50 ms including score
SafetyExclude stale GPS / busy drivers
OpsPer-city shard; lag alerts

A — Assumptions​

AssumptionWhy
Drivers emit GPS at ~0.5–1 HzIndex stays warm
Kafka absorbs spikesIndex consumers batch
ETA cache existsScore ≠ raw distance

C — Capacity​

1M loc/s city → Kafka partitions by geohash
H3 res ~9: tens of thousands of cells
k-ring depth 1–2 first; expand if empty
Top-K score 20 candidates — not 2000

T — Topology​

Step-by-step flow:

StepAction
1Map pickup → H3 cell
2Union k-ring available sets
3Filter freshness / type
4Score ETA; offer

I — Invariants​

  1. Busy drivers not in available sets.
  2. Stale GPS excluded from new matches.
  3. Accept uses atomic lock.
  4. Trip DB durable; Redis ephemeral rebuildable.

C — Constraints​

ConstraintResponse
Empty ringExpand radius / wait / fail gracefully
Cross-cityShard dispatch; no global scan
Redis lossRebuild from Kafka; degrade match quality briefly

E — Evolution​

GEO MVP → ETA scoring → surge cells → predictive positioning (offline ML, not on match hot path).


Closing line (interview)​

"Maintain an H3/GEO index of available drivers from Kafka GPS. Match does k-ring → filter freshness → ETA score → offer. No DB scan. Lua lock on accept. Trip state durable in DB."

Scoring signals​

StrongWeak
H3/GEO hot indexSQL scan all drivers
Freshness filterIgnore stale GPS
Atomic accept lockCheck-then-set race
BOE on loc/sNo numbers

Compact outline (if time-boxed to 2 minutes)​

"Maintain an H3/GEO index of available drivers from Kafka GPS. Match does k-ring → filter freshness → ETA score → offer. No DB scan. Lua lock on accept. Trip state durable in DB."

24. Weak Answer Example​

Weak: "Query all drivers and sort by distance in application."

Red flags: O(n) scan, no scale, no staleness, no locking.

25. Hands-On Exercise​

  1. Implement H3 k-ring driver lookup mock.
  2. Atomic busy lock with Redis Lua script.
  3. Simulate offer timeout and re-dispatch.
  4. Load test 100K location updates/sec to index.
  5. Extension: Surge calculator from request/driver counts.

25A. Extended Hands-On Lab​

  1. Build surge calculator from CSV of requests/drivers per cell; visualize heatmap.
  2. Chaos: freeze GEO index updates 60s; measure match quality degradation.
  3. Simulate driver accept race with 100 concurrent threads on same driver_id.
  4. Principal lab: Draft regulatory matrix of surge caps per city in config schema.

25B. Production Readiness Review Questions​

  • What is rider experience when zero drivers in 8 km radius?
  • Can driver reject without penalty abuse throttle?
  • Is trip state recoverable if Redis entirely flushed?
  • How are safety incidents correlated across logs, metrics, and trip ID?

Ride-sharing launches require ops playbooks beyond happy-path diagrams.

  1. Trip state transitions?
  2. Surge formula inputs?
  3. When exclude driver from match?

27. Flashcards​

FrontBack
H3Hexagonal hierarchical geospatial index
DispatchRide-to-driver assignment service
Surge multiplierDemand/supply price factor
Atomic driver lockPrevents double assignment
GPS stalenessExclude if update too old
GeofenceRegional pricing/rules polygon
Offer timeoutWindow for driver accept
Trip state machineLifecycle status enforcement
k-ringH3 neighbor cells for search
Supply heatmapDriver density visualization

28. Cheat Sheet​

REQUIREMENTS: request, match, track, pay, surge
SCALE: 1M GPS/sec; city-sharded dispatch
APIs: trip CRUD; location stream; offer accept
DATA: trip DB; Redis driver+geo; location Kafka
ARCH: ingest → geo index → dispatch → WS
DEEP: atomic lock; ETA scoring; surge cells
RELIABILITY: idempotent trip; state machine
SECURITY: fraud GPS; PII masking
OPS: match latency; supply/demand alerts

17A. Failure Scenario Drill​

Surge pricing bug sets 50× multiplier citywide during routine deploy—regulatory investigation and rider refunds. Mitigation: hard cap 3×; canary deploy pricing rules; shadow mode compare old vs new multiplier 24h before enable. Principal requires financial impact review on pricing code same as payment service.

18.1 Supply Positioning (Advanced)​

Predictive model pre-positions drivers to high-demand cells before event ends—separate ML pipeline feeding driver incentives, not blocking match hot path. Match still uses real-time GEO index; positioning is minutes-ahead optimization.

19A. Extended Review Scenario​

Scenario B: WebSocket gateway single region; cross-region riders see 5s location delay.

Review: Regional WS pools; driver location published to rider's region via internal bus; cap cross-region fanout.

21A. Additional Interview Questions​

  1. Wheelchair accessible vehicle filter? — Signals: attribute filter in GEO query before scoring. Follow-up: fallback if none available.
  2. Regulatory cap on surge? — Signals: geo-specific max; audit log of multiplier changes.

28A. Principal Interview Deep Dive​

Match radius expansion strategy​

Start 2 km → 3 → 5 → 8 km with 2s between expansions; avoid querying 20 km on first attempt (latency + unfair distant assign).

Location update frequency tradeoff​

IntervalProsCons
1sSmooth map2× ingest vs 2s
4sLower costStaler match
AdaptiveFast when on tripComplex

Trip state durability​

Trip DB is source of truth—Redis driver state ephemeral rebuilt from stream on crash. Never complete payment without durable trip record in COMPLETE state.

28B. Extended BOE Walkthrough​

Interviewer: "2M drivers, 50K rides/minute peak in one city."

Strong candidate:

"Location: 2M × 0.5 Hz = 1M updates/sec city—Kafka partitioned by geohash.

Match: GEO index H3 cells; query k-ring; score ETA not distance. Atomic Redis lock on accept.

50K rides/min ≈ 833/sec dispatch—each match <50ms index + offer loop.

Surge per H3 cell every 5 min. WS fanout for live map.

Payment post-trip via Payment Platform. Notify via Notification Platform."

30. References​

  • Uber H3 documentation — hexagonal index (open source).
  • Uber engineering blog — dispatch and surge posts (implementation anecdotes).
  • Kleppmann, DDIA — stream processing.

Distinction: H3 is open specification; matching scoring is proprietary.

30A. Further Reading Paths​

Integrate Distributed Rate Limiter on trip request API. Study Idempotency for trip create dedup.

30B. Marketplace Fairness Considerations​

Drivers with low acceptance rate may be deprioritized—product policy not just engineering. Document scoring weights and audit for bias (geographic redlining risk if surge ignores underserved areas). Principal architects engage policy/legal on surge caps.

30D. Principal Architecture Review Checklist​

  • Driver atomic lock tested under concurrent accept race (chaos test)
  • GPS staleness threshold enforced in match query—not post-filter only
  • Surge multiplier hard cap configured per regulatory region
  • Trip state machine transitions validated—no illegal jumps
  • Location ingest partitioned; lag alert < 30s at p99
  • WebSocket + backup poll both operational in mobile clients
  • Fraud signals documented with human review queue SLA
  • Payment integration idempotent post-trip—see Payment Platform

Ride-sharing combines real-time geo, marketplace fairness, and safety—principal review spans product policy not only QPS math.

30F. Closing Principal Note​

Ride-sharing systems sit at the intersection of real-time engineering, marketplace economics, and public safety. Technical interviews focus on GEO indexes and locking; production success requires surge governance, accessibility, fraud pipelines, and honest ETA communication when supply is constrained.

30G. Regulatory and Market Variation​

Launch playbooks must vary by city: some jurisdictions ban surge entirely; others require driver background check data residency. Architecture supports feature flags and config per geofence—not hardcoded global constants. Legal review precedes enabling pricing experiments in new markets.