Match riders with nearby drivers in real time: location tracking, dispatch, pricing and trip state.
โDesign a ride-sharing service like Uber or Lyft.โ
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Spotting the real load | Ride requests are rare. Driver location pings are constant. A strong candidate does the maths and sees that location ingestion, not booking, is the dominant load. |
| Geospatial thinking | Find nearby drivers fast while thousands of them move. The interviewer wants a cell-based index, the boundary problem, and a reason to keep the hot index in memory. |
| Correctness under races | One driver must never be promised to two riders, and one trip must never be created twice. This is the invariant the whole dispatch design protects. |
| State machines and failure | A trip lives for 30 minutes across a phone that drops signal. The answer needs idempotent transitions, crash recovery and no orphaned trips. |
| Trade-offs in matching | Nearest-first is simple. Batch matching is better overall but adds waiting. Naming that cost, with numbers, is the senior signal. |
A rider asks for a ride. We find the best nearby available driver, offer them the trip, and if they accept, track the trip through a small state machine until it ends. The hard parts are the firehose of driver locations, matching without double-assigning a driver, and keeping a trip correct across crashes and bad networks.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Rider and driver flows, what is out of scope (pool rides, ratings), scale, one city or global. |
| 2. Estimate | 3 | Location writes per second (the dominant load), ride requests, index size, connections. |
| 3. API and data | 5 | Location update, request ride, offer and accept, the trip states, what lives in memory. |
| 4. High-level design | 8 | Location ingestion, geo index, dispatch, trip service, ETA, pricing, gateways. One request path. |
| 5. Deep dives | 15 | Geo index and ingestion, then matching and the double-assignment invariant, then the trip state machine, then surge and the live map. |
| 6. Scale and failures | 7 | Region failover, a dispatch crash, a driver offline mid-trip, demand spikes, monitoring. |
| 7. Wrap up | 3 | Recap, trade-offs, what is out of scope, the phased plan. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Which flows are in scope: request a ride, match a driver, live tracking, ETA, pricing, payment? | Ride sharing is huge. We need a boundary, or we will draw 30 boxes and go deep on none. | Request, match, live tracking, ETA and surge pricing. Payment is a stub we call. | We design dispatch, location, trip and pricing in detail. Payments is a saga step, linked to a separate design. |
| Do drivers accept or decline an offer, and how long do they have? | A human in the loop makes matching slower and creates a timeout case. | Yes. A driver has about 10 seconds to accept. | Offers are time-limited and need an expiry. We must handle decline and silence. |
| Is a rider matched to the nearest driver, or the best match overall? | Nearest-first is simple. Looking at all requests together gives a better total but adds waiting. | Start simple (nearest by ETA). Mention batching as an improvement. | We build per-request matching first, and explain the batch option and its cost. |
| How fresh must a driver's location be? | Freshness sets the update rate, which sets the biggest load in the system. | A position every 4 seconds while online. A few seconds of delay is fine. | 750k writes a second at peak. Latest-only storage, no per-ping database write. |
| Do we show the driver moving on the rider's map? | Live tracking means a second fan-out path and many open connections. | Yes, during an active trip. | WebSocket gateways, and fan-out only to riders with a live trip. |
| Is there surge or dynamic pricing? | It needs a supply and demand signal per area, in near real time. | Yes, a multiplier per area. | A pricing service that counts requests and free drivers per cell over a sliding window. |
| Pool or shared rides, scheduled rides, ratings, support? | Each is a project of its own. | Out of scope. Mention how pool would change matching. | Keep the design to one rider, one driver, one trip. |
| One city or global? What scale? | Geography is the natural way to shard. Scale sets the numbers. | Global, many cities. 100M monthly users, 10M rides a day, 3M drivers online at peak. | Shard everything by region. Cross-region rides are rare and handled at the border. |
| What availability do we need, and what may fail? | A ride request that fails is lost revenue. A trip in progress that breaks is a safety problem. | 99.95% for requests. A trip in progress must never be lost. | Durable trip store, idempotent transitions, and failover per region. |
| Can location be approximate, or does privacy matter? | Location trails are sensitive personal data. | Keep trails short-lived, and only the latest point is used in real time. | Sampled trails with a retention limit, and access controls. |
| Assumption | Value |
|---|---|
| Drivers online at peak | 3,000,000 |
| Location update interval | every 4 seconds |
| Size of one location update | about 100 bytes |
| Rides per day | 10,000,000 |
| Peak to average ride requests | 8 times (illustrative) |
| Candidate drivers per request | 10 |
| Average trip, including wait | 20 minutes |
| Trip row size | about 2 KB |
| Regions (for sharding) | 10, evenly (illustrative) |
| One Redis-like node, simple operations | about 100,000 per second, target 50% load |
| What | Maths | Result |
|---|---|---|
| Location writes per second (peak) | 3,000,000 รท 4 s | 750,000 per second |
| Location ingest bandwidth | 750,000 ร 100 bytes | 75 MB/s |
| Ride requests per second, average | 10,000,000 รท 86,400 | about 116 per second |
| Ride requests per second, peak | 116 ร 8 | about 930 per second |
| Location load compared with ride requests | 750,000 รท 930 | about 800 times more writes than requests |
| In-memory index of online drivers | 3,000,000 ร 100 bytes | 300 MB (about 30 MB per region) |
| Writes per second per region | 750,000 รท 10 | 75,000 per second, one shard handles it |
| Nodes for location writes at 50% load, if one shared store | 750,000 รท 100,000 รท 0.5 | 15 nodes |
| Raw pings per day if every one were kept (average online is 25% of peak) | 3,000,000 ร 21,600 pings ร 0.25 | 16.2 billion pings, 1.6 TB a day |
| Pings kept if we sample one in five (every 20 s) | 16.2 billion รท 5 = 3.24 billion ร 100 bytes | 0.32 TB a day, about 118 TB a year |
| Trip storage | 10,000,000 ร 2 KB | 20 GB a day, about 7.3 TB a year |
| Trip state writes | 116 ร 6 transitions (peak: ร 8) | about 700 a second average, 5,600 at peak |
| ETA calls at peak (10 candidates each) | 930 ร 10 | about 9,300 per second |
| Concurrent trips at peak | 930 per second ร 1,200 s | about 1.1 million |
| Live-map pushes per second at peak | 1,100,000 trips รท 4 s | about 280,000 messages a second |
| WebSocket gateways (50,000 connections each) | drivers 3,000,000 รท 50,000, riders 1,100,000 รท 50,000 | 60 for drivers, about 22 for riders |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| PUT | /v1/drivers/me/location | { lat, lng, heading, speed, ts, seq } | 204 | Sent every ~4 s, often over a long-lived connection. Last write wins per driver. seq lets us drop an old ping that arrives late. |
| POST | /v1/drivers/me/status | { status: online | offline } | 200 { status } | Going online adds the driver to the geo index. Going offline (or no ping for 15 s) removes them. |
| POST | /v1/rides | { pickup, dropoff, quoteId } | 201 { rideId, state: REQUESTED } | Idempotency-Key header, so a retry never creates a second trip. quoteId pins the price the rider saw. |
| GET | /v1/rides/{id} | none | 200 { state, driver, eta, price } | Plus a WebSocket or push stream for live changes. The GET is the fallback after a reconnect. |
| POST | /v1/rides/{id}/cancel | none | 200 { state: CANCELLED, fee } | Idempotent. The fee depends on the state when it is cancelled. |
| POST | /v1/offers/{offerId}/respond | { accept: true | false } | 200 { rideId } or 409 | From the driver. 409 means the offer expired or was withdrawn. The driver gets a clear answer, not silence. |
| Where | What is stored | Notes |
|---|---|---|
| Geo index (memory, per region) | cell โ set of driver ids, and driver โ {lat, lng, status, updated_at} | Latest only. About 100 bytes a driver. Entries expire if no ping for ~15 s. Rebuilt in seconds from incoming pings after a crash. |
| Trips (durable store) | trip_id, rider_id, driver_id, state, pickup, dropoff, price, version, timestamps | Sharded by trip_id or rider. Every state change is a write with a version number. |
| Driver state (small, strongly consistent) | driver_id โ {status, current_trip, reserved_until} | The place where a driver is reserved for exactly one offer or trip. |
| Trail (log) | sampled (driver, time, lat, lng) | Append-only stream to a log or object store. Used for analytics and disputes, with a short retention. |
| Surge counters (memory) | cell โ {requests, free drivers} per sliding window | Tiny. About 20 MB for 100,000 cells. |
REQUESTED --offer sent--> OFFERED OFFERED --driver accepts--> ACCEPTED (driver reserved for this trip) OFFERED --declined/timeout-> REQUESTED (try the next driver) ACCEPTED --driver arrives--> ARRIVED ARRIVED --rider boards--> IN_PROGRESS IN_PROGRESS --drop-off--> COMPLETED --> payment saga REQUESTED | OFFERED | ACCEPTED | ARRIVED --cancel--> CANCELLED (fee rules apply)
| Component | What it does |
|---|---|
| Gateways | Hold the WebSocket connections for drivers and riders. Stateless apart from the open sockets. Fall back to push when a socket drops. |
| Location service | Takes pings, drops stale ones by sequence number, keeps the latest point, and updates the driver's cell. Expires a driver after about 15 s of silence. |
| Geo index | In memory, per region. A grid of cells (geohash, S2 or H3) pointing to the drivers inside. Answers 'who is near this point' in microseconds. |
| Dispatch | Shortlists nearby free drivers, asks the ETA service to rank them, reserves one, and sends the offer. Handles decline and timeout. |
| Driver state | A small, strongly consistent record per driver. A compare-and-set on it is what prevents one driver being offered two rides. |
| Ride service | Owns the trip state machine and the trip store. Every transition is idempotent and versioned. |
| ETA and routing | Pickup ETA and trip ETA from a road graph with live traffic. Cached by cell pair for a few seconds. |
| Pricing | Quotes a price with a surge multiplier per cell, valid for a short time. Reads supply and demand counters. |
| Event log | Every location sample and every trip transition goes onto a log for analytics, disputes and rebuilding views. |
The problem: 750,000 pings a second must update an index that can answer 'who is near this point' in microseconds, while every driver keeps moving. Writing each ping to a database would be 1.6 TB a day of data nobody reads.
| Option | How it works | Good | Bad |
|---|---|---|---|
| A database row per driver, updated on every ping | UPDATE drivers SET lat, lng, updated_at. Query with a bounding box. | Simple. Familiar tools. | 750k writes a second is far beyond one database, and a bounding-box query on moving data keeps hitting hot rows. |
| Quad tree over moving points | A tree that splits where there are many drivers. | Adapts to dense and sparse areas. | Every move may change the tree. Rebalancing under 750k updates a second is expensive. Good for mostly-static points. |
| Fixed grid of cells (geohash, S2 or H3), latest position in memory | Map each ping to a cell id. Keep cell โ drivers and driver โ position in memory, sharded by region. | A move is two small set updates. Lookup is the cell plus its neighbours. Easy to shard by cell prefix. | Needs the neighbour query for the boundary case, and a cell size that fits the density. |
| A geo-aware key-value store (for example sorted sets with geo commands) | Store points in a store that supports radius queries. | Less code to write. Fine for a small or mid-sized city. | One node per region hits a write limit, and you give up control of the cell layout. |
The invariant we protect here is simple: the index holds each online driver exactly once, at roughly their latest position. A fixed grid makes a move cheap (remove from one cell set, add to another) and makes a lookup cheap (read a few cells). A quad tree is great for points that rarely move; for 750k moves a second, rebuilding or rebalancing is the cost we cannot afford.
Per region this is only about 75,000 writes a second and 30 MB, so one in-memory shard (with a replica) is enough. If it is lost, it refills from the next pings in about 4 seconds, so we do not need to persist it. The cost: briefly after a crash the index is thin, so dispatch widens its search radius.
| Cell size (illustrative) | Good for | Cost |
|---|---|---|
| About 150 m (fine) | Dense city centres: few drivers per cell | More neighbour cells to read for a 2 km radius (about 100) |
| About 1 km (medium) | Most cities: tens of drivers per cell | A good default: a 3 by 3 ring covers about 3 km |
| About 5 km (coarse) | Rural areas | Too many drivers per cell in cities, so each lookup scans many |
The problem: Two riders near the same driver ask at the same moment. If both requests read 'driver G is free' and both offer G, one rider is promised a driver who is already gone. The invariant: a driver is reserved for at most one offer or trip at a time.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Read free drivers, offer, hope | Pick the nearest free driver and send the offer. Check later. | Simplest. | Races at busy times: two offers to one driver, a driver sees conflicting offers, and a rider is told yes then no. |
| Lock the whole region while matching | One distributed lock per region. | No races. | Serialises matching for a whole city. Throughput collapses and a stuck holder blocks everyone. |
| Atomic reservation on the driver record | A compare-and-set (free โ reserved for trip T until time X). Only one request wins. A short expiry releases it if nothing happens. | Fine-grained, fast, and correct. Cost is one small strongly consistent write per offer. | Needs a store with atomic conditional writes and a clock for the expiry, and care with the expiry (fencing). |
| Batch (global) matching every ~2 seconds | Collect requests and free drivers for a window, solve one assignment problem for the whole set, then reserve each pair. | A better total pickup time, and no race between requests inside the batch. | Riders wait up to the window. A heavier algorithm. Reservation is still needed against other batches. |
The reservation is what enforces the invariant. Dispatch picks the best driver by road ETA, then does one compare-and-set on that driver's state: from free to reserved for offer O until 10 s from now. If another request got there first, the write fails and dispatch tries the next driver. No locks are held across the network, and a crashed dispatcher cannot strand a driver, because the reservation expires.
Per-request matching is not the best overall. Early riders take drivers that later riders needed more. Batching gives a lower total pickup distance, at the cost of a short wait (see the visualizer). The pragmatic answer: start per-request, and batch only in cells where demand is high enough that the wait is worth it.
-- one small strongly consistent record per driver
ok = driverState.compareAndSet(
key = driverId,
expect = { status: FREE },
set = { status: RESERVED, tripId: T, until: now + 10s, version: v + 1 })
if (!ok) -> take the next candidate -- somebody else won
-- on accept: RESERVED -> ON_TRIP (same tripId, same version check)
-- on decline / timeout / expiry: RESERVED -> FREE (only if tripId and version still match)| Offer style | How | Good | Bad |
|---|---|---|---|
| One driver at a time | Offer, wait up to 10 s, then the next | No wasted offers. Fair to drivers. | Slow if several decline: 3 declines is 30 s |
| A few at once, first to accept wins | Offer to 3, cancel the others when one accepts | Faster match | Drivers see offers that vanish. Reserve all three, release two. More complexity. |
The problem: A trip lasts about 20 minutes, across phones that lose signal, servers that restart and users who tap twice. Invariants: one active trip per rider, one per driver, and no transition applied twice or lost.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Keep trip state in memory on one server | A server owns the trip while it runs. | Fast and easy. | A crash loses live trips. A rolling deploy drops them. Failover is manual. |
| Save the state, but update with plain writes | UPDATE trips SET state = ? WHERE id = ? | Survives a crash. | A retried tap or a late message can move the trip backwards (ARRIVED then back to ACCEPTED), and two writers can disagree. |
| A versioned state machine with conditional writes | Each transition says 'from state S at version v to state S2'. The store applies it only if the current state and version match. Retries carry the same transition id. | Idempotent, safe to retry, rejects stale or illegal moves, and every change is a durable row. | Needs a store with conditional updates, and clients that handle a 409 by re-reading the trip. |
| Event sourcing: store transitions, derive the state | Append events (accepted, arrived...) and fold them to get the current state. | A full audit trail and easy replay. | Heavier to build. You still need a conditional append so two events cannot both be the next one. |
The mechanism for no transition applied twice or lost is the conditional write plus a transition id: UPDATE ... SET state = 'ARRIVED', version = v + 1 WHERE id = ? AND state = 'ACCEPTED' AND version = v. A retry with the same transition id finds the work already done and returns success. A stale or impossible move updates zero rows and is rejected. The trip store is sharded by trip id, so each trip is one row on one shard.
One active trip per rider and per driver is a second invariant. For the driver it comes from the reservation record. For the rider, the create call takes an idempotency key and checks a unique constraint on (rider, active). Cost: a few more conditional writes, and every client must handle a 409 by re-reading the trip.
| Failure | What the design does |
|---|---|
| The driver app loses signal mid-trip | The trip is already saved, so nothing is lost. The app buffers pings and transitions locally, and on reconnect sends them with sequence numbers. The server applies the ones that still fit and ignores the rest. |
| A server crashes between saving a transition and replying | The client retries with the same transition id. The store sees the work is done and returns the saved result. |
| A rider double-taps request ride | The same idempotency key, so one trip. A second key while one is active hits the unique constraint. |
| A trip is stuck in OFFERED because dispatch died | A sweeper finds OFFERED trips with an expired reservation and puts them back to REQUESTED. |
| The driver forgets to end the trip | A timeout rule and a geofence check suggest completion. A human or support flow settles the rest. |
| Payment fails after COMPLETED | A saga retries or flags it. The trip is not rolled back (the ride happened). See Design a Payment System. |
The problem: Matching needs a believable pickup time. Pricing must react to demand without flapping. And a million riders must see cars move without a million database reads.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Straight-line distance for ETA | Distance divided by an average speed. | Trivial and instant. | Wrong near rivers, one-way streets and highways. Ranks a driver across a river as nearest. |
| Road graph routing with live traffic, cached | Shortest path on the road graph using current speeds. Cache results by (cell, cell) for a few seconds. | A believable ETA, and about 9,300 calls a second is manageable. | Needs a routing service, traffic data and a cache with a short life. |
| Surge: a multiplier from supply and demand per cell | Count requests and free drivers over a sliding window. Map the ratio to a multiplier, with smoothing. | Reacts to real conditions and pulls drivers to busy areas. | A raw ratio flaps from second to second. Needs smoothing, caps and a short-lived quote. |
| Push live position to riders over a socket | The gateway forwards each driver ping to the one rider on that trip. | A smooth live map. Only riders with an active trip receive anything. | About 280,000 messages a second at peak and 1.1 million open connections to manage, with reconnects. |
ETA decides who is 'nearest', so it must be road-based, and it is the one place the design depends on the maps system (see Design Google Maps). Caching by cell pair keeps it cheap because many requests in the same area ask nearly the same question.
For surge, compute ratio = requests รท free drivers per cell over a sliding window of about a minute, average it with neighbouring cells and the previous value, cap it, and round to steps (1.0, 1.2, 1.5...). The rider gets a quote that is valid for a couple of minutes, so the price they saw is the price they pay. Cost: a rule that is hard to explain and sensitive to regulation and fairness, so state that these rules vary by place and need a policy owner.
| Surge rule (illustrative) | Requests / free drivers | Multiplier |
|---|---|---|
| Calm | up to 1.0 | 1.0ร |
| Busy | 1.0 to 1.5 | 1.2ร |
| Very busy | 1.5 to 2.5 | 1.5ร |
| Peak (capped) | above 2.5 | 2.0ร cap |
surge = 0.7 ร previous + 0.3 ร new_ratio, updated every 30 seconds. Without it, a single request can flip a cell between 1.0ร and 1.5ร and riders see the price change while they look at it.A teaching model on an 8 by 8 grid with fixed positions (no random numbers). Distance is the number of blocks along the streets, not a straight line. Real systems use road distance and live traffic for the pickup time, and add many more rules (rating, vehicle type, direction of travel). One request at a time picks the nearest free driver, and ties go to the lower letter. Batch tries every way of pairing riders and drivers and keeps the one with the lowest total.
| Bottleneck | Fix |
|---|---|
| 750k location writes a second | Shard by region (about 75k a second each). Batch pings per gateway. Adaptive ping rate. Keep latest-only in memory, and sample the trail to a log. |
| A hot cell (stadium, airport) with thousands of drivers and riders | Split the cell into finer cells, or use a smaller hex size for that area. Batch matching in that cell, and queue requests for the next window. |
| Demand spike when an event ends | Surge pulls drivers in. Dispatch uses batch matching and a request queue with a cap. Shed load on non-essential calls (history, receipts) first. |
| ETA service latency during matching | Cache by cell pair, rank only a shortlist of about 10, set a deadline, and fall back to straight-line ranking if routing is slow. |
| Open connections: about 80 gateways, millions of sockets | Stateless gateways behind a load balancer, a connection registry for 'which gateway holds this user', and jittered reconnects after a gateway restart. |
| Trip store write load at peak (about 5,600 transitions a second) | Shard by trip id. Each trip is one row on one shard, so this is easy to spread. |
| Cross-region rides near a border | Assign the trip to the pickup region. Query the neighbour region's index for drivers within range. The driver reservation lives in the driver's home region. |
| Failure | How the design copes |
|---|---|
| A geo index shard crashes | A replica takes over. The index is rebuilt from the next pings in about 4 seconds. Dispatch widens its search radius during the gap. |
| Dispatch crashes after reserving a driver | The reservation expires in 10 seconds and the driver is free again. A sweeper returns the trip to REQUESTED and matching restarts. |
| A whole region goes down | Riders and drivers fail over to a standby region. Trips in progress are in a replicated trip store. Accept that a few seconds of transitions may need to be replayed from device buffers. |
| The driver app is offline (a tunnel) | The trip is safe in the store. The app buffers and replays on reconnect. The rider sees the last known position, marked as stale. |
| ETA or routing service is down | Fall back to straight-line ranking with a safety margin, and show a wider ETA range to the rider. |
| Payment service is slow or down at the end of a trip | Complete the trip, queue the charge, and retry with an idempotency key. Never block the rider from leaving the car. |
Drivers send a location every 4 seconds into a sharded in-memory grid that keeps only the latest point, about 300 MB for all online drivers. A rider's request becomes a trip in a versioned state machine. Dispatch shortlists nearby drivers from the grid and its neighbours, ranks by road ETA, and reserves the best driver with an atomic compare-and-set before offering, so no driver is promised twice. Surge is a smoothed supply-and-demand ratio per cell with a short-lived quote, and the live map is pushed over sockets to riders with an active trip. Payments run later as a saga.
| Decision | What we gain | What it costs |
|---|---|---|
| Latest-only location in memory | Handles 750k writes a second with a tiny index and no database on the hot path. | Position history is only a sample. A shard crash leaves a few seconds of thin coverage. |
| Fixed grid cells, not a quad tree | A move is two cheap set updates. Easy to shard. | Needs the neighbour query and a good cell size for density. |
| Atomic driver reservation with expiry | No double assignment, with no region-wide lock. | One strongly consistent write per offer, and care with expiry and stale writers. |
| Per-request matching first | Simple, fast, no waiting for a batch. | Not the best total pickup time. Batching in busy cells can do better, at the cost of a short wait. |
| Versioned, idempotent state machine | Safe retries and no lost or repeated transitions. | Clients must handle 409 and re-read. A conditional-write store is required. |
| Smoothed surge with a quote | Stable prices that riders can trust, and supply that follows demand. | Complex to explain, and sensitive to fairness and regulation. |
The biggest load in the system. Know why, and know the structure.
The correctness heart of the design: one driver, one offer.
Interviewers push on what happens when the phone, the server or the region fails.
The senior questions: spikes, geography, cost, privacy and how you would test it.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Add pool and shared rides | Matching becomes routing: a vehicle holds several riders, each match is a route with detours and ETA limits. The driver reservation becomes seats. Batch matching becomes essential. |
| Add scheduled rides (book for tomorrow 6 am) | A scheduled-jobs store holds the request. A job releases it to dispatch shortly before pickup, and a driver can be pre-assigned. Needs a no-show plan. |
| Riders should see a fixed price, not a surge multiplier | Pricing returns a quote from a model of expected demand and trip cost. The quote is guaranteed, so the company carries the risk. Surge counters feed the model, not the price directly. |
| Drivers must be matched fairly (no favourites) | Add a fairness term to ranking, such as time since last trip, and measure the distribution of trips. Batch matching can optimise it directly. |
| Ten times more drivers online | 7.5M writes a second. Shard more finely by cell prefix, lower the ping rate when idle, and batch at the gateway. The index still fits in memory: 3 GB. |
| Deliveries (food, packages) on the same platform | Add a second kind of trip with pickup and drop-off at different places, and a different state machine. The geo index and location service are shared. |
| Hard real-time guarantee: match in under 2 seconds at the 99th percentile | No parallel offers waiting on a human, so use pre-fetched shortlists, a hot reservation path and driver auto-accept in limited cases. More cost, less choice for drivers. |
| Offline mode for riders with bad signal | SMS or push fallback for the key transitions, a long-lived idempotent create call, and a clear local state so the app can resume safely. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing at once, or builds everything (pool, ratings, payments). | Scopes request, match, track, ETA and pricing, and states what is left out. | Also fixes the numbers, the location freshness, the accept timeout and the failure expectations, and says what drives the design. |
| Estimation | No numbers, or counts only rides. | Works out ride requests per second and some storage. | Finds that location writes are about 800 times the requests, and uses that to justify latest-only in-memory storage and sampled trails. |
| Geo index | SQL table with lat and lng, or a bounding box on every query. | Grid or geohash with a neighbour lookup. | Explains the boundary problem, cell size by density, why not a quad tree for moving points, sharding by region, and rebuilding from pings. |
| Dispatch correctness | Offers to the nearest driver with no race handling. | Notices the double-assignment problem and adds a lock or a check. | States the invariant, uses a per-driver atomic reservation with expiry, handles late accepts and dispatcher crashes, and compares batch matching with its cost. |
| Failure and state | Assumes servers never fail mid-trip. | Saves trip state and mentions retries. | A versioned idempotent state machine, sweepers for stuck states, offline driver replay, and a region failover plan with its limits. |
| Communication | Jumps between topics and lists technologies. | Follows the steps and explains each choice. | Summarises each step, names trade-offs with numbers, says what is out of scope, and offers a phased plan. |
| Mistake | Do this instead |
|---|---|
| Treating ride requests as the main load | Do the maths: location pings are about 800 times more frequent. Design the location path first. |
| Writing every location ping to a database | Keep only the latest in memory, sampled trails on a log, and say why. |
| Finding nearby drivers with a bounding-box SQL query | Use a cell grid with a neighbour lookup, in memory, sharded by region. |
| Ignoring the double-assignment race | State the invariant and reserve the driver with an atomic compare-and-set and an expiry. |
| Ranking by straight-line distance | Rank a shortlist by road ETA with live traffic, and say how you cache it. |
| Keeping trip state in server memory | A durable, versioned state machine with idempotent transitions and sweepers. |
| Cancelling a trip when pings stop for a few seconds | Tunnels and weak signal are normal. Buffer, replay, and escalate only after a long silence. |
| Putting payment logic inside the trip service | Complete the trip first, then run a saga with idempotency keys. Link to the payment design. |
A way to turn a place into a cell id.
The cell systems used for ride sharing, and the hexagon advantage.
The alternative index, and why moving points make it costly.
How the live map and offers reach the phones.
Why we use a per-driver compare-and-set and not a region lock.
Why retried taps and transitions must be harmless.
How trip completion and payment stay consistent.
Where road routing and ETA come from.