Ride-Hailing Platform (Uber-like)

Real-time driver location ingestion, geospatial indexing with H3, dispatch and matching, surge pricing, the trip state machine, payments and multi-city operations.

[!FACT] Public context Uber open-sourced H3, a hexagonal hierarchical geospatial index, and has published engineering posts about its dispatch, Ringpop (now archived), Cadence (workflow engine, forked as Temporal) and Kafka-heavy architecture. Details below are a generic design, not Uber's current internals.

[!ASSUMPTION] Scope "GoRide", a hypothetical ride-hailing app in 300 cities, 5 M rides/day. Numbers are assumptions.

1. Business problem and objectives

Match riders and drivers quickly and fairly, price dynamically, and run trips safely and reliably at city scale. Objectives:

  • Median time-to-match < 10 s; p95 pickup ETA error < 2 min.
  • Trip state never lost (a trip in progress must survive any server failure).
  • Surge pricing that balances supply and demand within minutes.
  • Launch a new city in weeks with local regulations, payments and vehicle types.

2. Business model and revenue generation

Stream Notes
Commission/take rate on fares Typically a share of each fare; varies by market
Surge/dynamic pricing Increases supply at peak, increases revenue
Subscriptions Rider memberships (discounts), driver subscriptions in some markets instead of commission
Delivery/adjacent services Reuse dispatch and maps for food/parcels
Ads In-app and in-car ads

3. Functional requirements

  1. Rider: set pickup/destination, see fare estimate and ETA, request ride, track driver, pay, rate.
  2. Driver: go online/offline, receive offers, accept/decline, navigate, start/end trip, earnings.
  3. Dispatch: find and offer the best driver(s) for each request.
  4. Pricing: base fare + time/distance + surge; upfront fares.
  5. Trip lifecycle: requested → matched → driver arriving → on trip → completed/cancelled.
  6. Payments: card/wallet/cash, driver payouts, receipts.
  7. Safety: SOS, trip sharing, driver verification, anomaly detection (long stops, route deviation).
  8. Ops: city configuration, promotions, support tools.

4. Non-functional requirements

Attribute Target
Location freshness Driver positions updated every 4 s; index reflects within 1 s
Matching latency Decision < 2 s after request (excluding driver acceptance)
Availability 99.99% for request and trip state
Consistency A driver can be assigned to only one active trip; a trip's state transitions are serializable
Scale 1 M concurrently online drivers; 250K location updates/s
Data Trip records retained for regulatory periods; PII minimized

5. Expected user base and traffic assumptions

  • 5 M rides/day; peaks of ~300 ride requests/s globally (rush hours per timezone), up to 5× on New Year's Eve.
  • 1 M online drivers at peak × 1 update/4 s = 250K updates/s.
  • Each request triggers geo-queries for candidates in rings of H3 cells, ETA computations for ~20 candidates.
  • Location history: 250K/s × 100 bytes ≈ 25 MB/s ≈ 2 TB/day.

6. High-level architecture

  • Edge/API: mobile apps via gateway; persistent connections (WebSocket/MQTT/gRPC streaming) for real-time updates to riders and drivers.
  • Location service: ingests GPS updates, filters/snaps to roads, updates the geospatial index and publishes location streams.
  • Supply index: in-memory index of available drivers per H3 cell, partitioned by city/region.
  • Dispatch/matching: selects candidates, computes ETAs, optimizes assignment, sends offers.
  • Pricing/surge: computes demand/supply per cell and multipliers.
  • Trip service: durable state machine for each trip.
  • Maps/ETA: routing engine plus ML ETA corrections.
  • Payments, notifications, safety, analytics.

7. Detailed component architecture

Component Design choice Reason
Location ingestion Stateless gateways → Kafka partitioned by driver ID High write rate, replay for analytics
Supply index In-memory H3 cell → set of available drivers, sharded by city (and by H3 parent cell for big cities) Microsecond neighbour lookups; data is ephemeral
Dispatch Per-city dispatch workers; batched matching every 1–2 s per area Global optimization beats greedy nearest-driver
ETA service Road graph routing (OSRM/Valhalla/own) + ML correction model Accurate pickup ETAs
Surge Stream processing per H3 cell (requests vs available drivers, 1–5 min windows) Fast reaction to imbalance
Trip service Durable workflow (Temporal/Cadence) or event-sourced state machine on a strongly consistent store Trip must survive failures
Driver state Single owner per driver (online, offered, on trip) with conditional updates Prevents double assignment

8. Architecture diagram

flowchart LR
  DRV[Driver app] -->|GPS every 4 s| LOC[Location ingestion]
  LOC --> K[[Kafka: locations]]
  K --> IDX[Supply index<br/>H3 cells, per city]
  K --> SURGE[Surge engine<br/>Flink per H3 cell]
  K --> LAKE[(Location history lake)]
  RID[Rider app] -->|request ride| API[API gateway]
  API --> PRICE[Pricing / upfront fare]
  PRICE --> SURGE
  API --> DISP[Dispatch / matching<br/>batched per area]
  DISP --> IDX
  DISP --> ETA[ETA service<br/>routing + ML]
  DISP -->|offer| PUSHC[Real-time channel] --> DRV
  DRV -->|accept| TRIP[Trip service<br/>durable state machine]
  TRIP --> DB[(Trips DB<br/>strongly consistent)]
  TRIP --> PAY[Payments]
  TRIP -->|status updates| PUSHC --> RID
  TRIP --> SAFE[Safety monitoring]

9. Frontend architecture

  • Native rider and driver apps; driver app optimized for battery and poor connectivity (batch GPS points when offline, upload on reconnect).
  • Map rendering with vector tiles; smooth driver marker animation by interpolating between updates.
  • Real-time channel (WebSocket/MQTT/gRPC stream) for trip updates; fall back to push notifications.
  • Server-driven configuration per city (vehicle types, payment methods, regulatory notices).

10. Backend architecture

  • Services in Go/Java; dispatch-critical paths in memory with periodic state snapshots.
  • Partitioning by city as the primary scaling and isolation unit: an outage in one city's dispatch does not affect others.
  • Trip workflow example: REQUESTED → (match) → DRIVER_ASSIGNED → ARRIVED → IN_PROGRESS → COMPLETED; timers for driver acceptance (15 s), rider no-show (5 min), cancellation fees.
stateDiagram-v2
  [*] --> REQUESTED
  REQUESTED --> SEARCHING
  SEARCHING --> OFFERED: candidate chosen
  OFFERED --> SEARCHING: decline / timeout 15 s
  OFFERED --> DRIVER_ASSIGNED: accept (driver lock acquired)
  SEARCHING --> NO_DRIVERS: timeout 3 min
  DRIVER_ASSIGNED --> ARRIVED
  DRIVER_ASSIGNED --> CANCELLED: rider/driver cancel
  ARRIVED --> IN_PROGRESS: start trip
  ARRIVED --> CANCELLED: no-show fee
  IN_PROGRESS --> COMPLETED: end trip, fare computed
  COMPLETED --> [*]
  CANCELLED --> [*]
  NO_DRIVERS --> [*]

11. API design with sample endpoints

POST /v1/fare-estimates    { pickup: {lat,lng}, dropoff: {lat,lng}, product: "standard" }
  -> { fareId, amount, currency, surgeMultiplier, expiresAt, etaSeconds }
POST /v1/rides             Idempotency-Key: ...   { fareId, pickup, dropoff, paymentMethodId }
  -> 201 { rideId, status: "SEARCHING" }
GET  /v1/rides/{rideId}
POST /v1/rides/{rideId}/cancel
POST /v1/driver/status     { online: true }
POST /v1/driver/offers/{offerId}/accept
WS   /v1/realtime          (trip updates, driver location for rider, offers for driver)

Location update (driver, compact):

{ "d": "drv_4471", "lat": 12.97161, "lng": 77.59456, "h": 182, "s": 8.2, "acc": 6, "t": 1795200000 }

12. Database schema and data model

CREATE TABLE trip (
  trip_id text PRIMARY KEY, city_id int NOT NULL, rider_id text NOT NULL, driver_id text,
  status text NOT NULL, product text, fare_id text, quoted_amount numeric(10,2),
  final_amount numeric(10,2), currency char(3), requested_at timestamptz, completed_at timestamptz,
  pickup geography(Point), dropoff geography(Point), version int NOT NULL
);
CREATE TABLE driver_state (
  driver_id text PRIMARY KEY, city_id int, status text CHECK (status IN ('OFFLINE','AVAILABLE','OFFERED','ON_TRIP')),
  current_trip_id text, version bigint
);
-- Assign atomically: succeeds only if the driver is still available or holding this offer
UPDATE driver_state SET status = 'ON_TRIP', current_trip_id = :trip, version = version + 1
 WHERE driver_id = :driver AND status IN ('AVAILABLE','OFFERED') AND version = :expectedVersion;

Supply index (in memory): H3 cell (res 8–9) → set<driverId>; driverId → {cell, lat, lng, heading, vehicleType, lastSeen}.

13. Database technology selection and reasoning

Data Store Reason
Live locations In-memory index (custom or Redis GEO/H3 sets) + Kafka Ephemeral, extremely high write rate
Trips, driver state Distributed SQL or sharded PostgreSQL by city; or Temporal persistence Correctness of assignment and state transitions
Location history Object storage (Parquet) + analytics engines Cheap, used for ETA/ML training and disputes
Payments Relational + ledger Money correctness
Maps data Routing engine graph files per region Specialized

14. Authentication and authorization

  • Riders: phone OTP or social login, device binding, risk checks on new devices.
  • Drivers: background checks, document verification, periodic selfie re-verification to prevent account sharing.
  • Tokens scoped to role; riders can see a driver's location only during an active trip.
  • Ops tools: RBAC by city and function; audited access to trip and location data.

15. Security architecture

  • Location data is highly sensitive: encrypt at rest, strict access, retention limits, aggregate/anonymize for analytics.
  • Phone number masking via proxy numbers for rider-driver calls.
  • GPS spoofing detection (impossible speeds, mock location flags).
  • Payment data via PSP tokens; fraud checks on new accounts and promotions abuse.

16. Caching strategy

  • Fare estimates cached briefly per origin/destination cell pair and surge state.
  • Road graph and ETA model in memory on ETA servers.
  • City configuration cached and versioned.

17. Messaging and event-driven architecture

  • Kafka topics: driver-locations (partitioned by driver), ride-requests, trip-events, surge-updates.
  • Stream processing (Flink) for surge, ETA feature aggregation, safety anomaly detection (route deviation, long unexpected stops).
  • Trip events feed payments, receipts, ratings, analytics.

18. Cloud deployment architecture

  • Regions close to served cities; each city assigned to a home region; dispatch shards per city.
  • Active-passive or active-active per region pair; driver/rider apps reconnect to the healthy region.
  • Real-time gateways on dedicated node pools tuned for connections.

19. CI/CD and DevOps

  • City-by-city rollout of dispatch changes; simulation of matching algorithms on recorded demand/supply before release.
  • Feature flags per city for pricing and product experiments.
  • A/B testing for dispatch and surge with marketplace-level metrics (switchback experiments, because riders and drivers interact).

20. Monitoring and observability

  • Marketplace health per city: open requests, available drivers, match rate, ETA, cancellation rate, surge level.
  • Location ingestion lag; supply index staleness.
  • Trip state anomalies (trips stuck in a state beyond expected duration).

21. Scalability and performance optimization

  • Drop or coalesce stale location updates under load (latest position wins).
  • H3 hierarchical cells: search the k-ring of neighbouring cells, expand rings until enough candidates.
  • Batch matching: every 1–2 s solve an assignment problem per area (e.g. Hungarian algorithm or min-cost flow) to minimize total pickup time.
  • Precompute ETA for popular cell pairs; cache routing results.

22. High availability and disaster recovery

  • Supply index rebuilt within seconds from the location stream after a failure.
  • Trip state durable before acknowledging transitions; dispatch failure only delays matching.
  • Region failover: apps reconnect; in-progress trips continue (the driver app keeps the trip locally and syncs).

23. Cost optimization

  • Ephemeral data in memory, not databases.
  • Location history compressed and downsampled for long-term storage.
  • Spot instances for batch ML (ETA training); right-size per-city dispatch.

24. Architecture trade-offs and alternatives

Decision Chosen Alternative Trade-off
Matching Batched optimization Greedy nearest driver Better global ETA vs slightly longer decision time
Geo index H3 hexagons Geohash, quadtree, S2 Uniform neighbours and distances vs ecosystem familiarity
Partitioning By city By global user ID Locality and isolation vs uneven city sizes
Trip orchestration Durable workflow engine Hand-written state machine on DB Built-in timers/retries vs one more platform

25. Technology stack recommendations

Go/Java services; Kafka; Flink; Redis or custom in-memory geo index with H3 library; PostgreSQL/CockroachDB/Spanner; Temporal; OSRM/Valhalla or a maps provider; Kubernetes; ML platform for ETA and fraud; OpenTelemetry.

26. Common architecture mistakes

  1. Storing every location update in a relational database.
  2. Greedy assignment that sends two offers to the same driver or assigns one driver to two trips.
  3. Trip state held only in memory of a dispatch node.
  4. Using geohash rectangles without handling edge effects (nearby points in different cells).
  5. Not testing surge algorithms for feedback loops (oscillating prices).

27. Senior architect interview questions and answers

How do you prevent two riders from being matched with the same driver?

The driver has a single authoritative state record. Assignment uses a conditional update (compare-and-set on status/version); only one succeeds. Offers are exclusive with a timeout; the dispatcher only offers drivers marked AVAILABLE, and marks them OFFERED atomically.

How do you find the nearest drivers quickly?

Convert the pickup point to an H3 cell, look up drivers in that cell and its k-ring neighbours from the in-memory index, filter by vehicle type and freshness, then rank by road ETA (not straight-line distance) for the top candidates.

How do you compute surge?

Stream per H3 cell: demand (requests, app opens) vs supply (available drivers) over short windows; map the ratio to a multiplier with smoothing and caps; publish to pricing. Guard against oscillation with hysteresis.

28. Enterprise architect interview questions and answers

How would you structure the platform to support food and parcel delivery later?

Extract shared capabilities (location, dispatch, ETA, payments, identity) as platform services with clear APIs, and build vertical products on top. Governance ensures verticals reuse rather than fork dispatch.

How do you handle different regulations per city?

City configuration as data (pricing rules, data retention, licensing checks), policy engine for compliance checks, and regional data residency where required.

29. CTO-level business and technology questions

Which metrics matter most to the business?

Completed trips, time-to-match, ETA accuracy, cancellation rates, driver utilization and earnings per hour, take rate, and contribution margin per trip.

Where should you invest in ML first?

ETA accuracy (drives matching and customer trust), then dispatch optimization and pricing, then fraud and safety.

30. Real-world implementation roadmap

Phase Duration Outcomes
1. Single-city MVP 0–4 months Request/match/trip/pay, greedy matching, basic pricing
2. Real-time platform 3–8 months Kafka, H3 supply index, real-time channels, durable trip workflows
3. Marketplace optimization 6–12 months Batched matching, surge, ML ETAs
4. Multi-city scale 9–18 months City partitioning, regional deployments, city configuration
5. Platform expansion 15+ months Delivery verticals on shared dispatch and payments