Resilient Dispatch and Trip Lifecycle at Global Scale
System DesignModel answerLast updated
Design a real-time ride-hailing backend that ingests driver pings, matches riders without double-booking, and runs an idempotent, fault-tolerant trip state machine.
Design the dispatch core of a worldwide ride-hailing service. The system must continuously absorb driver position updates, search and rank nearby available drivers when a rider requests a ride, prevent two riders from claiming the same driver (or one rider from being claimed twice), and manage the trip through its full lifecycle: REQUESTED, MATCHED, ARRIVED, IN_PROGRESS, COMPLETED, CANCELLED.
Functional requirements
- Location ingestion — Drivers report positions periodically; the platform keeps a spatial index that reflects where each active driver is.
- Candidate search and matching — On a ride request, find available drivers within a dynamic radius (roughly 3–5 km) and offer the trip to candidates sequentially or in batches.
- Conflict-free assignment — A driver may hold at most one outstanding offer/trip, and a ride request may be claimed by at most one driver.
- Trip state machine — Transitions must be idempotent, auditable, and safe under duplicate or out-of-order network packets.
- Rejection and timeout — If the targeted driver declines or does not answer within roughly 15 seconds, the ride moves on to the next-best candidate.
Non-functional requirements
- Scale — about 1,000,000 concurrently active drivers reporting every 4 seconds (≈250,000 location writes/sec), with peaks of 5,000 new ride requests/sec.
- Latency — candidate discovery plus the first dispatch offer within 1 second at p99.
- Consistency — strict consistency for driver assignment and trip transitions; eventual consistency is fine for the map/discovery index.
- Fault tolerance — regional network interruptions and node crashes must not lose active trip state.
What the answer should cover
- Endpoint design for location updates, ride requests, driver accept/decline, and trip transitions.
- Storage and indexing choices for trips and geospatial data (H3/S2/Redis GEO or equivalent).
- Matching-engine architecture with concurrency control that avoids double dispatch or split brain.
- The trip lifecycle machine, ordering guarantees, idempotency, and fare tracking.
- Failure handling: driver app disconnects, driver crashes mid-trip, and stale location data.
Assume the scope is the dispatch core — pricing/payment execution and detailed ETA modelling are out of scope, but a fare snapshot must be captured for auditing.
Hints
Hint 1
Split the system into a fast, lossy location plane and a small, strictly consistent dispatch/trip plane; the geo index should only nominate candidates, never authorize an assignment.
Hint 2
Use a short-lived conditional lease plus a fencing token on the driver row instead of holding a distributed lock across a network call to the driver's phone.
Hint 3
Give every trip a monotonic version and an append-only event log with unique constraints on (trip_id, version) and (trip_id, idempotency_key), so retries and reordered packets become no-ops.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model answer
1. Frame the problem and do the capacity math
The central design decision is to separate two planes with very different consistency needs.
- Location plane: high volume, in-memory, eventually consistent, allowed to lose or reorder updates.
- Dispatch/trip plane: much smaller write volume, transactional, strictly consistent, durable.
A common mistake is to push all 250k location writes/sec through the strongly consistent database, or to let the eventually consistent geo index decide which driver is genuinely free.
Back-of-envelope: 250k pings/sec at ~100 bytes each is roughly 25 MB/s of ingest. Storing just the latest position of 1M drivers in RAM costs on the order of 100 MB, so memory is cheap — the constraint is per-shard write throughput. Shard by geographic region so each shard absorbs roughly 10–20k writes/sec. At 5k ride requests/sec, each request scans a few dozen spatial cells and yields roughly 50 candidates.
Latency budget for the p99 1-second offer:
| Stage | Budget |
|---|---|
| Validate request, check rider state | ~50 ms |
| Spatial lookup | ~30 ms |
| Rank by ETA / acceptance rate | ~200 ms |
| Conditional reservation (CAS) | ~20 ms |
| Push offer to driver | ~200 ms |
2. API surface
PUT /v1/drivers/{id}/location {lat, lng, heading, speed, ts, seq} -> 204
POST /v1/rides {rider_id, pickup, dropoff, product} [Idempotency-Key]
POST /v1/offers/{offer_id}/accept {driver_id, lease_token}
POST /v1/offers/{offer_id}/decline{driver_id, lease_token}
POST /v1/trips/{id}/transitions {event, expected_version, idempotency_key, client_ts, location}
GET /v1/trips/{id} -> {state, version, driver_id, route, fare}
POST /v1/rides takes an Idempotency-Key so a retried request returns the same trip_id rather than creating a second trip. Location updates are fire-and-forget (204) and are best carried over a persistent WebSocket or gRPC stream, which also serves as the channel for pushing offers. Accept returns 409 Conflict when the lease has expired or the trip was already claimed.
3. Storage and indexing
Geo index (in-memory, sharded, disposable). Use H3 at resolution 8 (≈0.7 km² cells) with a cell -> set(driver_id) map plus a driver_id -> {lat, lng, ts, cell, coarse_status} table. Entries expire after ~20 s of silence, so a driver who drops off the network ages out automatically. Redis GEO/Redis sets per cell works; a custom service with consistent hashing on the resolution-4/5 parent cell scales better and avoids hot cells downtown.
Driver dispatch record (strictly consistent):
driver_id, status {OFFLINE, AVAILABLE, OFFERED, ON_TRIP},
current_trip_id, lease_token, lease_expires_at, version
Trip record:
trip_id, rider_id, driver_id, state, version, pickup, dropoff,
active_offer_id, offer_attempts[], dispatcher_owner, dispatcher_lease_expiry,
fare_snapshot, created_at, updated_at
Trip events live in an append-only table (trip_id, version, event, idempotency_key, actor, payload, ts) with unique constraints on (trip_id, version) and (trip_id, idempotency_key).
Choose Spanner, CockroachDB, or horizontally sharded MySQL/Postgres with conditional updates for the trip and driver rows, sharded by trip_id / driver_id. Write downstream changes (rider notifications, billing, analytics) through a transactional outbox into Kafka so the strong store never fans out synchronously.
4. Matching architecture
- Gateway receives pings and publishes them to Kafka, partitioned by the H3 resolution-5 parent cell.
- Location service consumers update the geo shards, dropping any ping whose
seqis not newer than the last seen. A copy goes to cold storage for breadcrumbs. - Ride service creates the trip in
REQUESTED(idempotently) and hands it to the dispatcher owning the pickup region. - Dispatcher queries the k-ring of cells around the pickup, expanding k until enough candidates exist or 5 km is reached; filters by freshness and coarse status; ranks by ETA, heading, and historical acceptance rate; then reserves the top candidate and pushes the offer.
- Timer service (delayed queue or hierarchical timing wheel) fires offer expiry at 15 s.
Conflict-free assignment
The geo index nominates; the driver row authorizes. Reserve with a compare-and-swap rather than a long-held distributed lock:
UPDATE drivers
SET status='OFFERED', current_trip_id=:trip, lease_token=:token,
lease_expires_at = now() + interval '15 seconds', version = version + 1
WHERE driver_id=:driver AND status='AVAILABLE' AND version=:expected_version;
Zero rows updated means someone else won the race; move to the next candidate within ~20 ms. Because the row carries current_trip_id and a single lease token, a driver can never hold two live offers.
Acceptance runs in one transaction across driver and trip (native in Spanner/CockroachDB; otherwise a saga where the lease token acts as a fencing token). Preconditions: driver.lease_token = :token, lease_expires_at > now(), trip.state = 'REQUESTED', trip.version = :expected. On success: trip → MATCHED with driver_id set, driver → ON_TRIP, both versions incremented.
Decline or timeout releases the driver back to AVAILABLE using a CAS on lease_token, records the failed attempt, and the dispatcher offers the next candidate. A late accept after expiry fails the lease check and gets 409. Leases are also reclaimed lazily on the next reservation attempt, so a lost timer cannot strand a driver permanently.
Dispatcher crash is handled by a dispatcher_owner + lease on each REQUESTED trip. A sweeper picks up trips whose dispatcher lease expired; since every write is a CAS, two briefly-overlapping dispatchers cannot double-book.
5. Trip state machine
Legal transitions:
REQUESTED -> MATCHED | CANCELLED
MATCHED -> ARRIVED | CANCELLED | REQUESTED (driver cancels, redispatch)
ARRIVED -> IN_PROGRESS | CANCELLED
IN_PROGRESS -> COMPLETED
Each transition is one transaction that (1) checks the idempotency key and returns the stored result if seen, (2) checks (current_state, event) against the transition table, (3) checks expected_version == version, then (4) applies the change, appends the event row, and writes the outbox record.
This neutralizes network pathologies: a delayed ARRIVE arriving after START is rejected with no side effect; a client retry after a refetch replays the stored result. Client timestamps are retained for audit only — ordering comes solely from the server version.
Fares are snapshotted at MATCHED (rate card, surge multiplier, route), so later pricing changes cannot alter what was agreed; the snapshot is exposed via GET /v1/trips/{id}.
6. Failure modes
- Driver app disconnects — the lease expires and the trip is reassigned; if the driver reconnects mid-trip, they re-register and the strong store reconciles their real trip state.
- Driver crashes mid-trip — a watchdog detects the absence of expected pings during
MATCHED/ARRIVED/IN_PROGRESS, marks the trip for rider-side policy (reassign if legal, otherwise cancel with compensation), and writes the reason to the event log. - Stale location cache — the geo index only affects ranking and is TTL'd; every assignment revalidates freshness and driver availability against the transactional store, so a stale entry can produce a wasted offer but never a double booking.
- Regional blip — Kafka retains pings and events for replay; the transactional store remains the source of truth for trips, and dispatchers resume with expired-lease sweeps after failover.
The result is a design where the cheap, lossy path handles volume and the expensive, correct path handles every decision that money and safety depend on.