Backend Design for a City-Scale Taxi Dispatch Service
System DesignModel answerLast updated
Design the backend for a multi-city on-demand taxi app: dispatch, live driver tracking, dynamic pricing, durable payments and trip records, and resilience at millions of daily users.
Problem
Design the backend for an on-demand taxi platform that operates in many cities and serves millions of daily users. Passengers book a car from a pickup point to a drop-off point, and nearby drivers are matched to them automatically.
What the product must do
Passengers can:
- Register, sign in, and edit their profile.
- Ask for a trip by giving a pickup and a destination.
- See nearby available cars with an estimated arrival time.
- See a fare estimate before they confirm.
- Watch the assigned car move on a map in real time.
- Pay with a saved payment method such as a card.
- Rate the driver afterwards.
Drivers can:
- Register, complete onboarding, and add their vehicle.
- Switch between online and offline.
- Receive trip offers and accept or decline them.
- Navigate first to the passenger and then to the destination.
The platform must:
- Match passengers with suitable nearby drivers automatically.
- Raise prices in areas where demand exceeds supply (dynamic pricing).
- Keep a history of trips (route, price, timestamps) for both sides.
- Send push or SMS notifications as the trip status changes.
Quality requirements
- Availability: the service keeps working when individual components fail.
- Latency: arrival estimates and match results appear within a few hundred milliseconds; vehicle positions look close to live.
- Scale: millions of daily active users across several regions.
- Correctness: payments and trip records are never lost and never charged twice. Live location may be eventually consistent.
- Security and privacy: user data and payment details are protected.
What to cover in your answer
- Overall architecture: the main services and how they communicate.
- Data model and storage: key entities, a rough schema, and which database type holds what.
- The booking and matching flow, including how to find and pick a nearby driver efficiently.
- Real-time location: how drivers report positions and how the system stores and serves them for ETAs and maps.
- Scaling and partitioning: sharding strategy and how to handle rush-hour hotspots.
- Reliability: handling service and data-center failures, and keeping payments and trip data durable.
- Briefly: dynamic pricing, plus monitoring, logging, and the metrics you would track.
State your scale assumptions and do a quick back-of-the-envelope estimate first.
Hints
Hint 1
Estimate the load before drawing boxes. Frequent driver location pings produce far more writes than trip requests, so the two paths need different storage and consistency models.
Hint 2
Use a spatial grid (geohash, H3, or S2) to look up nearby drivers, then rank candidates by road-network ETA rather than straight-line distance. Reserve a driver atomically so nobody receives two offers at once.
Hint 3
Model the trip as a state machine with conditional writes, and make payment calls idempotent with unique keys. That makes retries, duplicate events, and out-of-order messages harmless.
Hint 4
Partition by city or region first, then split hot cities by grid cell. Treat live location as soft state with a TTL so it rebuilds itself after a node failure.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and numbers
Assumptions, stated up front:
| Quantity | Assumption | Result |
|---|---|---|
| Trips per day | ~20M | ~230/s average, ~2k/s at peak |
| Online drivers at peak | ~1M | A ping every 4 s gives ~250k writes/s |
| Ping size | ~100 B | ~25 MB/s ingest, ~2 TB/day raw |
| Matching latency | p99 under 500 ms for ETA and nearby cars | Full assignment within a few seconds |
The key insight is that there are two workloads. Location is high-volume, short-lived, and tolerant of slight staleness, so it lives in memory with eventual consistency. Trips and payments are low-volume but must be correct, so they use durable, strongly consistent storage with idempotency.
2. Architecture
Clients (rider and driver apps) use HTTPS for requests and a persistent WebSocket or gRPC stream for live data. Behind that:
- API gateway: authentication, rate limiting, routing.
- Connection gateway: holds the sockets and pushes offers, status, and positions to clients.
- Profile service: riders, drivers, vehicles (SQL).
- Location service: in-memory geospatial index of live drivers.
- Pricing service: fare quotes and the surge multiplier.
- ETA/routing service: road graph plus live traffic.
- Dispatch service: candidate search, ranking, offer state machine.
- Trip service: authoritative trip state machine.
- Payment service: ledger plus an external payment processor.
- Notification service: push, SMS, socket fan-out.
- Rating service.
Synchronous calls use gRPC. Events go through Kafka (trip events, location stream) to analytics, fraud, and surge aggregation. The trip service writes events to an outbox table in the same transaction as the state change, and a relay publishes them, so the database and the event stream cannot diverge.
3. Data model and storage
| Entity | Key fields | Store |
|---|---|---|
| Rider, Driver, Vehicle | ids, contact, status, city, tier, rating | Sharded SQL |
| Trip | trip_id, rider_id, driver_id, city_id, status, pickup, dropoff, quote_id, fare, surge, timestamps | Strongly consistent SQL or NewSQL, sharded by trip_id with city locality |
| Route points | trip_id, ordered GPS samples | Wide-column store (Cassandra/Bigtable), archived to object storage |
| Live location | driver_id to (lat, lng, heading, ts, status, cell) | In-memory store (Redis or custom), TTL ~30 s |
| Payment and ledger | payment_id, trip_id, unique idempotency_key, amount, state; append-only double-entry rows | ACID SQL |
| Rating | trip_id (PK), rater, ratee, stars, text | SQL |
| Fare quote | quote_id, fare, surge, expires_at | Redis with TTL |
Card numbers are never stored; only processor tokens are kept.
4. Booking and matching flow
- Estimate. Pricing asks ETA/routing for distance and duration and reads the surge multiplier for the pickup cell. It returns a signed quote with a short TTL (about 2 minutes), freezing the price the rider saw.
- Create trip. The client sends the quote and an idempotency key. The trip is stored as
REQUESTED; a retry returns the same trip. - Find candidates. Map the pickup to an H3 cell, query that cell and its ring of neighbours, and widen the ring until enough available drivers (say 10) are found. Filter by vehicle tier.
- Rank. Score by road ETA (batched call to routing), then by acceptance rate and rating. In dense areas, use batched matching: collect requests for 1-2 s and solve an assignment problem to minimise total pickup time rather than greedily serving each request.
- Offer. Atomically flip the driver from
AVAILABLEtoOFFERED:trip_id(compare-and-set). This prevents double offers. Push the offer over the socket with a ~15 s timeout; on decline or timeout, release and try the next candidate. - Accept. Update the trip
MATCHINGtoACCEPTEDwith a conditional write. Notify the rider and start live tracking.
State machine: REQUESTED, MATCHING, ACCEPTED, ARRIVED, IN_PROGRESS, COMPLETED, with CANCELLED and NO_DRIVERS as exits. Since every transition is conditional, duplicates and reordering are harmless.
5. Real-time location
- Ingest: the driver app sends GPS roughly every 4 s over its persistent connection, batching and dead-reckoning on weak signal.
- Index update: the location service rewrites the driver's record and, on crossing a cell boundary, removes them from the old cell set and adds them to the new one.
- Stream: each ping is also published to Kafka keyed by driver_id. Consumers build route history, compute actual distance for fares, count supply for surge, and feed fraud and ETA models.
- Rider view: during an active trip the rider subscribes to a per-trip channel; the gateway pushes driver pings to the rider, and the client interpolates for smooth animation.
- ETA: contraction-hierarchy routing over the road graph, with traffic speeds derived from aggregated pings; coarse cell-to-cell ETAs are cached.
Live location is soft state: if a node dies, the index refills within one ping interval, and TTLs remove offline drivers automatically.
6. Scaling and hotspots
- Shard by region. Matching never crosses cities, so each region runs its own dispatch and location clusters near its users.
- Inside a big city, shard the geo index by cell using consistent hashing; a neighbour query touches only a few shards.
- Stateless services scale horizontally behind load balancers.
- Connection gateways hold millions of sockets, with a routing table mapping user to gateway node.
- Hotspots (stadium exits, rush hour): split hot cells into finer ones, add replicas for read-heavy queries, rely on batching to smooth bursts, and apply admission control or queueing when demand spikes.
7. Reliability
- Stateless tiers: multiple instances across availability zones; health checks and automatic failover.
- Databases: synchronous replication within a region, asynchronous or consensus-based replication across regions. Trip and payment writes are acknowledged only once durable.
- Payments: idempotency keys with a unique constraint, an append-only ledger, and a reconciliation job against the processor. Charge at trip completion with retries; never retry without the same key.
- Region failure: fail over traffic to a peer region; active trips resume from replicated trip state, and drivers re-register their location within seconds.
- Degradation: if routing is slow, fall back to straight-line or cached ETAs; if surge data is stale, use the last known multiplier.
- Messaging: Kafka replication, consumers that are idempotent, and dead-letter queues.
8. Surge, monitoring, security
- Surge: per cell, compute the demand-to-supply ratio over a sliding window (requests and app opens versus available drivers), smooth it over time and across neighbouring cells, cap it, and publish the multiplier. Quotes freeze it for a short time.
- Metrics: request-to-match time, offer acceptance rate, match success rate, ETA error, location-ingest lag, p99 latency per service, payment failure rate, cancellation rate, Kafka consumer lag. Add distributed tracing and structured logs keyed by trip_id, with alerts on SLO burn.
- Security: TLS everywhere, short-lived tokens, PII encryption at rest, tokenised cards (PCI scope kept small), rate limiting, fraud and GPS-spoofing detection, and masked phone numbers between rider and driver.
Common mistakes
- Treating location pings like normal database rows instead of in-memory soft state.
- Ranking by straight-line distance, which ignores rivers, one-way streets, and traffic.
- Offering one driver to several riders because reservation is not atomic.
- Charging twice after a timeout because payment calls are not idempotent.
- Sharding globally by user id, which scatters geographically local queries.
- Skipping the numbers, so nothing justifies the storage and sharding choices.