“Match a rider to a driver” sounds like nearest-neighbor search. Then you add pooling. Now the rider you want to match is not looking for an empty car - they are looking for a car that is already carrying one or two other passengers, heading roughly their way, that can swallow a new pickup and a new drop-off without making anyone else’s trip meaningfully worse. The question stops being “who is closest” and becomes “which in-progress trip can absorb this person for the least total detour, while still getting everyone picked up inside their promised time window.” That is an online vehicle routing problem, and you have to answer it in a couple of seconds, over and over, for a whole city, while cars are moving and other requests are landing at the same instant.
The core of this problem is that every new ride request must be inserted into one of thousands of live, partially-full trips such that total extra distance is minimized and no existing passenger’s pickup or drop-off time window is violated - and the decision must return in seconds, not minutes. Optimal multi-vehicle routing is NP-hard; you cannot solve it exactly at dispatch latency. So the entire design is about trading global optimality for a good-enough answer fast: narrow the candidate set with geospatial filtering, evaluate each candidate with a cheap greedy insertion heuristic, respect hard time-window constraints as you go, and commit the assignment atomically so two requests never claim the same seat. Let me build it properly.
Functional Requirements (FR)
In scope:
- Request a pooled ride. A rider submits pickup and drop-off locations and a party size (1-3 seats). The system finds a shared trip to join or, failing that, starts a new trip, and returns an ETA, a price, and a matched driver within a few seconds.
- Insert into an in-progress trip. The heart of the system: given a car already carrying passengers with a committed route, decide whether and where to insert the new rider’s pickup and drop-off stops so total detour is minimized and all time windows still hold.
- Respect per-passenger time windows. Each passenger has a promised pickup-by time and a maximum trip-time/detour cap. A new insertion must not push any existing passenger past their guarantees.
- Live route and ETA updates. As the car moves and new riders join, each passenger’s route, sequence of stops, and ETA update in real time.
- Driver supply tracking. Drivers continuously report GPS location, current occupancy, and remaining capacity. The matcher needs a fresh view of supply.
- Match within a bounded window. If no good pooled match is found within a few seconds, fall back to a solo (non-pooled) match or re-queue, rather than block the rider.
- Pricing for pooled rides. A pooled fare is cheaper than solo and reflects the shared segment; compute and lock the price at match time.
- Cancellations and re-optimization. A rider cancels before pickup; the car’s route re-optimizes to drop that stop and possibly free a seat for a pending request.
Explicitly out of scope (name it so you own the scope):
- Turn-by-turn navigation and the map/routing engine internals. I call a routing/ETA service that returns travel time and distance between two points given live traffic; I do not build the road graph or the shortest-path engine.
- Payments and the pricing model itself. I integrate a pricing service and a payment gateway as external async dependencies; I store the quoted fare and the charge reference.
- Driver onboarding, ratings, fraud, incentives. Supply acquisition and driver economics are separate systems; a driver that appears in the matcher is already authenticated and online.
- Solo-ride dispatch in depth. Classic one-rider-one-driver matching is the degenerate case; I focus on the pooling insertion problem, which subsumes it.
- Cross-city / intercity pooling. I design intra-city pooling where trips are short (minutes to tens of minutes) and the city is a bounded region.
The decision that drives everything: a trip is not a rider-to-driver edge; it is an ordered list of stops (an itinerary) attached to one vehicle, and matching is the act of inserting two new stops (a pickup and a drop-off) into that ordered list at the cheapest feasible positions. Detour minimization, time windows, and capacity all reduce to “evaluate candidate insertion points into existing itineraries, pick the best feasible one, commit it atomically,” and the rest of the system exists to make that evaluation fast and the commit safe.
Non-Functional Requirements (NFR)
- Scale: a large metro with ~5M daily riders, of whom a meaningful fraction choose pooling. Assume ~1.5M pooled ride requests/day, peaking at rush hour. ~150,000 active drivers at peak, a large share of them carrying 1-2 passengers already, so there are tens of thousands of in-progress poolable trips at any instant. GPS pings from drivers arrive continuously (every ~4s per driver).
- Latency: a match decision must return in under ~2-3 seconds end to end. The geospatial candidate filter must run in tens of milliseconds; the insertion evaluation across candidates in a few hundred milliseconds. Riders abandon if they stare at “finding your ride” too long.
- Availability: 99.9%+. If the pooling matcher is degraded it must gracefully fall back to solo matching rather than fail the request. A rider never gets a hard error because pooling was busy.
- Consistency: seat assignment needs strong consistency per vehicle - a given seat on a given trip is granted to exactly one rider; two requests must not both insert into the last free seat. Supply location and ETAs can be eventually consistent (a GPS position that is 1-2 pings stale is fine).
- Durability: a confirmed match and its committed itinerary must survive a crash. Once a rider is told “your car is 3 minutes away, seat B,” that fact and the route it implies are durable.
- Quality of match (a real NFR here): the system should keep average detour per passenger bounded (say under ~15-20% added time) and pool fill rate high (more shared seats = cheaper rides and fewer cars). A matcher that returns fast but routes everyone through terrible detours is a failure even if it meets latency.
The tension to state up front: optimal pooling is a global combinatorial optimization, but dispatch demands a per-request answer in seconds. Solving the full multi-vehicle routing problem (which trips, which passengers, which order, city-wide, jointly) is NP-hard and takes far longer than a rider will wait. We resolve it by decomposing the global problem into independent per-request insertions: filter to a small candidate set of nearby compatible trips with a geospatial index, run a greedy cheapest-insertion heuristic against each candidate, enforce time windows as hard constraints during evaluation, and commit the single best feasible insertion. We knowingly trade global optimality (a batch solver would pack cars slightly better) for the bounded latency live dispatch requires, and claw back some quality with short batching windows and periodic re-optimization.
Back-of-the-Envelope Estimation (BoE)
Real numbers with the arithmetic, because they dictate the architecture.
Request and match load:
Pooled ride requests per day: ~1,500,000
Average over the day: 1.5M / 86,400s = ~17 requests/sec.
Rush-hour concentration: ~35% of a day's rides land in ~3 peak hours.
0.35 * 1.5M = 525,000 requests in 3h = 10,800s -> ~49 requests/sec,
bursting to ~100-150 requests/sec in the tightest 15-minute windows.
So the request rate is modest - tens to low hundreds per second. The expensive part is not request volume, it is the work per request: each request evaluates many candidate trips.
Candidate evaluation is the real cost:
Active drivers at peak: ~150,000
In-progress poolable trips: ~tens of thousands (cars with a free seat
and a route compatible with new pickups).
Per request, geospatial filter narrows to candidates nearby and headed
the right way: assume ~30-100 candidate trips after filtering.
Each candidate insertion eval: try inserting pickup + dropoff at feasible
positions in an itinerary of up to ~6 stops.
Insertion positions ~ O(stops^2) ~ up to ~30 position pairs, but pruned
hard by time windows to a handful of feasible ones.
So per request: ~50 candidates * ~a few feasible position pairs each
* a routing/ETA lookup per trial = ~hundreds of ETA evaluations.
At 150 req/sec peak: 150 * ~300 evals = ~45,000 ETA evaluations/sec.
The headline: the matcher is an ETA-evaluation-bound system, not a request-bound one. The number that matters is candidate evaluations times routing lookups per second (tens of thousands), and the whole design is about shrinking that number (fewer, better candidates) and making each evaluation cheap (cached/approximate travel times) so the per-request budget stays under a couple hundred milliseconds.
Driver GPS ingestion:
Active drivers: ~150,000
Ping interval: every ~4s
Ingest rate: 150,000 / 4 = ~37,500 location updates/sec.
Each ping: driver_id, lat, lng, heading, occupancy, ts ~ 50-80 bytes.
Bandwidth: ~37,500 * 70B = ~2.6 MB/sec of raw pings -> trivial bytes,
but 37,500 writes/sec into a live spatial index is the real pressure.
So supply tracking is a ~37K writes/sec geospatial update problem - high write rate, small payloads, must be queryable by location with low latency.
Storage:
A completed trip record: rider+driver ids, stop sequence with times,
distances, fares, detour metrics ~ 2-3 KB.
1.5M pooled trips/day * 3 KB = ~4.5 GB/day -> ~1.6 TB/year of trip history,
retained for analytics, disputes, and pricing calibration.
Live state (in-progress itineraries): tens of thousands of trips, each an
itinerary of a few stops + passenger constraints ~ 2 KB.
~50,000 live trips * 2 KB = ~100 MB of hot itinerary state - fits in memory.
The crucial fact: the live, contended state (active itineraries + current supply positions) is small enough to live in memory, so matching reads and the seat-commit can happen against an in-memory store, with durable trip history and event logs behind it. The read storm, the write storm, and the compute storm are three different problems - supply ingestion, candidate retrieval, and insertion evaluation - and the design matches a tier to each.
High-Level Design (HLD)
The spine: drivers stream GPS into a location ingestion pipeline that maintains a live geospatial index of supply. A rider request hits a stateless matching service that (1) queries the geospatial index for nearby compatible in-progress trips, (2) runs the insertion/routing evaluator against those candidates using a routing/ETA service (heavily cached), (3) picks the best feasible insertion, and (4) commits it atomically via the trip/itinerary service, which owns each live trip’s ordered stop list and seat inventory in memory. A dispatch/notification layer pushes the updated route to the driver and the ETA to the rider. An event stream persists trips, feeds re-optimization, and updates analytics/pricing.
Drivers (GPS every ~4s) Riders (ride requests)
│ │
▼ ▼
┌───────────────────┐ ┌───────────────────────────┐
│ Location Ingestion │ │ Matching Service (stateless, N) │
│ (ping stream) │ │ orchestrates one match │
└─────────┬─────────┘ └───┬───────────────┬─────────┘
│ writes │ 1. candidates │ 3. commit
▼ ▼ ▼
┌───────────────────┐ ┌────────────────────┐ ┌──────────────────────┐
│ Geospatial Index │◄───────│ Candidate Retrieval │ │ TRIP / ITINERARY SVC │
│ (live supply: │ query │ (geo + direction + │ │ owns each live trip: │
│ driver cells, │ │ capacity filter) │ │ ordered stops + seats │
│ in-progress trips)│ └─────────┬──────────┘ │ atomic insert/commit │
└───────────────────┘ │ 2. evaluate │ sharded by trip_id │
▼ └───────┬──────────────┘
┌────────────────────────┐ │ committed itinerary
│ Insertion Evaluator │ ▼
│ greedy cheapest-insert │ ┌──────────────────┐
│ + time-window feasibility│ │ Dispatch / Notify │
└───────────┬────────────┘ │ push route->driver│
│ ETA queries │ push ETA->rider │
▼ └────────┬─────────┘
┌────────────────────────┐ │
│ Routing / ETA Service │ ▼
│ (travel time+distance, │ ┌──────────────────────────┐
│ live traffic, CACHED) │ │ Event Stream (Kafka) │
└────────────────────────┘ │ trips, re-optimization, │
│ pricing, analytics, audit │
└────────────────────────────┘
Match flow (the happy path, a rider joins an in-progress pool):
- A rider submits pickup P and drop-off D with party size. The request lands on a stateless matching service instance, which attaches a request id and a deadline (say now + 2.5s).
- Candidate retrieval queries the geospatial index: find in-progress trips whose current position is near P, that have a free seat for the party size, and whose direction of travel is roughly compatible with P -> D. This narrows tens of thousands of trips to ~30-100 candidates in tens of milliseconds.
- The insertion evaluator takes each candidate trip’s current itinerary and tries inserting P and D at feasible positions. For each trial it asks the routing/ETA service (cache-first) for the incremental travel time/distance, computes the added detour, and checks time-window feasibility for every existing passenger and for the new rider. Infeasible trials are discarded; feasible ones are scored by added detour.
- The evaluator returns the single best (lowest-detour, feasible) insertion across all candidates - trip T, pickup position i, drop-off position j - or “no feasible pool.”
- The matching service calls the trip/itinerary service for trip T to commit the insertion atomically: it re-validates feasibility against the trip’s current state (the car moved since step 2), claims a seat, and splices P and D into the ordered stop list. This is the single serialization point per trip - it prevents two riders from both taking the last seat.
- On commit, the updated itinerary is pushed to the driver via dispatch (new next stop, reordered route) and the ETA/price is returned to the rider. A
match_committedevent is emitted for persistence, pricing, and analytics.
No-pool flow: if step 4 finds no feasible pooled insertion within the deadline, the matcher falls back to starting a new trip on the nearest empty/under-full car (the solo/degenerate case) or re-queues briefly, so the rider always gets an answer.
The structural insight: the only strongly-consistent, serialized operation is the atomic seat-claim-and-splice on one trip’s itinerary, and it happens in memory per trip. Candidate retrieval is a stale-tolerant geospatial read; ETA evaluation is cache-backed approximate compute; persistence and pricing are async. Strong consistency lives only on the per-trip commit; everything expensive is pushed around it.
Component Deep Dive
The hard parts, naive-first then evolved: (1) the insertion heuristic that minimizes detour under time windows, (2) narrowing candidates with a geospatial + directional filter, (3) the atomic seat-claim-and-splice commit, (4) keeping routing/ETA evaluation cheap enough to do hundreds of times per request.
1. Inserting a rider into a trip: minimize detour under time windows
The job: given a car with an ordered itinerary of stops (pickups and drop-offs for existing passengers, each with time-window constraints) and a new rider (pickup P, drop-off D), decide where to put P and D in the sequence so that total added travel time is minimized and no passenger - old or new - has their guarantees violated.
Naive approach: solve the routing optimally for each candidate
For each candidate trip, enumerate all possible orderings of the full stop set (existing stops plus P and D), compute the total route cost of each ordering with the routing engine, and pick the globally optimal sequence that keeps all time windows satisfied.
For trip T with k existing stops, adding P and D:
consider all valid permutations of (k + 2) stops that keep each
passenger's pickup-before-dropoff order, score each with the router,
pick the min-cost feasible permutation.
Where it breaks:
- It is factorial. Even a small itinerary explodes: ordering k+2 stops with precedence constraints is still a Traveling-Salesman-with-pickup-and-delivery subproblem per candidate. With ~50 candidates and a deadline of ~2 seconds, you cannot enumerate orderings for each - you blow the latency budget by orders of magnitude.
- Each permutation costs a routing lookup. Scoring a full ordering needs the router for every consecutive-stop leg. Thousands of permutations times multiple legs times tens of candidates is tens of thousands of routing calls for a single request - nowhere near the few-hundred-millisecond budget.
- It re-plans stops that are already committed. Reordering the existing passengers’ stops freely can change promises already made to riders mid-trip (their ETA jumps around). Live passengers need stability, not a fresh global re-solve on every new join.
- Optimality is wasted. The marginal quality gain from a perfectly optimal insertion over a good greedy one is small, but the latency cost is enormous. You are paying NP-hard compute for a rounding-error improvement a rider never notices.
Exact per-candidate routing is correct but its cost is exponential in stops, and live dispatch has a hard few-second ceiling, so it is simply not an option.
Evolved approach: greedy cheapest-insertion with time-window pruning
Do not re-order the existing route. Keep the committed sequence fixed and find the cheapest place to splice in P and then D, rejecting any placement that breaks a time window. This is the classic cheapest-insertion heuristic adapted to pickup-and-delivery with time windows.
- Fix the existing order; insert into gaps. The itinerary is a sequence of stops
s0, s1, ..., sk(s0 = car’s current position). Inserting the pickup P means choosing a gap(si, si+1)to place P between. Inserting the drop-off D means choosing a later gap(sj, sj+1)withj >= i(D must come after P). So an insertion is a pair of positions(i, j)- at mostO(k^2)pairs, and k is tiny (a full pool is ~3 passengers = ~6 stops), so this is a handful of candidate pairs, not a factorial explosion. - Incremental cost, not full re-score. The added detour of inserting P between si and si+1 is
detour(P) = travel(si, P) + travel(P, si+1) - travel(si, si+1)- three routing lookups, independent of the rest of the route. Insert D similarly. The marginal cost of an insertion is a small, local computation, not a re-route of the whole trip. - Time windows prune aggressively. Before scoring, check feasibility: inserting P and D pushes back the arrival time of every stop after the insertion points. For each downstream passenger, verify their drop-off still lands inside their max-trip-time window, and the new rider’s own pickup-by and max-detour hold. Any placement that violates a window is discarded immediately - no scoring needed. In practice time windows kill most of the
O(k^2)pairs, leaving one or two feasible placements to score. - Greedy pick, bounded regret. Among feasible
(i, j)placements across all candidate trips, choose the one with the minimum total added detour (summed over the new rider and the pushed-back existing passengers, optionally weighted). It is greedy per request: once a rider is inserted, it stays put; later requests insert around it. This can be globally sub-optimal versus a batch solver, but each decision is feasible, cheap, and stable for existing passengers.
INSERT(trip T, new P, new D): # T.stops = [s0, s1, ..., sk]
best = (cost=INF, i=None, j=None)
for i in 0..k: # gap to place pickup P
p_cost = travel(s[i],P)+travel(P,s[i+1])-travel(s[i],s[i+1])
if pushes_back_violates_window(T, after=i, delay=p_cost): continue
for j in i..k: # gap to place dropoff D (>= P's pos)
d_cost = travel(s[j],D)+travel(D,s[j+1])-travel(s[j],s[j+1])
if violates_window(T, insert P@i, D@j): continue
total = p_cost + d_cost + pushed_back_penalty(existing pax)
if total < best.cost: best = (total, i, j)
return best # feasible cheapest insertion for THIS trip, or INF
MATCH(request):
candidates = geo_filter(P, D, party_size) # deep dive 2
scored = [ INSERT(T, P, D) for T in candidates ]
winner = min(scored by cost) # across all trips
if winner.cost == INF: fall_back_to_new_trip()
else: commit(winner.trip, winner.i, winner.j) # deep dive 3
Why this is right:
- The per-candidate work is
O(k^2)with tiny k, not factorial. With ~6 stops max per trip, that is a few dozen position pairs, most pruned by time windows, so a candidate costs a handful of routing lookups - affordable across ~50 candidates inside a few hundred milliseconds. - Incremental detour is a local computation. You never re-score the whole route; you compute the marginal cost of splicing two stops into two gaps. That is what keeps the ETA/routing call count bounded.
- Time windows are hard constraints checked cheaply. Feasibility is a forward pass over downstream arrival times, so a violating placement is rejected before any expensive scoring. Existing passengers’ guarantees are never silently broken.
- Existing passengers stay stable. Because the committed order is fixed and only new stops are spliced in, a rider already in the car does not see their route reshuffle every time someone new joins - at most their ETA pushes back by the bounded insertion delay, which you can cap and even reject against.
This “fix the route, cheapest-insert the new stops, prune by time windows, greedy-pick lowest detour” is the standard online pooling heuristic precisely because it converts an NP-hard re-route into a bounded local evaluation that fits the dispatch latency budget. The cost of greediness (slightly worse packing than an offline optimum) is reclaimed later by batching and re-optimization, discussed below.
2. Narrowing candidates: geospatial plus directional filtering
The job: of tens of thousands of in-progress trips, find the ~30-100 worth evaluating for a given request - near the pickup, with a free seat, and heading a compatible direction - in tens of milliseconds. Evaluate too many and you blow the budget; evaluate too few and you miss good matches.
Naive approach: scan all in-progress trips and test each
For each request, iterate every active trip, compute the distance from its current position to P, and run the insertion evaluator on all of them, letting the detour score sort it out.
Where it breaks:
- It is a full scan per request. Tens of thousands of trips times ~50-150 requests/sec means millions of trip-distance computations per second, and worse, you would run the (relatively expensive) insertion evaluator on every trip - instantly blowing the per-request latency budget.
- It ignores direction. A car two blocks from the pickup but driving the opposite way is a terrible match (huge detour), yet pure distance ranks it highly. You waste evaluation on trips that geometry alone could have rejected.
- It does not scale with the city. As supply grows, the scan grows linearly; there is no spatial pruning, so hot rush-hour load makes the scan worse exactly when you need it fast.
Scanning all trips makes candidate retrieval O(active trips) per request, which is both too slow and full of obviously-bad candidates.
Evolved approach: a spatial index (geohash / S2 / H3 grid) plus a direction and capacity filter
Index live supply by location in a grid/hierarchical spatial structure so “trips near P” is a cell lookup, then prune by direction of travel and free capacity before any insertion scoring.
- Grid the city, index trips by cell. Map every active trip’s current position to a spatial cell (geohash prefix, or an S2/H3 cell at a chosen resolution). The geospatial index is a map
cell -> {trip ids currently in this cell}, updated as cars move (deep dive on ingestion below). “Trips near P” becomes “look up P’s cell and its neighboring cells” - anO(1)-ish lookup returning a bounded local set instead of a full scan. - Radius by ring expansion. Start with P’s cell and its immediate neighbors (one ring). If that yields too few candidates, expand to the next ring. This adapts the search radius to local supply density: dense downtown needs one ring, a sparse suburb expands further. You cap the rings so a supply desert fails fast to the no-pool fallback.
- Directional compatibility filter. For each nearby trip, cheaply reject those heading the wrong way. Compare the trip’s current heading (and the bearing of its next few committed stops) against the bearing P -> D. A trip whose route direction is within, say, a ~60-90 degree cone of the rider’s direction is a plausible pool; one heading opposite is discarded without any routing call. This single geometric test removes the majority of near-but-useless candidates.
- Capacity and constraint pre-filter. Drop trips with no free seat for the party size, and trips whose remaining passengers’ time windows are already so tight that any insertion would violate them (a quick slack check). What survives - near, right-direction, has-a-seat, has-slack - is the ~30-100 set the insertion evaluator actually scores.
Supply index: cell_id -> set(trip_id) # updated from GPS pings
trip_id -> {pos, heading, free_seats, route_bearing,
min_slack} # live trip summary
CANDIDATES(P, D, party):
cells = [cell(P)] + neighbors(cell(P)) # ring 0..r, expand if sparse
near = union(index[c] for c in cells)
out = []
for t in near:
if t.free_seats < party: continue # capacity
if bearing_diff(t.route_bearing, bearing(P,D)) > CONE: continue # direction
if t.min_slack < MIN_REQUIRED_SLACK: continue # time-window slack
out.append(t)
return out # ~30-100 trips, pruned
Why this is right:
- Retrieval is a local cell lookup, not a global scan. The spatial index turns “find nearby trips” into reading a handful of cells, so candidate retrieval stays in the tens-of-milliseconds range regardless of total supply.
- Direction pruning removes the expensive-to-evaluate junk cheaply. A bearing comparison is nearly free and discards cars going the wrong way before any routing lookup, so the insertion evaluator only ever scores plausible pools.
- Adaptive ring expansion matches supply density. Dense areas return instantly; sparse areas widen the net but still bound the work, and a true desert fails fast to fallback instead of hanging.
- The candidate set size is controllable. By tuning cell resolution, ring count, and cone angle, you directly bound how many trips the evaluator scores, which is the knob that keeps per-request latency inside budget as load grows.
The principle: spend a cheap geometric filter (grid + heading + capacity) to shrink the candidate set to a few dozen before spending the expensive routing-based insertion evaluation - the same move that makes the whole system fit its latency budget.
3. Committing the match: atomic seat-claim-and-splice per trip
The job: when the evaluator picks “insert rider R into trip T at positions (i, j),” actually make it so - claim a seat, splice the two stops into T’s ordered itinerary - without two concurrent requests both inserting into the last seat of T, and without the stale evaluation (the car moved since retrieval) producing an infeasible route.
Naive approach: update the trip’s stop list in the matching service
The matching service that won the evaluation directly writes the new stop sequence and decrements the free-seat count in the shared trip store.
Where it breaks:
- Two matchers race for the same seat. Two requests evaluated against trip T concurrently (common at rush hour - several riders near the same busy corridor) both see one free seat, both decide to insert, and both write. Result: an over-capacity car, or one rider’s splice silently overwriting the other’s. This is the oversell bug, now per vehicle.
- The evaluation is stale by commit time. Candidate retrieval and insertion scoring happened a second or two ago against T’s position and route then. By the time the matcher writes, the car has moved and may have taken another passenger, so the positions (i, j) and the time-window feasibility computed earlier may no longer hold. Blindly writing can violate a window or splice at a stale index.
- No single owner of the itinerary. If any matcher can mutate any trip, there is no serialization point; concurrent splices interleave and corrupt the ordered stop list.
Letting stateless matchers mutate trips directly reintroduces the exact race that scarce-inventory systems exist to prevent - just at the granularity of one car’s seats.
Evolved approach: single-owner trip actor, compare-and-commit with re-validation
Make each live trip owned by exactly one writer (a sharded trip/itinerary service, one trip per owner), and make the commit an atomic re-validate-then-splice that rejects stale or conflicting insertions.
- One owner per trip, sharded by trip id. The trip/itinerary service shards live trips across nodes so each trip’s itinerary and seat count live on a single owner. All mutations to trip T - insert, cancel, stop-completed - are serialized through that owner. There is no cross-matcher race because only the owner writes.
- Commit carries the assumptions it was evaluated under. The matcher sends the owner: rider R, proposed positions (i, j), the added-detour it computed, and a version/snapshot token of T’s state it evaluated against (route version, current stop index). The commit is a conditional operation, not a blind write.
- Re-validate inside the critical section. The owner, holding the trip exclusively, re-checks feasibility against current state: is there still a free seat? Is the car still before stop si (positions still valid)? Do all time windows still hold given the car’s actual current position and the latest committed stops? This is a fast local forward-pass, not a re-route. If anything changed enough to break feasibility, the owner rejects the commit and the matcher either retries against the refreshed trip or picks its next-best candidate.
- Atomic claim-and-splice on success. If still feasible, the owner in one indivisible step: decrements free seats by the party size, splices P at i and D at j into the ordered stop list, bumps the trip’s route version, and returns the committed itinerary. Because this runs on the single owner, no interleaving can double-claim a seat or corrupt the sequence.
- Idempotency for retries. Each match attempt carries an idempotency key (request id). A retried commit that already succeeded returns the same result instead of inserting the rider twice.
COMMIT(trip T on its owner, rider R, pos (i,j), seen_version, party):
if T.version != seen_version:
refeasible = revalidate(T.current, R, i, j) # positions may shift
if not refeasible: return REJECT(stale) # matcher retries/next-best
if T.free_seats < party: return REJECT(no_seat)
if window_violation(T.current, insert R@ (i,j)): return REJECT(infeasible)
# atomic on the single owner:
T.free_seats -= party
splice(T.stops, pickup=R.P @ i, dropoff=R.D @ j)
T.version += 1
emit match_committed(T, R, itinerary) # async persist + notify
return OK(itinerary, eta, price)
Why this is right:
- Seat over-assignment is structurally impossible. The free-seat decrement and the splice happen atomically on the one owner of the trip; two requests cannot both claim the last seat because the second sees
free_seatsalready decremented and is rejected. - Stale evaluations are caught, not committed. The version token and in-critical-section re-validation mean an insertion scored against an out-of-date route is re-checked against reality and rejected if it no longer holds, so a moved car never gets an infeasible splice.
- The expensive work stayed outside the lock. Candidate retrieval and insertion scoring (the slow part) happened before the commit; the critical section is a fast re-validate-and-splice on a tiny in-memory itinerary, so holding one trip exclusively for a moment does not bottleneck the system.
- Different trips commit fully in parallel. Because trips are sharded by id to independent owners, thousands of commits to different cars run concurrently; only concurrent attempts on the same trip serialize, which is exactly the contention that must be serialized.
This “single-owner-per-trip, compare-and-commit with re-validation” is the same scarce-inventory serialization pattern, scoped to one vehicle’s seats and one itinerary - put the one unavoidable serialization on the smallest possible in-memory operation, and keep everything expensive outside it.
4. Keeping routing/ETA evaluation cheap at hundreds of calls per request
The job: the insertion evaluator needs travel time and distance between stop pairs, many times per request (every trial placement across every candidate). A live routing engine call that hits the road graph with current traffic is tens of milliseconds - do hundreds per request and you are far over budget. Make these lookups fast and still accurate enough.
Naive approach: call the full routing engine for every leg of every trial
For each candidate trip and each trial (i, j), call the routing/ETA service for each affected leg with live traffic, getting a precise travel time.
Where it breaks:
- Hundreds of synchronous routing calls per request. ~50 candidates, a few trial placements each, three legs per insertion -> hundreds of calls, each tens of ms, serialized within a ~hundreds-of-ms budget. It simply does not fit; the request times out.
- The routing engine becomes the bottleneck. At ~45,000 evaluations/sec peak (from the BoE), a precise-routing call per evaluation would need a routing tier sized for ~45K QPS of expensive graph queries - wildly expensive and the hottest dependency in the system.
- Over-precision for a pruning step. Most trial placements are thrown away (pruned by time windows or out-scored). Paying for an exact, traffic-aware route on placements you immediately discard is wasted compute.
Calling the full engine per leg per trial makes routing the dominant cost and misses the latency target by orders of magnitude.
Evolved approach: tiered estimation - cheap approximate first, precise only to confirm
Use a cheap approximate travel-time estimate for the inner-loop pruning and scoring, and the precise routing engine only for the handful of surviving placements (and the final commit).
- An ETA cache / travel-time matrix. Precompute and cache travel times between cell centroids of the spatial grid (the same grid from deep dive 2), refreshed periodically from live traffic. “Travel time from near A to near B” becomes a cache lookup keyed by
(cell(A), cell(B))- microseconds, not a graph query. For a city gridded into cells, this is a bounded matrix that fits in memory and is updated every minute or two as traffic shifts. - Cheap estimate drives the inner loop. All the
O(k^2)trial scoring and time-window pruning uses the cached cell-to-cell estimate. It is approximate (cell granularity, slightly stale traffic) but more than good enough to rank placements and prune infeasible ones. The entire insertion evaluation across all candidates runs on in-memory lookups. - Precise routing only for the finalists. Once the evaluator has the top one or two feasible insertions, call the real routing engine for just those to get exact ETAs and confirm feasibility with live traffic. That is a handful of precise calls per request, not hundreds. The precise call is also what produces the ETA shown to the rider and driver.
- Batch and cache aggressively. Routing calls for a single request’s finalists can be batched into one many-to-many matrix request. Precise results are themselves cached briefly, so repeated requests in the same corridor reuse them. The routing tier is sized for the finalist rate (a few precise calls per request), not the evaluation rate.
Inner loop (pruning + scoring): travel_est(A,B) = eta_matrix[cell(A)][cell(B)]
# in-memory, microseconds, approximate
Finalists only (top 1-2 inserts): travel_precise = routing_engine(A,B, live)
# tens of ms, exact, few per request
ETA matrix refresh: background job recomputes cell-to-cell times every ~1-2 min
from live traffic feeds -> keeps estimates fresh enough.
Why this is right:
- The inner loop costs in-memory lookups, not graph queries. The hundreds of per-request evaluations hit a cached matrix, so they collapse from hundreds of ms of routing calls to sub-millisecond lookups - the single change that makes the whole matcher fit its budget.
- Precise routing is spent only where it matters. You pay for exact, traffic-aware ETAs on the one or two placements you will actually use and show the user, not on the dozens you prune. The routing tier is sized for finalist volume, which is ~request rate, not evaluation rate.
- Accuracy where it counts. Pruning tolerates approximation (you only need relative ranking and a feasibility bound); the committed ETA uses the precise engine, so the rider gets a trustworthy number even though the search used estimates.
- It degrades gracefully. If the routing engine is slow or down, the matcher can commit on the cached estimate with a wider feasibility margin rather than fail - the fallback keeps dispatch alive.
The principle: separate the cheap approximate pass that does the bulk search from the expensive precise pass that confirms the winner - so the costly dependency (real routing) is called a few times per request instead of a few hundred, and the latency budget survives.
API Design & Data Schema
External APIs
REST/HTTPS for request/response; a persistent stream (WebSocket/gRPC) for live driver pings and route pushes.
POST /v1/rides/pool # rider requests a pooled ride
headers: { Idempotency-Key: "req_usr88_1730000000" }
body: {
"rider_id":"usr88",
"pickup": { "lat":12.9719, "lng":77.6412 },
"dropoff": { "lat":12.9352, "lng":77.6245 },
"party_size":2,
"max_wait_sec":300 # rider's pickup-by tolerance
}
-> 200 {
"match_id":"mt_41c9",
"status":"MATCHED",
"trip_id":"trip_7781",
"driver_id":"drv_204",
"pickup_eta_sec":180,
"seats":["B","C"],
"quoted_fare_paise":18200,
"shared_with":1 # one other passenger already aboard
}
-> 200 (no pool) {
"match_id":"mt_41ca", "status":"NEW_TRIP", "trip_id":"trip_9002",
"driver_id":"drv_511", "pickup_eta_sec":150, ... } # solo fallback
-> 200 (none) { "status":"NO_SUPPLY", "retry_after_sec":20 }
GET /v1/rides/{match_id} # poll current ETA/route/status
-> 200 { "status":"EN_ROUTE_TO_PICKUP", "pickup_eta_sec":90,
"trip_id":"trip_7781", "position":{...} }
DELETE /v1/rides/{match_id} # rider cancels -> triggers trip re-optimization
-> 200 { "status":"CANCELLED", "refund_paise":0 }
# Driver-facing (persistent stream)
WS /v1/driver/stream
up: { "driver_id":"drv_204","lat":...,"lng":...,"heading":84,
"occupancy":1,"free_seats":2,"ts":... } # GPS ping ~every 4s
down: { "type":"ROUTE_UPDATE","trip_id":"trip_7781",
"stops":[ {"seq":0,"kind":"DROPOFF","rider":"usr40","lat":...,"eta":...},
{"seq":1,"kind":"PICKUP","rider":"usr88","lat":...,"eta":...},
{"seq":2,"kind":"DROPOFF","rider":"usr88","lat":...,"eta":...} ] }
Data model and store choices
1. Live supply / geospatial index - in-memory spatial store (Redis with geo, or a sharded in-memory grid service). Eventually consistent (a ping or two stale is fine), very high write rate, queried by location. Keyed by spatial cell.
geo:cell:{cell_id} -> set(trip_id) # trips currently in cell
trip:live:{trip_id} -> { # live trip summary (hot)
driver_id, pos{lat,lng}, heading, route_bearing,
free_seats, min_slack_sec, version }
# updated on every GPS ping; read by candidate retrieval.
2. Live itinerary state - in-memory, single-owner per trip (sharded trip/itinerary service). Strongly consistent per trip: the ordered stop list and seat count. This is the commit point (deep dive 3). Reconstructable from the event log.
itinerary:{trip_id} -> {
driver_id, version,
free_seats,
stops: [ { seq, kind:PICKUP|DROPOFF, rider_id, lat, lng,
planned_eta, window_latest } ], # ordered; fixed except splices
passengers: [ { rider_id, pickup_by, max_trip_sec, seats } ] }
Shard key: trip_id -> exactly one owner. Single writer per trip.
3. Trips / match history - sharded SQL (Postgres), source of truth for a completed/committed match. Relational: a trip is a transactional entity with passengers, stops, fares, and metrics that need ACID and joins for billing, disputes, and analytics. Shard by trip_id.
CREATE TABLE trip (
trip_id BIGINT PRIMARY KEY,
driver_id BIGINT NOT NULL,
status VARCHAR(16) NOT NULL, -- FORMING|ACTIVE|COMPLETED|CANCELLED
started_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
total_dist_m BIGINT,
pool_size SMALLINT -- peak passengers carried together
);
CREATE INDEX ON trip (driver_id, started_at);
CREATE TABLE trip_leg ( -- one row per rider on a trip
trip_id BIGINT REFERENCES trip(trip_id),
rider_id BIGINT NOT NULL,
seq_pickup SMALLINT, seq_dropoff SMALLINT, -- positions in itinerary
pickup_eta TIMESTAMPTZ, dropoff_eta TIMESTAMPTZ,
solo_dist_m BIGINT, shared_dist_m BIGINT, -- for detour metric + pricing
detour_sec INT,
fare_paise BIGINT,
status VARCHAR(16), -- MATCHED|PICKED_UP|DROPPED|CANCELLED
idempotency_key VARCHAR(64) UNIQUE, -- dedupe match retries
PRIMARY KEY (trip_id, rider_id)
);
CREATE INDEX ON trip_leg (rider_id); -- "my rides"
4. Event stream - append-only (Kafka). Every match, splice, cancel, stop-completed, and GPS summary is an event. Durable truth to rebuild in-memory itineraries after a crash, and the feed for pricing, re-optimization, and analytics.
event: { seq, trip_id, type:MATCH|SPLICE|CANCEL|STOP_DONE,
rider_id, itinerary_version, ts } # replay -> rebuild live trip
5. ETA / travel-time matrix - in-memory cache, eventually consistent. Cell-to-cell travel times refreshed from live traffic every 1-2 minutes (deep dive 4). Serves the inner-loop estimate.
6. Reference data - read-mostly SQL + edge cache. Static map tiles, cell definitions, pricing rules, surge zones. Rarely changes, heavily cached.
Why this split: the contended write (seat-claim + splice) demands in-memory strong consistency per trip, so it lives in a single-owner itinerary service, not SQL. The supply index demands high-write, location-queried, stale-tolerant storage, so it lives in an in-memory geo index. The durable trip (money, metrics, passengers) demands ACID and rich queries, so it lives in sharded SQL. The ETA lookups demand microsecond approximate reads, so they live in a cached matrix. One database could not serve a 37K-writes/sec geo index, a per-trip linearizable commit, and a TB-scale analytical store at once - match each store to its access pattern.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. GPS ingestion into the geospatial index (~37K writes/sec) - a constant firehose. Every driver updates its cell membership continuously; naive per-ping index rewrites thrash the structure. Fix: ingest through a buffered stream and update the in-memory index in place; only move a trip between cells when it actually crosses a cell boundary (most pings keep the same cell, so they are cheap position updates, not index churn). Shard the geo index by region so writes spread across nodes. The index is reconstructable from the ping stream, so it does not need its own durability.
2. Candidate retrieval blowing up in dense zones. A downtown cell at rush hour may hold thousands of trips, so even a cell lookup returns too many to evaluate. Fix: finer cell resolution in dense areas (adaptive grid) so each cell holds a bounded set, and cap the candidate count after the direction + capacity filter - take the N nearest/most-aligned and evaluate those. Over-supply is pruned geometrically before the expensive evaluator ever runs.
3. Routing/ETA evaluation cost (the real compute bottleneck). Hundreds of travel-time lookups per request at ~150 req/sec peak is the dominant load. Fix: the tiered estimation of deep dive 4 - cached cell-to-cell matrix for the inner loop, precise routing only for the one or two finalists. This collapses hundreds of expensive calls per request to in-memory lookups plus a few precise calls, sizing the routing tier for request rate, not evaluation rate.
4. The per-trip commit hot spot (a popular corridor’s cars). Several riders near the same busy car contend to insert into it. Fix: single-owner-per-trip with compare-and-commit (deep dive 3). Contention is only ever between attempts on the same trip, which serialize correctly and cheaply; different trips (the overwhelming majority of concurrent commits) run fully in parallel because they are sharded to different owners. A rejected stale commit retries against its next-best candidate.
5. Stale evaluation from moving cars. The car moved between candidate retrieval and commit, so the scored insertion may be infeasible. Fix: version token + in-critical-section re-validation on commit - a fast forward-pass that rejects placements the car’s movement invalidated, so a stale score never becomes a bad route.
6. Hot spatial cells and hot regions (airport, stadium letting out). Supply and demand both spike in one place; one geo shard and the trips there get hammered. Fix: shard the geo index and the trip owners by region with sub-sharding of hot cells; add surge-aware admission so demand that outstrips supply in a hot zone is told NO_SUPPLY/retry quickly instead of making every matcher scan a melting cell. The matcher degrades to solo/queue rather than spin.
7. Global optimality loss from greedy insertion. Per-request greedy packing is worse than an offline optimum - cars fill less efficiently than they theoretically could. Fix: short batching windows and periodic re-optimization. Instead of matching each request the instant it lands, collect requests over a ~1-2s window and match the small batch jointly (a bounded local assignment across the batch and nearby trips), which packs better than strict one-at-a-time greedy while still bounded in latency. A background re-optimizer can also re-pair not-yet-picked-up riders when a better pooling appears. This reclaims quality without abandoning the latency budget.
8. Routing engine as a dependency SPOF. If precise routing is down, finalists cannot be confirmed. Fix: fall back to the cached estimate with a wider feasibility margin so matching continues (slightly less precise ETAs) rather than failing, and run the routing engine behind a circuit breaker so a slow engine does not stall every request.
9. Durability and recovery of live itineraries. If a trip owner node dies, its in-progress itineraries must not be lost - riders are physically in those cars.
Fix: replicate each trip-owner shard (primary + sync replica) and treat the append-only event log as the source of truth; on failover the replica rebuilds itinerary + seat counts from snapshot + log and resumes. A confirmed match and its committed stops are in the durable log before the rider is told “matched,” so no committed passenger is lost. Correctness (never drop or double-book a seated rider) over availability on the commit path.
10. Storage growth (~1.6 TB/year of trips + logs). Kept for billing, disputes, pricing calibration. Fix: partition trip tables by month and archive completed trips to cold storage; roll the event log to object storage after trip completion; keep only live and recent trips hot. Snapshots bound replay time on recovery.
Shard keys, stated plainly: the geospatial supply index shards by spatial cell/region (the unit of location queries), with finer resolution and sub-sharding for hot cells. Live itineraries and their seat inventory shard by trip_id - the unit of contention, ordering, and consistency, so one car’s seats have exactly one writer. Durable trips shard by trip_id too, so a trip’s record and legs sit together. The ETA matrix is keyed by cell pair. Matching service and dispatch are stateless (scale for load only). Never shard a single trip’s itinerary internally - one trip is one writer by design, and that single-writer property is exactly what makes seat over-assignment impossible.
Wrap-Up
The trade-offs that define this design:
- Greedy per-request insertion instead of global optimization. Optimal multi-vehicle pooling is NP-hard and far too slow for live dispatch, so we fix each trip’s committed route and cheapest-insert the new rider’s two stops, pruned by hard time windows. We knowingly trade a few percent of packing efficiency for a bounded, seconds-scale answer - and claw some of it back with short batching windows and background re-optimization.
- Cheap approximate search, precise confirmation. The inner loop that scores hundreds of trial insertions runs on a cached cell-to-cell ETA matrix (microseconds, approximate); the real routing engine is called only for the one or two finalists and the committed ETA. We trade inner-loop precision for a latency budget that actually fits, and keep accuracy exactly where the rider sees it.
- Geometry before computation. A spatial index plus a direction-and-capacity filter shrinks tens of thousands of trips to a few dozen candidates with near-free geometric tests, so the expensive insertion evaluator only ever scores plausible pools. We trade a small risk of missing a far-but-good match for a retrieval step that stays fast as the city grows.
- Strong consistency only on the per-trip seat commit; everything else async or eventually consistent. The one linearizable operation is the atomic seat-claim-and-splice on a single-owner trip, re-validated against the car’s current state. Supply location, ETAs, persistence, and pricing all live outside that critical section. We trade a globally simple model for a small, fast, correct core surrounded by eventually-consistent scale.
- Correctness over availability on the commit path. A stale or conflicting insertion is rejected rather than risk double-booking a seat or an infeasible route; a briefly stuck trip is recoverable, a rider physically double-assigned to a seat is not.
One-line summary: a live geospatial index narrows a rider’s request to a few dozen nearby, right-direction, has-a-seat trips, a greedy cheapest-insertion heuristic splices the rider’s pickup and drop-off into each candidate’s fixed itinerary - scoring on a cached ETA matrix, pruning hard on per-passenger time windows, and confirming only the finalists with precise routing - then an atomic seat-claim-and-splice on the single owner of the winning trip commits the match in milliseconds, so thousands of in-progress pools absorb new riders at minimum total detour, in seconds, never over-capacity, with durable trips in sharded SQL and an append-only event log as the source of truth for scale, recovery, and re-optimization.
Comments