Design Ride Hailing: Live Locations, Matching, Trip State and Payments at City Scale
It is 23:40 on a Saturday and a stadium concert has just ended. Forty thousand people open the app within ten minutes, all inside a few square kilometres. Two thousand drivers are nearby, every one of them sending a GPS fix every 4 seconds. The dispatch system has to decide, for each rider, which driver to offer the trip to, and it has to make sure that no driver is ever handed two riders at once, even while the matching service for that city is failing over.
Meanwhile prices in the cells around the stadium are rising because demand is ten times supply, riders are watching a car icon crawl across the map, and the card processor in one country is timing out on 8% of authorizations.
Ride hailing is the hardest of the four capstones because almost every part is real time and every part is coupled: location feeds matching, matching feeds trips, trips feed payments, and all of it feeds pricing. This walkthrough uses the system design framework and links to the concept articles where each building block is taught.
1. Requirements
Functional
- Rider: see nearby cars and a price quote with an ETA, request a ride, see the driver approach live, ride, pay automatically, rate.
- Driver: go online and offline, stream location, receive trip offers, accept or decline, navigate, start and end trips, see earnings.
- Matching: pick a good driver for each request, by pickup ETA rather than straight-line distance.
- Trip lifecycle: a clear state machine from request to payment, with cancellations by either side.
- Pricing: base fare plus distance and time, with surge pricing when demand exceeds supply in an area.
- Payments: authorize at request, charge the final fare at the end, pay drivers out.
Non-functional
- Freshness: driver positions in the matching index are at most a few seconds old.
- Latency: a nearby-drivers query in under 100 ms server side; a driver offered within a couple of seconds of a request.
- Correctness: one driver, one active trip. One trip, one charge. These are the two invariants you never trade away.
- Availability: the request-and-match path is the business; aim for 99.99% per city. Analytics and history can degrade.
- Isolation: a failure in one city or region must not take down others.
Out of scope
Shared or pooled rides, food delivery, driver onboarding and background checks, map tile serving and fraud models beyond a mention. Say so early and spend the time on location, matching and the trip lifecycle.
2. Estimation
Work through the numbers with the method in back-of-envelope estimation. To see location ingestion in the calculator, treat drivers as users: enter 1,000,000 users, 10,800 writes per user per day (one fix every 4 seconds for about 12 online hours), an object size of 0.1 KB and a peak factor of 2. The write rate dwarfs everything else in the system.
The shape is clear: a modest transactional core (175 trips per second) sitting on a very large stream of ephemeral location data. The design choice that follows is to treat locations as soft state, held in memory and rebuilt from the next updates, and to treat trips and payments as hard state with strong guarantees.
3. API
Drivers and riders hold a persistent connection to a connection gateway for anything real time, and use plain request-response APIs for everything else. The real-time options are compared in polling, SSE, WebSockets and webhooks.
POST /v1/quotes
{ "pickup": [12.9716, 77.5946], "dropoff": [13.1986, 77.7066], "product": "standard" }
200 OK
{ "quote_id": "q_8f2...", "fare_estimate": 640, "currency": "INR",
"surge_multiplier": 1.4, "pickup_eta_s": 240, "expires_at": "2026-11-30T23:47:00Z" }
POST /v1/trips
Idempotency-Key: 3b9e...
{ "quote_id": "q_8f2...", "payment_method_id": "pm_41..." }
202 Accepted
{ "trip_id": "t_77a...", "state": "MATCHING" }
POST /v1/trips/t_77a.../cancel
POST /v1/driver/offers/o_19c.../accept -> 200 or 409 if the offer expired
POST /v1/driver/trips/t_77a.../start
POST /v1/driver/trips/t_77a.../complete
Driver connection, upstream every 4 s:
LOCATION driver_id lat lng heading speed accuracy client_ts seq
Driver connection, downstream:
OFFER offer_id trip_id pickup eta expires_in=15s
Rider connection, downstream:
TRIP_UPDATE trip_id state driver_position eta
The quote ID locks the price the rider saw for a few minutes, so surge changing between quote and request never surprises them. The idempotency key on trip creation means a rider tapping Request twice on a bad connection creates one trip, as in idempotency.
4. Data model
| Data | Store | Key | Why |
|---|---|---|---|
| Driver live position and status | In-memory geo index, per city shard | H3 cell, driver ID | 250k writes per second, soft state |
| Driver dispatch state (available, offered, on trip) | Strongly consistent KV per city | driver_id | Conditional writes enforce one trip per driver |
| Trips and state transitions | Sharded relational or KV store | trip_id, city prefix | Hard state, versioned transitions |
| Location trail for trips | Log plus time-series or object storage | trip_id, time | Fare calculation and disputes |
| Payments and ledger | Relational, double entry | payment_id, account_id | Money needs ACID and audit |
| Surge multipliers | Cache, written by the stream job | city, H3 cell | Read on every quote |
CREATE TABLE trips (
trip_id UUID PRIMARY KEY,
city_id INT NOT NULL,
rider_id BIGINT NOT NULL,
driver_id BIGINT,
state VARCHAR(20) NOT NULL,
version INT NOT NULL, -- incremented on every transition
quote_id VARCHAR(40) NOT NULL,
requested_at TIMESTAMPTZ NOT NULL,
final_fare NUMERIC(12,2)
);
CREATE TABLE driver_dispatch (
driver_id BIGINT PRIMARY KEY,
city_id INT NOT NULL,
status VARCHAR(12) NOT NULL, -- OFFLINE, AVAILABLE, OFFERED, ON_TRIP
trip_id UUID,
offer_expires TIMESTAMPTZ,
version INT NOT NULL
);
Keep the geo index and the dispatch state separate. The index answers “who is near here” and can be slightly stale and lossy. The dispatch record answers “is this driver free” and must be exact. Mixing them forces either the index to be strongly consistent (too slow at 250k writes per second) or the dispatch decision to be lossy (double assignment).
5. High-level design
flowchart LR D["Driver app"] -->|"location every 4 s"| GW["Connection gateway"] RA["Rider app"] --> API["Trip API"] RA <-->|"live updates"| GW GW --> LS["Location service"] LS --> GI["Geo index<br/>in memory, by H3 cell"] LS -.-> K["Location stream<br/>(Kafka)"] API --> M["Matching and dispatch"] M --> GI M --> ETA["ETA service"] M --> DS["Driver dispatch state<br/>conditional writes"] API --> T["Trip service<br/>state machine"] T --> P["Payment saga"] K --> SP["Stream jobs<br/>surge, traffic speeds"] SP --> ETA style M fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style DS fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style T fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style GI fill:#E1F5EE,stroke:#0F6E56,color:#085041 style K fill:#F1EFE8,stroke:#888780,color:#444441
Everything in this diagram is deployed per city cell (section 6.6). A request flows like this: the rider gets a quote (geo index for supply, ETA service, surge cache), requests a trip, the trip service creates it in MATCHING, the matching service finds candidates in the geo index, ranks them by ETA, and reserves one driver with a conditional write before sending the offer through the gateway. Once the driver accepts, the trip moves to DRIVER_ASSIGNED, the rider’s connection starts receiving the driver’s position, and the payment saga waits for completion.
6. Deep dives
6.1 Location ingestion and the geo index
At 250,000 writes per second, a database that writes every update durably to disk is the wrong tool. The latest position of each driver is soft state: if you lose it, the next update arrives within 4 seconds. So the location service keeps it in memory and writes only a side copy to a log.
The index is a hash map from a hierarchical cell ID to the set of drivers in that cell, plus a map from driver ID to current cell. Geospatial indexing explains the cell systems; the two you will see are Uber’s open-source H3 (hexagons) and Google’s S2 (squares on a cube projection). With H3, resolution 9 cells have an average edge of about 200 m and an area of about 0.1 km²; resolution 8 is about 530 m and 0.74 km². Hexagons have the useful property that all six neighbours are the same distance away, which makes “search ring by ring outward” uniform.
On each update the service:
- Drops the update if its sequence number or client timestamp is older than what it already holds (mobile networks reorder packets, and latest wins).
- Computes the cell at resolution 9, moves the driver between cell sets if it changed, and updates the position.
- Sets a last-seen time. Drivers not heard from in about 20 to 30 seconds are excluded from search.
- Appends the update to a location stream for trip trails, traffic speeds and surge.
A nearby search for a pickup point takes the pickup cell plus its first ring (7 cells, about 0.7 km²), and keeps expanding rings until it has enough available candidates or hits a radius cap. Each lookup is a few hash map reads, which is why the 100 ms budget is easy.
Sharding: shard first by city, then within very large cities by a coarse parent cell, so one shard owns a contiguous area. A search near a shard boundary fans out to the two or three neighbouring shards. Routing updates by driver ID instead (as consistent hashing would by default) spreads write load evenly but makes every search a scatter-gather across all shards, which is the wrong trade for a read that is inherently local. The general version of this decision is in sharding and partitioning.
Replicate each shard in memory to a standby. If both are lost, a fresh shard is fully repopulated within one or two update intervals, 4 to 8 seconds, because every online driver reports in again. This is the nicest property of soft state: recovery is automatic and fast.
6.2 Matching and dispatch: one driver, one trip
Matching has two halves: choosing and committing.
Choosing. Take the candidates from the geo index, ask the ETA service for the road-network pickup time for each (straight-line distance lies across rivers and one-way systems), and score them by ETA, plus factors like acceptance probability and vehicle type. A greedy matcher offers each request the best available driver immediately. A batched matcher collects requests in a cell for a second or two and solves an assignment across all of them, which can lower total pickup time when demand is dense, at the cost of a little added latency. Batching is the better default in busy cells and greedy is fine in quiet ones.
Committing. This is where correctness lives. Two matcher instances, or two requests in the same batch window, must never reserve the same driver. Use a conditional write on the authoritative dispatch record:
UPDATE driver_dispatch
SET status = 'OFFERED', trip_id = :trip, offer_expires = now() + interval '15 seconds',
version = version + 1
WHERE driver_id = :driver AND status = 'AVAILABLE' AND version = :seen_version;
-- 1 row updated: the driver is reserved for this trip. 0 rows: someone else won, pick the next candidate.
The offer is effectively a lease: if the driver does not accept within 15 seconds, a sweeper (or the next read) treats the reservation as expired and returns the driver to AVAILABLE. Accept is another conditional write (OFFERED and matching trip_id to ON_TRIP) and is idempotent: a duplicate accept for the same trip returns success, an accept for an expired offer returns 409.
Why not a distributed lock per driver? Because a lock held by a process that pauses (GC, network partition) can expire while the holder still thinks it owns it. The conditional write against a single source of truth, with a version number, is the same idea as a fencing token from leader election, leases and locks: the store rejects the stale writer rather than trusting it to know it is stale. If matching is itself partitioned with one leader per city shard, that leader’s term number should be part of the write so a deposed leader’s writes are refused.
6.3 The trip state machine
Model the trip as an explicit state machine with versioned transitions. Every transition is a conditional update (WHERE state = :expected AND version = :v), and every successful transition emits an event to the trip stream through an outbox, so downstream consumers (rider updates, payments, receipts) never see a transition that did not commit.
stateDiagram-v2 [*] --> Requested Requested --> Matching: quote valid, card authorized Matching --> DriverAssigned: driver accepts offer Matching --> NoDriversFound: search timeout Matching --> Cancelled: rider cancels DriverAssigned --> Matching: driver cancels, rematch DriverAssigned --> Arrived: driver at pickup DriverAssigned --> Cancelled: rider cancels, fee may apply Arrived --> InProgress: trip started Arrived --> Cancelled: rider no show InProgress --> Completed: trip ended, final fare computed Completed --> Paid: payment captured Completed --> PaymentPending: capture failed, retrying PaymentPending --> Paid: retry succeeds NoDriversFound --> [*] Cancelled --> [*] Paid --> [*]
Two details matter. First, the driver’s phone and the server can disagree (the driver tapped Start in a tunnel). Accept transitions from the client with the client’s timestamp and its last known version, apply them if they are still legal, and reconcile the rest; never let a late message move a trip backwards. Second, the final fare is computed from the trip’s location trail, which the driver app also buffers locally and uploads in batches, so a gap in real-time updates does not change what the rider pays.
6.4 Payments as a saga
A trip touches several systems that cannot share one database transaction: the card processor, the internal ledger, driver earnings and receipts. Two-phase commit is not available across an external payment provider, so use a saga: a sequence of local steps, each with a compensating action.
sequenceDiagram participant T as Trip service participant P as Payment service participant PSP as Card processor participant L as Ledger T->>P: authorize estimate (trip_id, idempotency key) P->>PSP: authorize hold PSP-->>P: auth ok Note over T,P: trip runs T->>P: complete, final fare P->>PSP: capture final amount PSP-->>P: captured P->>L: debit rider, credit driver earnings, platform fee P-->>T: Paid Note over P,PSP: on rider cancel before pickup, compensate by voiding the hold
Every step carries an idempotency key derived from the trip ID and the step name, so retries after timeouts never double charge. The ledger is double entry and append only; corrections are new entries, never updates. Driver payouts run later in batches from the ledger, decoupled from trips entirely. The saga orchestrator persists its own progress, so a crash mid-saga resumes from the last completed step rather than starting over.
6.5 Real-time updates, surge and ETAs
Updates to riders. The connection gateway keeps long-lived connections (WebSocket or a similar bidirectional protocol) to apps in the foreground and maintains a registry of which gateway node holds which user. When the location service sees an update for a driver on a trip, it forwards the position to the gateway node holding the rider. When the app is backgrounded, state changes (driver arrived) go through mobile push notifications instead. At an assumed 50,000 to 100,000 connections per gateway node, about 1.3M concurrent connections need 15 to 30 nodes, plus headroom for reconnect storms after a deploy.
Surge. A stream processing job consumes the location stream (supply: available drivers per cell) and the request stream (demand: quotes and requests per cell) in tumbling windows of a minute or two, at a coarser resolution such as H3 resolution 7 or 8. It computes a demand to supply ratio, smooths it across neighbouring cells and over time so prices do not flicker, and writes a multiplier per cell to a cache read by the quote service. The intuition is economic: a higher price both reduces marginal demand and pulls drivers toward the area. Smoothing and caps keep the system stable and fair; jurisdictions may also regulate surge.
ETA. Pickup and trip ETAs come from a routing engine over the road graph, using precomputed speed-ups so a route query takes milliseconds rather than a full graph search. Live speeds per road segment come from another stream job that aggregates on-trip GPS traces, and a learned correction layer adjusts for systematic error (a stadium exit always slower than the graph says). ETA quality directly drives matching quality, so it is worth monitoring as a first-class SLI.
6.6 City cells and multi-region
Ride hailing partitions naturally by geography: a trip in one city never needs a driver from another. That makes it a textbook fit for cell-based architecture. Each cell is a full stack (gateway, location, matching, trip, dispatch state) serving one large city or a group of smaller ones. A thin global routing layer maps a request’s pickup location to its cell. A bad deploy or a runaway hot spot in one cell affects that cell only, and you can roll changes out cell by cell.
Global services sit outside cells: identity, payment methods, the ledger and rider profiles. Keep their use on the hot path to cached reads so a global service blip does not stop rides everywhere.
For multi-region, each cell has a home region and a warm standby in another. Hard state (trips, dispatch state) is replicated to the standby; soft state (the geo index) is not, because it rebuilds itself in seconds from fresh updates. On regional failover, apps reconnect to the standby, the geo index fills within one or two update intervals, and in-flight trips continue from replicated trip records. Because asynchronous replication can lose the last few seconds of transitions, the apps also hold the current trip state and replay their latest view on reconnect, and the server reconciles against what it has.
7. Bottlenecks, failure scenarios and trade-offs
Lost and stale location updates. Mobile networks drop packets and phones lose GPS in tunnels. Latest-wins with sequence numbers handles reordering, the last-seen expiry keeps ghosts out of matching, and the server can dead-reckon a moving driver forward from heading and speed for display. Fares do not depend on real-time delivery because the trail is buffered on the phone. The thing to alert on is not individual drops but a city-wide fall in update rate, which usually means a gateway or carrier problem.
Matching service partitioned from dispatch state. If a matcher cannot reach the dispatch store, its conditional writes fail and it cannot reserve anyone, which is safe. The danger is a matcher that believes it owns a city shard after its lease expired. Lease-based shard ownership with a term number on every write (see distributed consensus for how terms are agreed) means the store refuses the stale owner. Riders see a short delay while a new owner takes over; nobody gets a double booking. Choose correctness over availability here, which is the CAP trade made consciously for one invariant.
Payment provider outage. Do not block trips on the provider. If authorization at request time fails because the provider is down (not because the card was declined), let low-risk riders proceed with a pending authorization and higher-risk ones be asked for another method. At completion, move to PaymentPending and retry capture with exponential backoff and jitter from timeouts, retries and backoff, behind a circuit breaker so a dead provider does not tie up threads. Where you have a second processor, route new authorizations there. Idempotency keys make every retry safe.
Hot cells. The stadium puts thousands of searches and requests on a handful of cells owned by one shard. Batched matching helps here, as does load shedding of non-essential work (map refreshes of nearby cars) before trip requests.
Gateway reconnect storms. A deploy or a network blip disconnects a million drivers at once, and they all reconnect within seconds. Drain gateway nodes gradually and have clients reconnect with jittered delays.
| Decision | You gain | You pay | When it flips |
|---|---|---|---|
| In-memory geo index, no durable writes | 250k writes per second on a few nodes, simple recovery | Seconds of position loss on failure | Regulation requires every position persisted in real time |
| Shard by area, not by driver ID | Local searches hit one shard | Uneven load, boundary fan-out | Cities with very even density and tiny search radius |
| Conditional writes over distributed locks | Correct even with pauses and partitions | A single authoritative store per city | Never for the one-trip invariant |
| Batched matching over greedy | Lower total pickup time in dense areas | A second or two of extra latency | Quiet cells, where greedy is just as good |
| City cells | Blast radius of one city, staged rollouts | Duplicated infrastructure, cross-cell edge cases at borders | Very small markets, grouped into shared cells |
✅ Key takeaways
- 1M online drivers reporting every 4 seconds is 250,000 writes a second; keep latest positions as soft state in an in-memory index keyed by H3 or S2 cells and let the next update repair any loss.
- Shard the geo index by area (city, then coarse parent cell) so searches are local, and expand rings of cells until you have enough candidates.
- Enforce one driver, one trip with a conditional, versioned write on an authoritative dispatch record, with offers as short leases; never rely on a lock holder knowing it is stale.
- Model trips as an explicit state machine with conditional transitions and outbox events, and run payments as a saga with idempotency keys and compensations.
- Surge and live traffic speeds are stream processing jobs over the location and request streams; city cells give natural blast radius limits and simple multi-region failover.
🧠 Check your understanding
0 / 4-
1Why is it acceptable to keep driver positions only in memory, without durable writes for every update?
Latest positions expire and refresh every 4 seconds, so losing them costs only a few seconds of freshness. In-memory replication can still lose data, and fares depend on the trip trail, which is buffered on the phone and logged separately for exactly that reason.
-
2Two matcher instances both see driver 42 as available and try to offer them different trips. What prevents a double booking?
The authoritative store arbitrates: exactly one conditional update can move the driver from AVAILABLE to OFFERED. The geo index is eventually consistent and cannot arbitrate. A lock with a timeout can expire while a paused holder still acts on it, and relying on the client leaves the server state wrong.
-
31M drivers are online and each sends a location every 4 seconds. What is the ingest rate?
1,000,000 drivers divided by 4 seconds is 250,000 updates per second. Multiplying by 4 instead of dividing is the common slip, and 11,600 comes from spreading the updates over a whole day.
-
4The card processor is down. A rider's trip has just ended. What should the system do?
The trip really ended, so the trip state must say so, and the payment saga continues asynchronously. Idempotency keys make retries safe, and backoff behind a circuit breaker protects the system. Holding the trip open corrupts driver availability and earnings, and cancelling loses revenue for a temporary outage.
Interview questions
How do you find the nearest drivers when the pickup is right at the edge of a cell?
Never search a single cell. Take the pickup cell and its neighbouring ring (7 hexagons in H3), and expand ring by ring until you have enough available candidates or reach a radius cap. Then rank candidates by road-network ETA, not by cell or straight-line distance, because the nearest driver on the map may be across a river. If the ring crosses a shard boundary, query the neighbouring shards in parallel and merge.
A driver accepts an offer at the same moment it expires. What happens?
The accept is a conditional write that requires status OFFERED, the same trip ID and an unexpired offer. Expiry is enforced by the same store, so exactly one of them wins: either the accept commits and the trip moves to DriverAssigned, or the expiry returned the driver to AVAILABLE first and the accept gets a 409 and the driver app shows the offer as missed. There is no window where both happen because both are conditional updates on the same record.
How would you price surge without making it flicker every few seconds?
Compute demand and supply per cell in windows of one to two minutes, smooth the ratio across neighbouring cells and over time with a damping factor, apply bounded step changes per window, and lock the price the rider saw with a quote ID for a few minutes. That keeps the multiplier responsive to the stadium but stable enough that a rider refreshing the app does not see it jump around.
What happens to trips in flight if a whole region fails?
The city’s cell fails over to its standby region. Apps reconnect, the geo index rebuilds from fresh updates in one or two intervals, and trip records come from the asynchronously replicated store. Because the last few seconds of transitions may be missing, apps send their current trip state on reconnect and the server reconciles, accepting only forward, legal transitions. Payments resume from the saga’s persisted progress with the same idempotency keys, so nothing is charged twice.
Where to go next
- Geospatial indexing explains H3, S2 and geohash in depth, including ring searches and resolution choice.
- Cell-based architecture shows how to size cells, route to them and handle requests that straddle a border.
- Design a chat system is a close cousin: the same connection gateway, presence and fan-out problems without the geography.
- Saga pattern covers orchestration vs choreography and how to write compensations that are safe to retry.
Finished this lesson?
Mark it complete to track your progress across the roadmap.