Marketplace, Dispatch, and Logistics System Design Questions
Designing two-sided marketplaces and real-time operational platforms end to end, where the domain shapes the architecture: rider/driver and order/courier matching and dispatch (batched vs greedy assignment, single-assignment guarantees, re-matching, pooling), order, booking and inventory flows (holds, double-booking prevention, quote-to-checkout price honoring), surge and dynamic pricing systems (demand/supply signals, damping, caps and fairness controls, pricing rules), ETA and routing services (road graphs, time-dependent weights, map-matching, traffic fusion, degraded modes), proximity-driven matching over moving supply (geo-partitioned matchers, hotspot rebalancing, boundary effects), and real-time location tracking. Covers the canonical ride-hailing, food/parcel delivery, and booking marketplace case studies and the consistency, latency, and scale challenges they share. Generic building blocks used by these designs (caching, rate limiting, sagas, stream-processing internals, spatial index primitives, observability, deployment) are covered by their own topics.
Compare spatial partitioning strategies for distributed matching: fixed grid bucketing, geohash sharding, and Voronoi (dynamic) partitions. For each approach discuss load balancing, handling mobile entities crossing boundaries, rebalancing cost, and how it affects match quality and latency in peak demand.
Sample Answer
Direct answer
Fixed grids are simple and cheap to route but balance badly, because a downtown square and a suburban square carry very different load. Geohash sharding keeps the grid's cheap lookup and adds a hierarchy, so a hot cell can be split into finer cells. Voronoi partitions (each shard owns the area nearest to its "seed" point, with seeds placed by demand) balance best but are the most expensive to change and route. My recommendation for peak-demand matching: use a hierarchical cell system (geohash, or S2 or H3) as the unit of data, and a dynamic, load-aware map from cells to shards as the unit of ownership. That gives most of Voronoi's balance, keeps rebalancing to moving a handful of cells, and keeps point-to-shard routing a table lookup.
Terms
- Shard: one instance, a single server or process, that owns and serves a subset of the data or cells.
- Fixed grid bucketing: divide the map into equal squares (say 1 km), each assigned to a shard.
- Geohash sharding: geohash encodes a location as a string where each extra character subdivides the cell into 32; shards own prefixes. Precision 6 cells are about 1.2 km by 0.6 km and precision 7 about 150 m by 150 m at the equator, and moving away from the equator toward the poles, a cell's east-west width shrinks while its north-south height stays about the same (lines of longitude converge toward the poles).
- S2 and H3: other hierarchical cell systems. S2 (from Google) uses cells on a cube projected onto the sphere, ordered along a space-filling curve (a single continuous path that visits every cell, so cells near each other on the path are usually near each other on the sphere, letting a 1-D sort stand in for 2-D locality); H3 (from Uber) uses hexagons, whose six neighbours are all the same distance away.
- Voronoi partition: given seed points, each point on the map belongs to its nearest seed. Placing more seeds where demand is dense gives smaller cells there.
The comparison
| Criterion | Fixed grid | Geohash sharding | Voronoi (dynamic) |
|---|---|---|---|
| Point-to-shard routing | Arithmetic: floor(x / size) | String prefix lookup | Nearest-seed query (needs its own small index) |
| Load balancing | Poor: equal area, unequal load; a hot square overloads one shard | Good: split a hot prefix into children and spread them | Best: seeds placed so each cell carries similar load |
| Mobile entities crossing borders | Crossing rate set by square size | Same per cell; hierarchy lets you merge quiet cells to cut crossings | Irregular borders; placeable in sparse areas, but they move when seeds move |
| Rebalancing cost | Only by reassigning whole squares | Split or move a few cells; neighbours unaffected | Moving one seed reshapes several neighbouring cells, so many entities change owner at once |
| Boundary effects on match quality | Borders cut through dense areas arbitrarily | Same, plus neighbouring cells can have very different prefixes (for example across the equator or the prime meridian), so "neighbours" must be computed, not inferred from prefixes | Borders can be placed through low-density areas, fewest misses at peak |
| Peak latency | Hot shard queues; p99 (99th-percentile) latency spikes | Good once the split has happened; lag between hotspot and split | Good if seeds adapt quickly, but recomputing seeds is itself a batch job |
Crossing rate, with numbers
For entities moving in random directions at speed v, the fraction of a cell's entities crossing its border per second is v x P / (pi x A), where P is the perimeter and A the area. Intuition: averaged over a uniformly random direction, an entity's effective outward speed at the boundary is v/pi (the average of the outward component of a random direction), so crossings per second equal that outward speed times the perimeter, divided by the area to convert a total crossing count into the fraction of the cell's own population crossing. For a square of side L that is 4v / (pi L).
- Drivers at 10 m/s in 1 km squares: 4 x 10 / (3.1416 x 1,000) = 0.0127/s, so each driver changes cell about every 79 s.
- In 2 km squares: about every 157 s.
- In 150 m cells: about every 12 s.
Each crossing costs an ownership handoff between shards if the two cells are on different shards. This is the argument for keeping cells small (for balance) but assigning contiguous groups of cells to the same shard, so most crossings are internal to a shard and cost only an in-memory move.
How each behaves at peak
Fixed grid. At a stadium let-out, one square gets ten times its usual searches and every rider there competes for the same shard's CPU. The only remedy is moving the whole square, which moves the hotspot. Fine for a single small city with even demand; poor anywhere with sharp hotspots.
Geohash. The stadium prefix is split into 32 children spread across shards, and quiet children can be re-merged later. Two costs: a search near the stadium now fans out across more shards (boundary effect), and the split lags the hotspot by the detection window. Pre-splitting known venues before scheduled events removes most of that lag.
Voronoi. Seeds recomputed (for example by clustering recent demand, grouping nearby recent pickup requests so each group's centre becomes a new seed) give every shard similar load and place borders in quiet areas, which is the best match quality at peak. But a recomputation moves borders city-wide, so thousands of drivers change owner at once, the change must be coordinated (every router, the service in front of matching that directs each request to the shard currently responsible for that area, needs the new seed set atomically), and point-to-shard routing needs a nearest-seed lookup. Recomputing during the peak is exactly when you can least afford that disruption.
Why the hybrid wins
Treat cells as fixed, small, hierarchical units (geohash precision 7, or H3 resolution chosen for similar size), and keep a separate cell-to-shard assignment table:
- Balance: assign cells to shards by measured load, in contiguous groups; this is effectively a Voronoi-like grouping drawn with cell boundaries.
- Rebalancing: move a few cells, not the whole map; each move is a small, fenced handoff: the old owner's writes are tagged with a version number that the new owner's takeover invalidates, so a de-synced old owner cannot act on a cell it no longer owns.
- Routing: compute the cell arithmetically, then one table lookup.
- Borders: choose group edges along low-density cells, which recovers most of Voronoi's boundary advantage.
What would change my mind: a small, single-city deployment with flat demand, where a fixed grid is simpler and good enough; or a world where borders must follow physical or legal lines (a river, a city limit), where hand-drawn polygons over cells are the practical answer.
Pitfalls
- Choosing by elegance rather than by measured load skew; flat demand does not need Voronoi.
- Assuming geohash prefix similarity means adjacency.
- Recomputing a global partition during peak.
- Balancing by drivers only: searches, not updates, often dominate CPU during a surge.
Design the matching logic for pooled/shared rides (ride-pooling) where one driver can serve multiple riders with overlapping routes. Describe constraints (max detour, ETA increase), a scoring function, and how to quickly generate feasible multi-stop itineraries at scale. How does this change the candidate retrieval and state model compared to single-rider matching?
Sample Answer
Direct answer
Match a pooled request by trying to insert the new rider's pickup and drop-off into each candidate vehicle's existing ordered list of stops, keeping only insertions that respect every rider's detour cap, pickup-wait limit and the seat count, and choosing the cheapest under a cost that charges both the extra vehicle time and the extra time imposed on riders already aboard. The big change from single-rider matching is that a vehicle is no longer "free or busy": it is a planned itinerary with spare seats. Retrieval must find vehicles whose future route passes near the rider, and the thing you lock when committing is the itinerary's version, not an availability flag.
Terms used below
- Itinerary: the ordered list of stops a vehicle will visit, for example pickup A, pickup B, drop B, drop A.
- Detour: how much longer a rider's trip takes because of pooling, compared with driving straight from their pickup to their drop-off.
- ETA (estimated time of arrival).
- Slack: how many minutes a stop can be delayed before some promise later in the route breaks.
- Compare-and-set (CAS): update a record only if its version is still the one you read.
Constraints (hard: violating any one rejects the insertion)
| Constraint | Example value | Protects |
|---|---|---|
| Seats | onboard riders ≤ 4 at every point of the route | capacity |
| Precedence | each pickup before its own drop-off | sanity |
| Max detour per rider | ride time ≤ 1.5 × direct time, and at most +10 min | every rider, including the new one |
| Max pickup wait for the new rider | ≤ 10 min | the new rider |
| Max ETA increase for riders already matched | promised drop-off time + 4 min at most | people who already said yes to a quote |
Scoring function
For a candidate vehicle v and new rider r (lower is better):
cost(v,r)=ΔTv+αj∈Rv∑Δtj+βwr- ΔTv: extra minutes the vehicle drives with the new rider inserted.
- Δtj: extra minutes imposed on each rider j already assigned to the vehicle.
- wr: the new rider's wait until pickup.
- α=1.5 and β=1 as starting values: a minute taken from someone who already accepted a quote costs more trust than a minute of vehicle time. These are tuned from cancellation and rating data, not guessed once.
The pooled match is offered only if its cost beats the best solo dispatch by a margin; otherwise the rider gets a dedicated car and the pooled product does not degrade into a slower solo ride.
Worked comparison. Vehicle 1 already carries rider A; its route is 20 min long and becomes 32 min with the new rider inserted, A arrives 3 min later, and the new rider waits 5 min. Vehicle 2 is empty, 9 min away, and the new rider's trip is 18 min.
cost1cost2=12+1.5×3+1×5=21.5=(9+18)+0+1×9=36The wait term deliberately overlaps in time with part of ΔTv rather than adding brand-new minutes: for vehicle 2, the same 9 minutes the vehicle spends driving to the new rider is also that rider's whole wait, so the formula counts it twice on purpose, once as fleet cost (ΔTv, what the extra driving costs the platform) and once as rider experience (wr, how long they personally stand around before pickup). For vehicle 1 the 5-minute wait is likewise part of the 12-minute ΔTv (the slice of the detour spent reaching the new pickup before continuing on to serve A), not 5 minutes on top of it. Both terms stay in the formula because a design that only minimised fleet minutes could still leave the new rider waiting an unacceptably long time for a cheap detour; the wait term is what stops that.
Vehicle 1 wins, as long as A's extra 3 minutes are inside A's promise (they are, the cap is 4) and the new rider's ride stays within 1.5 × direct.
Generating feasible itineraries quickly
- Candidate retrieval (the part that changes most). Index every pooled vehicle by the grid cells its planned route crosses in the next 15 min, not only its current cell. Query cells within about 1.5 km of the pickup, keep vehicles with a free seat, and keep the top 30 by a cheap lower bound: a number fast to compute that is guaranteed no greater than the true cost, here straight-line distance from the route to the pickup and drop-off (real drive time can only be equal or longer, so ranking by it never discards a candidate that could have been genuinely cheapest).
- Insertion enumeration. A route with k stops has (k+1)(k+2)/2 ways to place a pickup and a later drop-off. For k=4 that is 15.
- Constant-time feasibility. Precompute for each stop its planned arrival time and its slack (the smallest gap between planned arrival and latest allowed arrival over that stop and everything after it). An insertion that delays stop i by d minutes is feasible downstream only if d is at most the slack at i, so each check is a comparison instead of re-simulating the route. The single winning route is then re-simulated exactly before commit.
- Greedy insertion, then local search. Collect requests in a 2 s window, assign them greedily (hardest-to-serve first: long trips, remote pickups), then spend the rest of the time budget on local moves: move one rider to another vehicle, or swap two riders between vehicles, keeping any move that lowers total cost. Only riders not yet picked up can move.
Scale arithmetic (assumed: 3,000 pooled requests/s across all cities at peak, 30 candidates each, 4 stops per route):
| Quantity | Calculation | Per second |
|---|---|---|
| Insertion feasibility checks | 3,000 × 30 × 15 | 1.35 million |
| New travel-time legs needed | 3,000 × 30 × 2 × (4 + 1) | 900,000 |
Where the 2(k+1) comes from: inserting one new stop between two existing consecutive stops replaces the single leg between them with two fresh legs (previous stop to the new stop, new stop to the next one). With k existing stops there are k+1 places to insert it, so pricing every insertion position for one new stop costs 2(k+1) travel-time lookups. That is a smaller number than the (k+1)(k+2)/2 combinations from step 2: this row estimates the dominant lookup cost (the pickup's insertion, evaluated at every position), not every full pickup-and-drop-off combination, since the drop-off's legs are cheap to derive once the pickup's position is fixed.
1.35 million slack comparisons per second is cheap arithmetic spread over a few machines. The 900,000 travel-time lookups are the real bottleneck, which is why production systems precompute cell-to-cell travel-time tables or use a routing engine built on contraction hierarchies (a road-graph preprocessing technique that makes each shortest-path query very fast), and cache per request. Matching runs partitioned by city, so each shard (one independent partition of the matching workload, here one city's worth, running on its own machines) sees a fraction of this.
How candidate retrieval and the state model change
| Aspect | Single-rider matching | Pooled matching |
|---|---|---|
| Vehicle state | idle, en_route, on_trip | itinerary (ordered stops), seats used, promised times per rider, version |
| Who is a candidate | idle vehicles near the pickup | any vehicle with a free seat whose planned route passes near pickup and drop-off |
| Spatial index key | current position | current position plus cells along the planned route |
| Cost per candidate | one ETA lookup | up to (k+1)(k+2)/2 insertions, each with new legs |
| Commit | CAS on status = idle | CAS on itinerary version: two requests in one window may pick the same vehicle, the loser re-evaluates |
| A cancellation | frees the vehicle | re-optimises the itinerary and changes other riders' ETAs |
flowchart LR
REQ[Pooled request] --> RET[Route-cell retrieval]
RET --> ENUM[Enumerate insertions]
ENUM --> CHK[Slack check]
CHK --> SCORE[Score and pick]
SCORE --> CAS[CAS on itinerary version]
CAS -->|conflict| ENUM
CAS -->|ok| NOTIFY[Update all riders' ETAs]
Trade-offs and pitfalls
- Detour cap: a larger cap creates more matches and lower fares but a worse ride. Commit to 1.5x with an absolute ceiling, then tune per market by measuring cancellations and repeat usage.
- Pitfall: retrieving by current position only. It misses the vehicle 3 km away whose route passes the rider's door in 4 minutes, which is often the best pooled match.
- Pitfall: scoring only vehicle time. It keeps adding riders to the same car until the first rider's trip doubles; the existing-rider term and the promise cap prevent that.
- Pitfall: locking a boolean "available". Two inserts into one itinerary both succeed and produce an impossible route; version the itinerary.
- Depth beyond most interviews: holding a seat empty because a better match is predicted to appear, and learning the weights with offline replay of past request streams.
You're asked to choose between eventual and strong consistency for the flow: create-order -> payment -> driver-assignment. Discuss trade-offs for choosing each, and propose a hybrid design that ensures payment correctness while minimizing user-visible anomalies during assignment (e.g., double-assignments or incorrect status shown to users).
Sample Answer
Direct answer
Do not pick one consistency model for the whole flow. Use strong consistency where a wrong answer costs money or a physical promise: the order's state machine, the payment record, and the "which driver holds this order" record. Use eventual consistency for everything users merely look at: status screens, maps, notifications, analytics. Stitch the steps together as a saga (a sequence of local transactions, each with a compensating action if a later step fails), and make every status update carry a version number so a client never shows an older state after a newer one.
Trade-offs for each choice
Strong consistency means every read sees the latest committed write (for a single record, this is called linearizable). Eventual consistency means replicas may briefly disagree but converge if writes stop.
| Step | If strongly consistent | If eventually consistent |
|---|---|---|
| Create order | one row insert, cheap either way | risk of duplicate orders on retry unless keyed by an idempotency key |
| Payment | correct by construction; latency of one local transaction plus the payment provider call | double charges, or a charge with no order, under retries and failovers: unacceptable |
| Driver assignment | no double assignment; each assignment is a conditional write on the driver record | two matchers can assign the same driver; the user sees "driver assigned" then "finding another driver" |
| Status shown to users | every screen read hits the primary (the one database replica that accepts writes and always holds the latest data): expensive at millions of polls per minute | cheap, cacheable, may lag by a second or two |
Doing the whole flow strongly (one distributed transaction across order, payment and dispatch services) couples their availability: if any is down, no one can order. Doing it all eventually gets payments wrong. Hence the hybrid.
Hybrid design
flowchart LR
A[Create order: CREATED] --> B[Authorize payment: hold funds]
B -->|approved| C[PAYMENT_AUTHORIZED]
B -->|declined| X[FAILED, nothing to undo]
C --> D[Assign driver: CAS on driver record]
D -->|driver accepts| E[DRIVER_ASSIGNED]
D -->|no driver in 5 min| V[Void authorization, CANCELLED]
E --> F[Trip completed: capture payment]
- Create order in the order database with a client-supplied idempotency key (a unique id per checkout attempt, so a retried request returns the same order instead of creating a second). State CREATED, version 1.
- Authorize the payment through the PSP (payment service provider, the company that talks to card networks) with the order id as the provider's idempotency key. Authorization places a hold on the rider's funds without moving money; capture happens later. The payment result and the order's state transition are written in one local transaction, and an outbox row (an event stored in the same transaction, published afterwards) announces PAYMENT_AUTHORIZED. This avoids "payment recorded but event lost".
- Assign a driver only for orders in PAYMENT_AUTHORIZED. Dispatch runs as many independent matchers, each owning one geographic cell and periodically collecting a short batch of nearby requests to assign together rather than one at a time. The assignment is a compare-and-set (CAS) on the driver's record ("set to OFFERED for order o only if AVAILABLE and version v": update the record only if it still matches what was last read), so two matchers cannot both win. The order moves to DRIVER_ASSIGNED only after the driver accepts.
- Capture the payment on trip completion (for the final fare), or void the authorization (cancel the hold and release the funds back to the rider, without ever moving money) if no driver is found or the rider cancels before pickup. Void and capture are the saga's compensation and completion steps; both are idempotent by order id.
- Status to users flows from the order's events into a read model (a query-optimised copy, such as a cache or a push channel, a live connection like a WebSocket that pushes updates to the client instead of the client repeatedly asking) that is eventually consistent. Each status carries the order version; the client drops any update with a version lower than what it already shows.
Worked example: an anomaly and how the design handles it
Two matchers in adjacent cells both pick driver d9 for orders o1 and o2 within the same second.
- Matcher 1:
CAS d9: AVAILABLE v12 to OFFERED(o1)succeeds, d9 is now v13. - Matcher 2:
CAS d9: AVAILABLE v12 to OFFERED(o2)fails, since the version is 13. Matcher 2 re-queues o2 into its next batch, about 2 seconds later. - Rider o2 never saw "driver assigned", because the order only moves to DRIVER_ASSIGNED after a successful CAS plus driver accept. The only visible effect is a slightly longer "finding your driver".
Now the status-lag case: o1's status events are version 3 (PAYMENT_AUTHORIZED) and version 4 (DRIVER_ASSIGNED). If the push channel delivers 4 then 3, the client ignores 3, so the screen never flips back from "Driver on the way" to "Finding a driver".
Pitfalls
- Charging before assignment is certain: authorize, do not capture, until the trip happens; otherwise every "no driver found" becomes a refund, which is slower for the rider and costs fees.
- Authorizations expire: a hold does not last forever (the exact window depends on the card network and provider), so long scheduled bookings need re-authorization logic.
- Blocking dispatch on the payment provider: if the PSP is slow, orders queue. For trusted riders, one option is to authorize in parallel with matching and cancel the offer if authorization fails; it trades a small chance of a wasted driver trip for lower wait.
- Showing optimistic status: saying "driver assigned" when the offer was only sent (not accepted) is the most common source of user-visible reversals.
Design a multi-region ride-matching architecture for global service: support active-active across 3 regions, preserve low-latency matching, and offer cross-region failover. Discuss data partitioning, leader election for assignments, conflict resolution if same driver appears in two regions, and expected replication strategy for indexes and metadata.
Sample Answer
Direct answer
Matching is local: a rider in Paris is never matched to a driver in Tokyo. So "active-active across 3 regions" should mean every region serves traffic, and every city is homed in exactly one region at a time, not that one city is matched simultaneously in several regions. Each region runs the full matching stack for its cities with in-region consensus for assignments; a global directory, changed only through fenced epochs, says which region owns each city and each driver. Location indexes are never replicated across regions (they rebuild from driver pings in seconds); trip and account metadata replicates asynchronously to a designated standby region. That keeps matching latency at in-region speed, makes "the same driver in two regions" a directory conflict with one defined winner, and makes failover a controlled re-homing of cities.
Terms
- Active-active: all regions take production traffic, as opposed to one active and others idle.
- Leader election: choosing one node to be the single decision-maker for some data, typically with a consensus protocol such as Raft (a protocol where a majority of replicas must agree before a decision counts).
- Lease and epoch: a leader's authority expires unless renewed (lease), and each new leader gets a higher number (epoch) that is attached to its writes so an old leader's writes can be rejected (fencing).
- RPO / RTO: recovery point objective (how much recent data you may lose) and recovery time objective (how long recovery may take).
Requirements I am designing to
- Matching p99 (99th-percentile) latency in the low tens of milliseconds, measured server-side.
- Survive the loss of a whole region with city traffic back within minutes.
- No driver ever holding two concurrent trips.
Why cross-region synchronous replication is ruled out
Light in fibre travels at about 200,000 km/s. For regions 6,000 km apart, one way takes at least 6,000 / 200,000 = 30 ms, so a round trip is at least 60 ms before any processing. A synchronous cross-region write on every assignment would by itself exceed a low-tens-of-milliseconds budget. So: synchronous within a region (replicas in three availability zones, which are separate data centres in the same metro, so that a majority, two of three, can keep agreeing even if one zone is lost), asynchronous across regions.
Architecture
flowchart TB
DIR[Global directory: city and driver home, epochs]
subgraph RA[Region A]
MA[Matching for its cities] --> SA[Trip and driver status, Raft in 3 zones]
end
subgraph RB[Region B]
MB[Matching for its cities] --> SB[Trip and driver status, Raft in 3 zones]
end
DIR --> MA
DIR --> MB
SA -. async replication .-> SB
SB -. async replication .-> SA
Data partitioning and replication
| Data | Owner | Replicated how | Why |
|---|---|---|---|
| Live location index | Home region of the city | Not replicated across regions | Rebuilt from driver pings within one update interval after failover |
| Driver status and in-flight trips | Home region, Raft across 3 zones | Async to one standby region (RPO of seconds) | Must survive a zone loss synchronously; region loss accepts seconds of loss, reconciled from the driver and rider apps |
| Accounts, payment methods, pricing config | Global | Async to all regions | Read-mostly, tolerate seconds of staleness |
| City and driver home assignments | Global directory (small, strongly consistent, can tolerate slower writes) | Consensus spanning regions | Rarely written; must never disagree |
The global directory is the only data that uses cross-region consensus, and it is written only when a city or driver changes home, never per match.
Leader election for assignments
Within a region, each city (or each geographic shard of a large city) has one assignment leader elected by Raft, holding a lease with an epoch. Every assignment writes driver status with a compare-and-set that includes the epoch; a deposed leader's writes fail. Across regions, only the directory can move a city's home, and moving it bumps the city epoch, so even if an old region is still running after a network partition (the regions temporarily lose the ability to talk to each other, though each keeps running on its own), its writes carry the old epoch and are rejected once it reconnects.
When the same driver appears in two regions
This happens in three ways: a driver near a border between cities homed in different regions, a driver relocating (flies from one country to another), and a split brain (both regions believing they are the sole authority for the same driver) during a network partition.
Region-selection rules for drivers:
- A driver's home region is the home of the city whose operating area they are in when they go online.
- Mid-trip, a driver never changes home; the trip finishes in the region that created it, even if it ends across the border.
- Between trips, if the driver's position is in a city homed elsewhere for more than a short dwell time (for example 2 minutes, to avoid flapping at a border), the directory moves their home with an epoch bump. The old region stops offering them the moment its epoch is stale.
- A relocating driver who goes offline in one city and online in another is simply re-homed at go-online.
Conflict resolution when prevention fails (for example a partition in which both regions believe they own a driver): the directory's epoch decides. The assignment made with the current epoch stands; the other is cancelled, and its rider is re-matched at the front of the queue with a notification. Prevention is the main defence: during a partition, a region that cannot confirm its epoch for a city stops assigning in that city (choosing consistency over availability for assignment only, refusing to assign rather than risk a wrong or double assignment; browsing and quoting keep working).
Failover
- Health checks declare region B down (several independent signals, not one probe, to avoid failing over on a monitoring glitch).
- The directory re-homes B's cities to their standby region, bumping each city's epoch.
- Driver and rider apps reconnect to the new region (DNS or client-side region lists). Within one ping interval (for example 4 s) the location index is populated.
- In-flight trips are restored from the async replica; the last few seconds may be missing and are reconciled from the apps, which hold their own copy of the active trip.
Capacity: with 3 regions and one failed, the failed region's load splits over the other two, so each needs its own load L plus L/2, which is 1.5L. Normal utilisation must therefore stay at or below 1 / 1.5, about 67%.
Trade-offs and pitfalls
- Truly multi-master matching (letting more than one region independently accept assignments for the same city at once) for one city across regions needs cross-region coordination per assignment; the latency arithmetic rules it out.
- Replicating the location index across regions costs bandwidth for data that is stale by the time it arrives and is rebuilt in seconds anyway.
- Automatic region failover on a flaky signal causes more incidents than it prevents; require corroboration.
- Forgetting border dwell time makes drivers flap between regions.
Technical coding: Provide high-level pseudocode to set up a bipartite graph between drivers and riders, compute an approximate min-cost max-flow using an existing library, and handle timeouts by returning a valid partial assignment. Describe API inputs/outputs and complexity considerations for real-time use.
Sample Answer
Direct answer
Treat each matching window (for example every 2 seconds, per geographic cell) as a bipartite graph: drivers on one side, waiting riders on the other, and an edge only where a driver could plausibly pick the rider up, weighted by predicted pickup time (the ETA, estimated time of arrival, of the driver at the rider). Add a source and a sink with capacity-1 edges and run a min-cost max-flow solver from a library: it returns the largest possible set of one-to-one matches and, among those, the one with the smallest total pickup time. Before calling the solver, compute a cheap greedy assignment so a valid answer already exists; give the solver whatever is left of the deadline and return the greedy answer if it runs out.
A bipartite graph is a graph whose nodes split into two groups with edges only between the groups. Min-cost max-flow pushes as many units of "flow" as possible from source to sink through capacity-limited edges, then picks the cheapest way to do it. With every capacity equal to 1, one unit of flow through driver d and rider r means "d picks up r".
Formalising the objective
Let xij∈{0,1} mean driver i is assigned to rider j, and cij the predicted pickup time in seconds.
mins.t.(i,j)∈E∑cijxijj∑xij≤1for every driver ii∑xij≤1for every rider jOn its own this is minimised by matching nobody, so something must reward a match. Two standard choices:
- Lexicographic (optimise in strict priority order: fully settle the first goal, then break ties on the second, never trading the first for the second) , which is what max-flow-min-cost does: first maximise the number of matches, then, only among the assignments that already achieve that maximum, minimise total pickup time.
- Penalty form: add a cost P for every rider left unmatched, so a match is taken only when its pickup time is below P.
The penalty form is more tunable (P becomes "how many seconds of pickup is one extra completed ride worth").
Optional background, safe to skip: you do not need the rest of this paragraph to use a flow solver correctly; it only explains why the solver is allowed to return clean 0/1 answers at all. Solving the assignment problem directly, forcing every xij to be exactly 0 or 1, is a hard combinatorial search in general (that is what integer programming means: optimisation where some variables are required to be whole numbers, which is usually much slower than optimisation where they can be any real number). Flow solvers dodge that cost by first solving the relaxed problem, letting each xij be any value between 0 and 1, which is fast. For most optimisation problems that relaxed answer would come out fractional (some xij = 0.4) and would need to be forced whole by hand. Bipartite matching happens to avoid that: its constraint matrix (the table of which variable appears in which "at most one" rule above) has a structural property called total unimodularity, which guarantees the relaxed problem's best answer is already whole, 0 or 1, with no fractions to clean up. That is the one fact this section depends on: it is why flow solvers can use fast continuous methods and still hand back valid 0/1 assignments, not something you need to re-derive to use one.
High-level pseudocode
function match_batch(drivers, riders, params):
start = now()
edges = []
for rider in riders:
for driver in spatial_index.k_nearest(rider.location, params.k):
eta = eta_service.pickup_seconds(driver, rider)
if eta <= params.max_pickup_s:
edges.append(driver, rider, eta)
fallback = local_search(greedy(edges)) # always valid, computed first
remaining = params.deadline_ms - elapsed(start)
if remaining <= 0 or solver_still_busy_from_last_batch:
return fallback, solver="greedy+swap"
result = run_with_timeout(min_cost_max_flow(build_graph(edges)), remaining)
return result if finished else fallback
Unmatched riders are simply carried into the next window, which is what "valid partial assignment" means here: every driver appears at most once, every rider at most once, and nobody is promised a driver the solver has not confirmed.
Runnable implementation (Python, networkx)
pip install networkx. networkx's max_flow_min_cost computes the maximum flow value, then solves a min-cost flow for that value with the network simplex method (an algorithm that starts from one valid whole-number assignment and repeatedly swaps along a cycle of edges whenever a swap lowers total cost, stopping when no improving swap remains, working directly on the graph rather than on a general table of numbers).
import math
import random
import time
from concurrent.futures import ThreadPoolExecutor
import networkx as nx
SPEED_KMH = 24.0 # assumed average city pickup speed
def travel_s(d, r):
"""Pickup travel time in whole seconds (straight-line km / speed)."""
km = math.hypot(d["x"] - r["x"], d["y"] - r["y"])
return int(round(km / SPEED_KMH * 3600))
def candidate_edges(drivers, riders, k, max_pickup_s):
"""Keep only the k nearest drivers per rider within the pickup cap (sparsifies the graph)."""
edges = []
for r in riders:
costs = sorted((travel_s(d, r), d["id"]) for d in drivers)
for c, did in costs[:k]:
if c <= max_pickup_s:
edges.append((did, r["id"], c))
return edges
def greedy(edges):
"""Always-valid fallback: take the cheapest remaining edge whose endpoints are both free."""
used_d, used_r, out = set(), set(), []
for did, rid, c in sorted(edges, key=lambda e: (e[2], e[0], e[1])):
if did not in used_d and rid not in used_r:
used_d.add(did); used_r.add(rid); out.append((did, rid, c))
return out
def swap_improve(assign, cost, max_passes=3):
"""Local search: swap the drivers of two matched riders when that lowers total cost."""
a = list(assign)
for _ in range(max_passes):
improved = False
for i in range(len(a)):
for j in range(i + 1, len(a)):
(d1, r1, c1), (d2, r2, c2) = a[i], a[j]
n1, n2 = cost.get((d2, r1)), cost.get((d1, r2))
if n1 is not None and n2 is not None and n1 + n2 < c1 + c2:
a[i], a[j] = (d2, r1, n1), (d1, r2, n2)
improved = True
if not improved:
break
return a
def solve_flow(edges):
"""Min-cost max-flow: maximise matches first, then minimise total pickup seconds."""
G = nx.DiGraph()
for did, rid, c in edges:
G.add_edge("S", ("d", did), capacity=1, weight=0)
G.add_edge(("d", did), ("r", rid), capacity=1, weight=c)
G.add_edge(("r", rid), "T", capacity=1, weight=0)
flow = nx.max_flow_min_cost(G, "S", "T")
cost = {(d, r): c for d, r, c in edges}
out = []
for u, targets in flow.items():
if isinstance(u, tuple) and u[0] == "d":
for v, f in targets.items():
if f == 1 and isinstance(v, tuple) and v[0] == "r":
out.append((u[1], v[1], cost[(u[1], v[1])]))
return out
_pool = ThreadPoolExecutor(max_workers=1)
_inflight = None # a solve that overran its deadline may still be running
def match_batch(drivers, riders, k=5, max_pickup_s=600, deadline_ms=200):
global _inflight
start = time.monotonic()
edges = candidate_edges(drivers, riders, k, max_pickup_s)
cost = {(d, r): c for d, r, c in edges}
fallback = swap_improve(greedy(edges), cost) # valid answer exists BEFORE the solver starts
solver = "greedy+swap"
result = fallback
remaining = deadline_ms / 1000 - (time.monotonic() - start)
solver_busy = _inflight is not None and not _inflight.done()
if remaining > 0 and edges and not solver_busy:
_inflight = _pool.submit(solve_flow, edges)
try:
result = _inflight.result(timeout=remaining)
solver = "min_cost_flow"
except Exception: # TimeoutError or solver error
result = fallback
matched = {r for _, r, _ in result}
return {
"assignments": [{"driver_id": d, "rider_id": r, "pickup_s": c}
for d, r, c in sorted(result, key=lambda t: t[1])],
"unmatched_riders": sorted(r["id"] for r in riders if r["id"] not in matched),
"solver": solver,
"matches": len(result),
"total_pickup_s": sum(c for _, _, c in result),
}
if __name__ == "__main__":
rng = random.Random(7)
drivers = [{"id": f"d{i:02d}", "x": rng.uniform(0, 5), "y": rng.uniform(0, 5)} for i in range(30)]
riders = [{"id": f"r{i:02d}", "x": rng.uniform(0, 5), "y": rng.uniform(0, 5)} for i in range(25)]
edges = candidate_edges(drivers, riders, k=5, max_pickup_s=600)
cost = {(d, r): c for d, r, c in edges}
g = greedy(edges)
gs = swap_improve(g, cost)
print("candidate edges:", len(edges))
def show(label, n, total, extra=""):
print(f"{label:<13} matches={n} total_pickup_s={total} mean_pickup_s={total / n:.0f} {extra}".rstrip())
show("greedy", len(g), sum(c for *_, c in g))
show("greedy+swap", len(gs), sum(c for *_, c in gs))
full = match_batch(drivers, riders, deadline_ms=5000)
show(full["solver"], full["matches"], full["total_pickup_s"], f"unmatched={full['unmatched_riders']}")
late = match_batch(drivers, riders, deadline_ms=0)
show(late["solver"], late["matches"], late["total_pickup_s"], f"unmatched={late['unmatched_riders']}")
Output (networkx 3.7, Python 3.14; seed 7):
candidate edges: 125
greedy matches=22 total_pickup_s=1286 mean_pickup_s=58
greedy+swap matches=22 total_pickup_s=1273 mean_pickup_s=58
min_cost_flow matches=25 total_pickup_s=2016 mean_pickup_s=81 unmatched=[]
greedy+swap matches=22 total_pickup_s=1273 mean_pickup_s=58 unmatched=['r03', 'r04', 'r23']
The third line assumes the solve finishes inside the generous 5-second budget on this 125-edge graph; the fourth line is deterministic because a deadline of 0 is already spent before the solver is submitted.
Reading the worked example
- Greedy grabbed the cheapest edges first and in doing so used up the only nearby drivers of r03, r04 and r23, stranding three riders. The swap pass trimmed 13 seconds but cannot fix that, because it only swaps drivers between already-matched riders.
- The flow solver matched all 25. Its mean pickup is higher (81 s vs 58 s) because the three extra matches are the long ones; it is not "worse", it is answering a different question (maximum matches first). If the business prefers "skip a match whose pickup exceeds P seconds", use the penalty form above instead.
API inputs and outputs
| Field | Direction | Meaning |
|---|---|---|
batch_id, cell_id | in | idempotency key for the window and the geographic cell it covers |
drivers[] | in | driver_id, location, location_ts, vehicle type, state (only AVAILABLE drivers are sent) |
riders[] | in | request_id, pickup location, requested_at, product type |
params | in | k, max_pickup_s, deadline_ms, optional penalty P |
assignments[] | out | driver_id, rider_id, pickup_s (each id at most once) |
unmatched_riders[] | out | carried into the next window, oldest first |
solver | out | min_cost_flow or greedy+swap, so dashboards can alert when fallback is used too often |
objective | out | total pickup seconds and match count, for monitoring |
The output is a proposal, not a commitment: the dispatch layer still performs a conditional write per driver ("set OFFERED only if still AVAILABLE") because a driver can go offline between snapshot and write.
Complexity for real-time use
| Step | Cost | Note |
|---|---|---|
| Candidate generation | about R times (log D + k) with a spatial index | R riders, D drivers; the demo scans all drivers for clarity, which is R times D log D |
| Graph size | E = k times R edges | k = 5 keeps it linear in R instead of R times D |
| Greedy | E log E | sort edges once |
| Swap local search | m squared per pass, m = matches | capped at 3 passes |
| Exact assignment | Hungarian algorithm (the classic exact method for one-to-one assignment on a dense cost matrix) is cubic in n | n = 1,000 gives about 10 to the power 9 elementary steps, too many for a 2-second window in Python |
| Network simplex on the sparse graph | no tight worst-case bound, fast in practice on sparse graphs | this is why sparsification matters more than the solver choice |
Approximation strategies when n is large:
- Clustering / geographic sharding: solve each cell independently; drivers near a boundary are offered to one cell only (by ownership rule) so cells cannot double-book.
- Greedy then local search: the fallback above; cheap and always valid.
- Auction algorithm: riders "bid" for drivers and prices rise until the assignment settles; with bid increment epsilon the total cost is within n times epsilon of optimal, and bids parallelise well.
- Shrinking k when the edge count exceeds what the time budget can handle.
Trade-offs and pitfalls
- You cannot kill a Python thread. The demo's timeout returns the fallback but the solve keeps running; the
solver_busyguard stops the next batch from queueing behind it. In production, run the solver in a separate process you can terminate, or use a solver with a built-in time limit. - Deterministic tie-breaking (sort by cost, then ids) makes batches reproducible for debugging and replay.
- Stale inputs: a driver location older than a few ping intervals should be dropped from the batch rather than matched with a wrong ETA.
- Straight-line ETA is a stand-in. Real costs come from a routing service; calling it for k times R pairs is the dominant latency, so cache road-segment speeds and compute pair ETAs in bulk.
- Batch window length trades matching quality against added wait: a 2-second window adds about 1 second of average wait (half the window) before anyone is matched.
Unlock Full Question Bank
Get access to all 40 Marketplace, Dispatch, and Logistics System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.