Build a Backend for On-Demand Car Rides and Driver Dispatch
System DesignModel answerLast updated
Design a service that pairs passengers with close-by available drivers, ingests live driver positions, and carries each trip from request to payment without ever double-booking a driver.
You are asked to design the server side of an on-demand taxi platform. A passenger picks a pickup location and a destination, the platform finds a suitable driver nearby, sends that driver an offer, and then follows the trip until it ends.
Treat the discussion as one you are leading. Begin by pinning down requirements, then build the architecture in stages. For each component, explain why it exists, compare alternatives, and point out where the design could be improved. Your interviewer may interject with changes midway, so keep the overall structure coherent while absorbing them.
Scope to assume
- Passengers can view a fare estimate, request a ride, and follow the assigned driver's approach in near real time.
- Drivers switch between online and offline, and while online they send location updates at regular intervals.
- Each request is matched with a nearby available driver, who has a short window to accept or decline. A driver must never be committed to two trips at the same moment.
- Every trip passes through well-defined states: requested, driver assigned, in progress, completed, or cancelled. A finished trip ends in payment, which may be handed to an external payment provider.
- Not in scope unless raised: pooled rides, pre-booked rides, driver onboarding, and ratings.
- No traffic numbers are provided. Pick your own assumptions, state them, and size the system from them.
Questions worth settling early
- Is the matching goal shortest straight-line distance, shortest estimated arrival time, or a broader score that also considers acceptance likelihood?
- Is each request offered to a single driver at a time, or to several simultaneously?
- How old can a driver's reported position be before match quality degrades noticeably?
- Is surge pricing part of the design?
- Is the launch a single region, or several regions with data-residency rules?
What to deliver
Cover requirements and scale estimates, the main entities and APIs, a trip state machine, a way to search for nearby moving drivers, a dispatch flow that avoids double assignment and handles declines, timeouts and cancellations, real-time delivery to both apps, and the behavior when components or devices fail.
Hints
Hint 1
Start with numbers: how many online drivers, how often each reports a position, and how many ride requests per second at peak. The location write rate will dominate and should drive your storage choice.
Hint 2
Driver positions change constantly, so a durable disk-based database is a poor home for them. Think about an in-memory store partitioned by a grid or hierarchical cell id (geohash, S2, H3), and query the rider's cell plus its neighbors.
Hint 3
Double assignment is a concurrency problem. Use an atomic claim on the driver (compare-and-set or a short lease with expiry) before sending the offer, and make the trip state transitions idempotent and versioned.
Hint 4
Decide up front what happens when an offer times out, a driver app drops offline mid-offer, or the dispatch service crashes. Offers with expiry timestamps and a durable trip record let another worker resume.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale assumptions
Functional: fare estimate, request ride, match to driver, accept/decline, live tracking, trip lifecycle, payment handoff.
Non-functional: match within a few seconds, location freshness of roughly 5 seconds, no double-booking of a driver (strong consistency on that one fact), high availability for the request path, and graceful degradation if non-critical pieces fail.
Assumed scale (one launch region, then scale out):
- 1M drivers registered, about 300k online at peak.
- Each online driver reports every 4 seconds, which is about 75k location writes per second.
- 20M trips per day, so about 230 per second on average and around 1,000 per second at peak.
- Each location update is roughly 100 bytes, so the ingest stream is under 10 MB/s. Small in bandwidth, but write-heavy and latency-sensitive.
2. Core entities and APIs
Entities: Rider, Driver (status: offline, available, offered, on_trip), Trip (id, rider, driver, pickup, dropoff, state, version, fare), Offer (trip, driver, expires_at, outcome), Payment.
APIs:
POST /fare-estimatesreturns price and ETA.POST /tripscreates a request (with an idempotency key).POST /trips/{id}/cancel.PUT /drivers/me/statustoggles online/offline.POST /drivers/me/location(or a streaming channel) for position updates.POST /offers/{id}/acceptand/decline.- A WebSocket or push channel for trip and driver-position events.
3. Trip state machine
REQUESTED → DRIVER_ASSIGNED → IN_PROGRESS → COMPLETED, with CANCELLED reachable from the first three states, and REQUESTED able to fall back to itself when an offer is declined. Every transition is a conditional write (UPDATE ... WHERE state = X AND version = n), so retries and races are harmless. Trips live in a replicated relational store (or a strongly consistent key-value store) because correctness matters more than raw write rate here.
4. Finding nearby drivers
Scanning all drivers is out of the question. Divide the map into cells using geohash, Google S2 or H3 (hexagons are attractive because all neighbors are equidistant). Maintain cell_id → set of available driver ids in an in-memory store such as Redis, sharded by cell or region. A driver update removes the driver from the old cell set and adds to the new one only when the cell changes; the exact position is kept in a per-driver record with a TTL (about 15 seconds), so crashed apps vanish automatically.
Query: take the pickup's cell, expand to rings of neighbors until enough candidates are found, then rank. Ranking can start with straight-line distance and improve to road-network ETA from a routing service, calling it only for the top 10-20 candidates to control cost.
Trade-offs: a fixed grid is simple but uneven in dense downtowns (use a finer resolution or adaptive cell splitting there); a quadtree adapts automatically but is harder to shard and update. Location data is ephemeral, so losing it on a node failure is acceptable: drivers re-report within seconds.
5. Dispatch without double assignment
- Trip is persisted as
REQUESTED; a dispatch worker picks it up from a queue (partitioned by trip id). - Worker gets ranked candidates.
- For the best candidate, it performs an atomic claim: a conditional update
available → offeredon the driver record with a lease (for example 15 seconds) and the trip id. In Redis this is a Lua script orSET NX PX; in a database it is a compare-and-set. If the claim fails, move to the next candidate. - Push the offer to the driver's app.
- On accept, a transaction moves the trip to
DRIVER_ASSIGNEDand the driver toon_trip, both guarded by the claim token. On decline or timeout, release the claim and continue with the next candidate, never repeating a driver for the same trip. - If no one accepts after N attempts or a total deadline, widen the search radius, then tell the rider that no driver is available.
Offering to one driver at a time is simpler and fair to drivers; offering to a small batch cuts latency but requires the claim step to also handle "someone else already accepted" and can annoy drivers with wasted offers. A sensible default is sequential offers with short windows (10-15 seconds) and a scored ordering that includes ETA and past acceptance rate.
Cancellation: the rider's cancel is another conditional transition. If it races with an accept, whichever write wins is the truth, and the loser receives a clear error and releases any lease.
6. Real-time updates
Rider and driver apps keep a WebSocket (or MQTT/push fallback) connection to a gateway tier. Gateways are stateless apart from a connection registry (user_id → gateway). Backend services publish events to a pub/sub bus; the gateway holding the connection forwards them. During a trip, driver positions are published to the trip's channel every 2-4 seconds, and the rider app smooths movement client-side. If a socket drops, the app reconnects and fetches the latest trip snapshot, so events are not the only source of truth.
7. Payments and pricing
At completion, compute the final fare from distance and time, then call the payment provider with an idempotency key tied to the trip id. Record the result asynchronously and retry with backoff; never block trip completion on the provider. Surge pricing can be added later by computing demand/supply ratios per cell over a sliding window and applying a multiplier shown in the fare estimate and locked in at request time.
8. Failure handling
- Dispatch worker crash: the trip is durable and offers carry expiry times, so another worker resumes; claims expire on their own.
- Driver app goes silent: the location TTL removes them from the pool; an active offer times out; an in-progress trip triggers an alert and fallback to last known position.
- Location store node loss: replicas or a quick rebuild from incoming updates; matching quality dips briefly.
- Duplicate requests: idempotency keys on trip creation and payment.
- Regional isolation: deploy per region with independent stacks, which also satisfies data-residency needs.
9. Improvements to propose
Batch matching in short windows (a couple of seconds) to optimize across several riders and drivers at once, ETA-based and acceptance-aware scoring, predictive repositioning of idle drivers, and map-matching to clean noisy GPS.
Common mistakes
- Storing live locations in a disk-based relational table and updating it every few seconds.
- Checking driver availability and then assigning in two separate steps without an atomic claim.
- Forgetting timeouts, so an unresponsive driver blocks a rider forever.
- Treating push events as the only source of truth instead of allowing a state refetch.
- Omitting scale numbers, which makes every component choice look arbitrary.