Zero-Detour Ride-Pool Matching on a Grid

Hard · System Design · Software Engineer · Technical Screen

Prompt

Architect the matching and routing engine for a commuter carpool platform operating on an orthogonal street grid governed by Manhattan (L1) distance, d((x1, y1), (x2, y2)) = |x1 - x2| + |y1 - y2|. Each driver begins at grid intersection S heading toward destination T and will only take on pooled passengers if the resulting multi-stop route preserves the driver's exact baseline travel distance d(S, T)—adding zero extra blocks of travel.

Your objective is to serve as many pooled passengers as possible while strictly enforcing the zero-detour rule and vehicle seat limits. Cover your product assumptions, rider and driver APIs (ride requests, match offers and acceptance, live position and route updates), service topology, data model and storage tiers, geometric multi-stop matching algorithm, concurrency and fault handling at scale, and key health metrics and edge cases.

Scope & Expectations

  • Product rules, APIs, and data model: Clarify seat-capacity, timing, and tie-breaking assumptions, define asynchronous endpoints and live streaming channels for drivers and riders, and separate transactional route state from high-frequency location updates.
  • Zero-detour geometry and online optimization: Derive the exact coordinate condition under which a multi-stop sequence keeps total Manhattan length equal to d(S, T), and design a fast indexing and batch-assignment strategy that maximizes total riders served over time.
  • Concurrency, scale, and operational edge cases: Prevent double-booked seats or stale offers while vehicles are moving, recover cleanly from matcher or GPS failures, and address degenerate routes (such as single-axis trips or same-corner handoffs) and monitoring metrics.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Before drawing architecture boxes, pin down what makes this problem different from ordinary ride pooling. All vehicles move along an orthogonal street network measured by Manhattan distance (also called taxicab or L1 distance — the sum of east-west and north-south blocks separating two intersections):

    d((x1, y1), (x2, y2)) = |x1 - x2| + |y1 - y2|
    

    Here the driver is a commuter already heading from origin S to destination T. The product makes a strict promise: picking up riders never adds even a single extra block to the driver's trip, so total distance driven stays fixed at d(S, T). That turns the usual "minimize detour" heuristic into an exact geometric rule that shapes our index, algorithm, and storage design.

    Functional requirements

    • Publish a driver trip: A driver posts origin S, destination T, departure time, available seats C (1 to 3), and whether matches are auto-accepted.
    • Request a ride: A rider submits pickup P, dropoff D, seat count (default 1), and a pickup time window (for an immediate ride, within the next 10 minutes).
    • Zero-detour matching: Offer riders to drivers so every driver's total driven Manhattan distance stays d(S, T) while serving as many riders as possible.
    • Accept and track: Drivers accept or decline offers (or use auto-accept); drivers and riders receive live updates for GPS location, ETAs, stop changes, pickups, dropoffs, and cancellations.

    Non-functional requirements

    • Low decision latency: Return an initial match offer or a "SEARCHING" status update within ~3 seconds (p99), including a short matching batch window.
    • Hard safety invariants: Zero system-caused extra blocks, at most C riders in the car on any street leg, and zero double-booked seats.
    • High availability: 99.9% uptime for ride requests and offer acceptance; if the matcher briefly restarts, active trips continue unaffected.
    • Location freshness: Drivers send GPS pings every 4 seconds; trips without a ping in the last 15 seconds receive no new offers until fresh pings resume.

    Clarifying assumptions

    • Distance vs. time: Zero detour applies strictly to Manhattan distance. Every pickup or dropoff still takes curb time, so we budget up to 60 seconds of dwell time per stop and never match a rider if the driver would have to sit idle waiting for the rider's earliest pickup time.
    • Grid coordinates: Positions are street intersections with integer coordinates (x, y). Riders meet the driver at P and exit at D (walking a block or two to meet a car is covered in the follow-ups).
    • Route flexibility: A driver is not locked to one pre-chosen street path before matching; any shortest Manhattan path of length d(S, T) is valid.
    • Seats are per leg, not per trip: A 1-seat car can serve three sequential riders one after another as long as two riders never overlap in the car.
    • Online arrivals: Rider requests arrive continuously without knowledge of future demand. Pricing, payments, and fraud detection are out of scope.
  2. Back-of-the-envelope numbers

    Ride matching never crosses cities, so we size one large metro area and replicate the unit per metro. Using Little's Law (a queuing rule stating that the average number of concurrent active items equals arrival rate multiplied by average duration), we can estimate active trips and memory footprint:

    Traffic in one large metro
      Driver trips offering seats   100,000 / day; 12% in peak hour = 12,000 / hour
      Average trip length & time    ~10 km Manhattan distance, ~30 min (0.5 hour) at 20 km/h
      Concurrent active drivers     12,000 / h * 0.5 h = 6,000 active trips (size for 20,000)
      Rider requests                400,000 / day; 12% in peak hour = 48,000 / hour = ~13.3 / s
                                    Plan for 4x surges (rain, stadium exit) -> ~50 requests / s
    
    Driver GPS location stream
      Peak ping rate                6,000 active trips * (1 ping / 4 s) = 1,500 pings/s (surge: 5,000/s)
      Wire bandwidth                1,500/s * 200 B = 0.3 MB/s per metro (~15-50 MB/s across 50 metros)
      Daily cold location log       100,000 trips/day * 450 pings/trip * 200 B = ~9 GB/day per metro
    
    Spatial grid index (500 m x 500 m cells = 0.25 km^2 per cell; 600 km^2 metro = 2,400 cells)
      Initial trip rectangle        e.g., 6 km east * 4 km north = 24 km^2
      Average remaining rectangle   As progress u goes 0 -> 1, remaining width and height scale as (1 - u),
                                    so area scales as (1 - u)^2, whose average over the trip is 1/3:
                                    24 km^2 * (1/3) = 8 km^2 remaining on average
      Cells covered per active trip 8 km^2 / 0.25 km^2 = 32 interior cells (~50 cells with borders)
      Total in-memory index entries 6,000 trips * 50 cells = 300,000 IDs (~2.4 MB of RAM!)
      Candidate trips per pickup    6,000 trips * (8 km^2 / 600 km^2) = ~80 candidate trips
    
    Compute per 2-second matching batch
      Peak batch workload           ~27 requests * ~80 candidate trips = ~2,160 exact checks
      Cost per exact check          O(m) integer comparisons (m <= 8 stops ahead) -> a few milliseconds total
    

    These numbers reveal where to focus our design: CPU and RAM for matching are tiny (megabytes of memory and milliseconds of compute per metro). The real engineering problems are enforcing exact geometric compatibility across multiple riders, avoiding greedy matches that block future riders, and preventing race conditions when drivers move while offers are in flight.

  3. Core APIs

    Because matching runs in 2-second batches, ride creation is asynchronous. Drivers maintain a WebSocket (a persistent two-way network connection over TCP that lets the server push offers immediately without repeated HTTP polling), while write endpoints require an idempotency key (a unique client-generated UUID sent in the header so retrying a timed-out request returns the original response instead of creating duplicate trips or requests).

    Driver endpoints
      POST /v1/driver-trips                          Header: Idempotency-Key: <uuid>
           {origin: {x, y}, destination: {x, y}, depart_at, seats: 3, auto_accept: true}
        -> 201 {trip_id, plan_version: 1, stops: []}
    
      WS   /v1/stream
           driver -> server   location {trip_id, x, y, ts, seq}                  (every 4 s)
           server -> driver   offer    {offer_id, request_id, pickup, dropoff, pickup_eta, expires_at}
                              plan     {trip_id, plan_version, stops: [{stop_id, kind, x, y, eta}]}
    
      POST /v1/offers/{offer_id}/accept              {plan_version: 4}
        -> 200 {plan_version: 5} | 409 Conflict (plan changed) | 410 Gone (offer expired)
      POST /v1/offers/{offer_id}/decline
      POST /v1/driver-trips/{trip_id}/stops/{stop_id}/complete   {kind: "PICKED_UP" | "DROPPED_OFF" | "NO_SHOW"}
      POST /v1/driver-trips/{trip_id}/end
    
    Rider endpoints
      POST   /v1/ride-requests                       Header: Idempotency-Key: <uuid>
             {pickup: {x, y}, dropoff: {x, y}, seats: 1, earliest_pickup, latest_pickup}
          -> 202 {request_id, status: "SEARCHING"}
      GET    /v1/ride-requests/{request_id}
          -> 200 {status, trip_id, pickup_eta, dropoff_eta, driver_position}
      DELETE /v1/ride-requests/{request_id}          (cancel request)
      WS     server -> rider events: matched, eta_update, driver_location, picked_up, dropped_off, expired
    

    Notice that accept sends back the plan_version the driver saw on screen. If a rider cancelled or the offer timed out a moment earlier, the version check catches the mismatch cleanly instead of committing an outdated route.

  4. Data model and storage choices

    Transactional trip plans and fast-moving GPS pings have very different access patterns, so we split storage by responsibility:

    • PostgreSQL (one primary + synchronous standby per geographic region): Holds trips, ordered stops, ride requests, and offers. At ~13 requests/s per metro, write throughput is modest (~100 SQL writes/s), and ACID transactions (atomic database operations guaranteed to succeed completely or roll back completely) let us update stops, offers, and plan_version together without race bugs.
    • Redis (in-memory key-value store): Holds only the latest GPS fix per active trip (pos:{trip_id} -> {x, y, ts, heading}) for sub-millisecond reads and matcher recovery.
    • Kafka (distributed append-only event stream): Topic driver-locations partitioned by trip_id ingests the 1,500+ GPS pings/s per metro, feeding both the live matcher and archival object storage.
    driver_trip  (trip_id PK, driver_id, metro_id, sx, sy, tx, ty, seats, auto_accept,
                  status ACTIVE|ENDED, plan_version INT, depart_at, created_at)
    
    trip_stop    (trip_id, stop_id, seq INT, kind PICKUP|DROPOFF, request_id,
                  x INT, y INT, seats INT, state TENTATIVE|CONFIRMED|DONE|CANCELLED,
                  eta TIMESTAMP,  PRIMARY KEY (trip_id, stop_id))
    
    ride_request (request_id PK, rider_id, metro_id, px INT, py INT, dx INT, dy INT,
                  seats INT, earliest_pickup, latest_pickup,
                  status SEARCHING|OFFERED|MATCHED|PICKED_UP|DONE|CANCELLED|EXPIRED,
                  trip_id NULL, idempotency_key UNIQUE, created_at)
    
    offer        (offer_id PK, request_id, trip_id, plan_version INT,
                  expires_at TIMESTAMP, status OPEN|ACCEPTED|DECLINED|EXPIRED)
    
    trip_event   (event_id PK, trip_id, ts, event_type, payload JSONB)   -- append-only audit log
    

    Raw grid coordinates (x, y) are stored as submitted; the matcher normalizes each trip's travel direction in memory.

  5. High-level architecture

     Driver app --- HTTPS (trip/accept) + WS (GPS every 4 s, offers, plan) ---+
     Rider app  --- HTTPS (request/cancel) + WS (live match & ETA updates) ---+
                                                                              |
                                                                              v
                                               +----------------------------------------------+
                                               |   Load Balancer + WebSocket Gateway Tier     |
                                               +----------------------------------------------+
                                                    |                 |                  |
                                                    v                 v                  v
                                             +------------+    +-------------+    +-----------------+
                                             |  Trip Svc  |    | Request Svc |    | Location Ingest |
                                             +------------+    +-------------+    +-----------------+
                                                    |                 |                  |
                                                    v                 v                  v
                                        +------------------------------------+    Kafka: driver-locations
                                        |     PostgreSQL (per region)        |      (key = trip_id)
                                        | trips, stops, requests, offers,    |           |
                                        | plan_version                       |           v
                                        +------------------------------------+    +---------------------------+
                                               ^                   ^              | Matcher Leader (1/metro)  |
                                               |                   +-- CAS txn ---|  - 500 m cell grid index  |
                                        +--------------+              commit      |  - open request pool      |
                                        |  Offer Svc   |<-------------------------|  - in-memory plan cache   |
                                        | (15 s holds) |                          +---------------------------+
                                        +--------------+                                 |             |
                                               |                                         v             v
                                               +---> push via WS Gateways         Redis: latest   ETA Service
                                                     to driver and rider          GPS per trip   (cell speeds)
    

    End-to-end lifecycle:

    1. Trip start: Trip Service writes driver_trip to Postgres and notifies the metro's Matcher Leader, which inserts the trip's rectangle [S, T] into its 500 m cell grid index.
    2. GPS ping: Location Ingest writes the latest fix to Redis and appends to Kafka; the Matcher updates the driver's current corner cur, shrinking the reachable rectangle to [cur, T].
    3. Ride request: Request Service persists ride_request (SEARCHING) and forwards it to the Matcher's next 2-second batch.
    4. Batch match: Every 2 seconds, the Matcher queries candidate trips from the grid index, runs exact chain insertion and ETA checks, computes a maximum-weight assignment, and writes tentative stops + an offer to Postgres using plan_version.
    5. Accept / auto-accept: Offer Service flips tentative stops to CONFIRMED in one SQL transaction (or Matcher writes CONFIRMED directly when auto_accept = true) and pushes updated routes and ETAs over WebSockets.
  6. Deep dive 1: Zero-detour geometry and O(m) chain insertion

    Why can some riders be picked up with zero extra Manhattan blocks while others cannot? Look at one axis at a time. On a 1D number line, going from a to x to b satisfies |a - x| + |x - b| = |a - b| if and only if x lies between a and b (never stepping backward). Because Manhattan distance is simply horizontal distance plus vertical distance, a multi-stop route S -> X1 -> X2 -> ... -> Xk -> T has total length d(S, T) if and only if neither x nor y ever reverses direction.

    If we flip the coordinate signs for a trip so T sits "east and north" (up and right) of S, zero detour becomes a monotone chain (a sequence where every stop is greater than or equal to the previous stop in both coordinates, forming a rising staircase):

    Oriented grid for driver S = (0, 0) -> T = (6, 4):
    
      y
      4 | .  .  .  .  .  .  T(6,4)
      3 | .  .  .  .  D_A.  .        Rider A: P_A(1,1) -> D_A(4,3)  [VALID: (0,0)<=(1,1)<=(4,3)<=(6,4)]
      2 | .  .  .  .  .  D_B.        Rider W: (4,3) -> (1,1)        [INVALID: inside box, but moves backward!]
      1 | .  P_A.  .  .  .  .        Rider B: P_B(3,0) -> D_B(5,2)  [VALID alone, CONFLICTS with Rider A!]
      0 | S  .  .  P_B.  .  .
        +-------------------- x
          0  1  2  3  4  5  6
    
    Why Rider A and Rider B cannot BOTH ride on the same shortest path:
      Compare P_A(1, 1) and P_B(3, 0):
      - Going P_A(1,1) -> P_B(3,0) moves SOUTH (y drops 1 -> 0): 2 blocks of detour!
      - Going P_B(3,0) -> P_A(1,1) moves WEST  (x drops 3 -> 1): 4 blocks of detour!
    

    Three crucial consequences follow immediately from this staircase rule:

    1. Every rider also gets a zero-detour ride: Any slice of a monotone chain between P and D is itself monotone, so the rider travels exactly d(P, D).
    2. Navigation keeps street-level freedom: Between consecutive stops s_k and s_{k+1}, any east/north street sequence has the exact same Manhattan length, so turn-by-turn navigation can dynamically route around traffic jams.
    3. Insertion into m planned stops takes O(m) time: Suppose the car's remaining plan in oriented coordinates is stops = [cur, s_1, ..., s_{m-1}, T], with load[k] riders on board between stops[k] and stops[k + 1]. Because stops is already a sorted chain, checking whether P fits between stops[i] and stops[i + 1] requires comparing P only against those two adjacent stops. When two stops share the exact same intersection, dropoffs must happen before pickups so a seat vacated at corner X can be filled at corner X:
    def manhattan(a, b):
        # Taxicab distance on an integer grid: |x1 - x2| + |y1 - y2|
        return abs(a[0] - b[0]) + abs(a[1] - b[1])
    
    
    def orient(S, T):
        # Choose +1 or -1 multipliers per axis so T is always >= S in both coordinates
        sx = 1 if T[0] >= S[0] else -1
        sy = 1 if T[1] >= S[1] else -1
        return sx, sy
    
    
    def to_oriented(point, sx, sy):
        return (point[0] * sx, point[1] * sy)
    
    
    def leq(a, b):
        # True if moving from a to b never steps backward in either oriented coordinate
        return a[0] <= b[0] and a[1] <= b[1]
    
    
    def find_insertion(stops, load, seats, P, D, need=1):
        """Check if a rider (P -> D) needing `need` seats fits into an oriented chain `stops`.
        stops: [cur, s_1, ..., T] in oriented coordinates.
        load[k]: seats already occupied on leg k (between stops[k] and stops[k + 1]).
        Returns (i, j) meaning insert P after stops[i] and D after stops[j] (after P if i == j),
        or None if geometric order or seat capacity is violated.
        """
        # Reject zero-length rides or riders moving backward in the driver's frame
        if P == D or not leq(P, D):
            return None
    
        n = len(stops)
        for i in range(n - 1):
            # Corner tie-break: place new pickup AFTER any existing stops at the same corner P,
            # which means stops[i] <= P < stops[i + 1]
            if not (leq(stops[i], P) and leq(P, stops[i + 1]) and P != stops[i + 1]):
                continue
    
            for j in range(i, n - 1):
                # Every leg from i through j will carry this rider, so check spare capacity
                if load[j] + need > seats:
                    break
                # Corner tie-break: place new dropoff BEFORE any existing stops at corner D,
                # which means stops[j] < D <= stops[j + 1]
                if leq(stops[j], D) and leq(D, stops[j + 1]) and D != stops[j]:
                    return (i, j)
    
        return None
    

    Notice why find_insertion runs in O(m) time: if P satisfies P <= stops[i + 1] and P != stops[i + 1], then P.x + P.y < stops[i + 1].x + stops[i + 1].y, so P can never be >= stops[k] for any k >= i + 1. At most one index i enters the inner loop! Every candidate that passes find_insertion then undergoes an ETA feasibility check: using cell speeds from the ETA service plus 60 seconds of stop dwell, verify that the driver reaches P within [earliest_pickup, latest_pickup] without waiting and does not push any already-confirmed rider past their promised arrival window (e.g., <= 3 minutes of additional stop dwell).

  7. Deep dive 2: Maximizing riders served (online batch matching)

    Our goal is not merely finding a valid rider, but serving as many riders as possible. Distinguish the offline benchmark from the live online policy:

    1. Offline benchmark (all requests known ahead of time). For a 1-seat car, riders cannot overlap; rider i can precede rider j iff D_i <= P_j. Sorting feasible riders by P.x + P.y gives a valid topological order, turning single-driver max riders into longest-chain dynamic programming (solving a problem by combining optimal answers to smaller subproblems) in O(n^2) time. We run this offline on historical logs to measure how close our live matcher comes to optimal:

    def pickup_progress(rider):
        # Sum of oriented pickup coordinates strictly increases along any valid chain
        pickup = rider[0]
        return pickup[0] + pickup[1]
    
    
    def max_sequential_riders(S, T, riders):
        """Offline 1-seat benchmark in oriented coordinates: max non-overlapping riders on S -> T."""
        feasible = [
            (P, D) for P, D in riders
            if P != D and leq(S, P) and leq(P, D) and leq(D, T)
        ]
        feasible.sort(key=pickup_progress)
    
        # best[j] stores the longest chain of riders ending with feasible[j]
        best = []
        for j in range(len(feasible)):
            best_chain_len = 1
            for i in range(j):
                # Rider i finishes at feasible[i][1] before rider j starts at feasible[j][0]
                if leq(feasible[i][1], feasible[j][0]):
                    best_chain_len = max(best_chain_len, best[i] + 1)
            best.append(best_chain_len)
    
        return max(best, default=0)
    

    2. Online production matching (requests arriving continuously). In real time, matching the first feasible rider greedily is short-sighted. On a trip from (0, 0) to (10, 10), matching a rider from (1, 9) to (9, 10) serves 1 rider today, but pinches the driver's route into two skinny corners and blocks almost every future rider! By contrast, matching (4, 4) -> (6, 6) keeps two wide rectangles [ (0,0), (4,4) ] and [ (6,6), (10,10) ] open.

    We quantify this opportunity cost (the expected future matches lost by committing to an action now) by counting how many reachable intersections remain on legs that still have at least one free seat (load[k] < seats):

    def usable_grid_corners(stops, load, seats):
        """Count grid intersections still reachable on legs that have spare seat capacity.
        Works even when S and T lie on the same straight street (dx == 0 or dy == 0).
        """
        usable = 0
        for k in range(len(stops) - 1):
            if load[k] >= seats:
                # Car is full on leg k; no new rider can board or ride across this leg
                continue
            a, b = stops[k], stops[k + 1]
            usable += (b[0] - a[0] + 1) * (b[1] - a[1] + 1)
        return usable
    

    Weighting each reachable grid cell by historical pickup demand for that 15-minute time-of-day bucket converts lost grid corners directly into expected_future_riders_lost. Every 2 seconds, the metro's Matcher Leader runs one batch:

    1. Candidate lookup: For each open request r, look up P's 500 m cell in the grid index (~80 trips), skipping trips with stale GPS (> 15 s) or an already-open offer.
    2. Exact filter + safety buffer: Orient (P, D), require P to lie ahead of the driver's extrapolated position by at least the distance traveled during the 15-second offer window (~80 m at 20 km/h) so drivers never pass P while reading the offer, and run find_insertion + ETA checks.
    3. Edge scoring: Score each valid (request, trip) pair as 1.0 - lambda * expected_future_riders_lost - mu * pickup_wait_minutes + urgency_bonus (where urgency_bonus rises as latest_pickup nears so harder requests do not starve).
    4. Global batch assignment: Solve maximum-weight bipartite matching (pairing requests on one side with trips on the other, at most one match per request and one new offer per trip in a batch, maximizing total score). With ~27 requests per batch, an exact solver (Hungarian / min-cost flow) finishes in milliseconds.
  8. Deep dive 3: Concurrency, moving drivers, and failure handling

    While the matcher computes a batch, drivers keep moving, riders cancel, and previous offers expire. Three mechanisms keep seat counts and routes consistent without distributed locks:

    1. Optimistic concurrency control (compare-and-set on plan_version). Rather than locking a driver row while waiting 15 seconds for a human tap, every edit to a trip increments plan_version inside a short SQL transaction:

    BEGIN;
      UPDATE driver_trip
         SET plan_version = :v + 1
       WHERE trip_id = :t AND plan_version = :v AND status = 'ACTIVE';
      -- If 0 rows updated, another event modified this trip -> ROLLBACK and retry next batch
    
      INSERT INTO trip_stop (..., state = 'TENTATIVE') VALUES (...), (...);   -- P and D
      INSERT INTO offer (offer_id, request_id, trip_id, plan_version, expires_at, status)
           VALUES (:oid, :r, :t, :v + 1, now() + interval '15 seconds', 'OPEN');
    
      UPDATE ride_request
         SET status = 'OFFERED'
       WHERE request_id = :r AND status = 'SEARCHING';
      -- If 0 rows updated, rider just cancelled -> ROLLBACK
    COMMIT;
    

    2. Tentative holds vs. auto-accept. Tentative stops reserve their seats and chain positions immediately for up to a 15-second TTL (time-to-live expiration window), and each trip allows at most one OPEN offer at a time so concurrent offers never invalidate each other's plan_version. If the driver declines or 15 seconds pass, Offer Service deletes the tentative stops (plan_version + 1) and returns the request to SEARCHING. Drivers who enable auto_accept skip tentative holds completely — the matcher writes CONFIRMED stops directly, boosting match throughput because zero detour removes route surprises.

    3. Lazy grid updates via the shrinking-box invariant. As a driver follows a monotone route toward T, their remaining bounding box [cur, T] only shrinks. That means a slightly stale grid index entry covers a superset of the true remaining box: it can yield harmless extra candidates (filtered out in microseconds by find_insertion), never a missed match! Therefore, the matcher updates a trip's cells in the grid index only when the car crosses a 500 m cell boundary (~every 90 s at 20 km/h, or 6,000 / 90 ≈ 67 index updates/s per metro instead of 1,500/s). If a driver makes a wrong turn and moves backward in oriented coordinates (beyond ~30 m of GPS noise), the matcher immediately updates [cur, T] and re-indexes; already-confirmed riders keep their pickups, while new matches use the updated box.

    Failure modes and recovery

    • Matcher leader crash: One Matcher Leader per metro holds a 10-second lease (a time-bounded ownership lock in etcd/ZooKeeper). If it dies, a standby acquires the lease and rebuilds the in-memory grid index in ~2 seconds from Postgres active plans + Redis latest positions. Ongoing rides continue unaffected.
    • Lost GPS / rider no-show: Trips dark for > 15 s get no new offers; if dark for > 2 minutes before a confirmed pickup, we cancel the stop and prioritize rematching the rider. Drivers wait up to 2 minutes at P before marking NO_SHOW, freeing the seat for downstream legs.
    • Duplicate taps and network retries: Handled cleanly by Idempotency-Key on creation and primary-key / plan_version guards on offer acceptance.
  9. Metrics, edge cases, and trade-off summary

    Key metrics to monitor

    • Safety & promise metrics (target: 0 system violations): Actual GPS blocks driven minus d(S, T) (split into system-planned vs. driver wrong turns), over-capacity legs, double-offered seats.
    • Marketplace health: Rider match rate, average riders served per driver trip, seat-km utilization, pickup wait time (p50/p95), offer acceptance rate, online-vs-offline match ratio on replayed logs.
    • System health: Request-to-offer latency (p50/p99), 2 s batch compute time, GPS age at match time, plan_version CAS conflict rate.

    Geometric edge cases

    • Straight-line trips (S.x == T.x or S.y == T.y): Bounding box degenerates to a 1D street segment; leq and usable_grid_corners handle width-0 boxes naturally.
    • Degenerate inputs (S == T or P == D): Rejected with 400 Bad Request at the API boundary (and guarded in find_insertion).
    • Same-corner handoffs (D_1 == P_2): Dropoff-before-pickup tie-breaking lets Rider 1 exit and Rider 2 board at the exact same intersection in a 1-seat car.
    • Multi-seat requests (need > 1): Checked against load[j] + need <= seats across every spanned leg.
    Design decision Chosen approach Main alternative Why this fits best
    Route representation Ordered chain of stops (any monotone street path between stops) Single fixed turn-by-turn path Keeps maximum matchable area open and lets navigation route around live traffic
    Dispatch cadence 2-second micro-batches per metro Instant greedy match per request Tiny latency cost (< 2 s) unlocks global bipartite matching across competing requests
    Match scoring 1 - opportunity_cost (usable corners/demand lost) First feasible driver Prevents diagonal "box-pinching" riders from blocking several future matches
    Concurrency control Single metro leader + SQL plan_version CAS Distributed locks across services Zero lock contention over the network; atomic rollback if a rider cancels mid-commit
    Spatial indexing 500 m grid updated only on cell crossings R-tree updated on every 4 s GPS ping Monotone trips only shrink boxes, making lazy cell updates 20x cheaper with zero false negatives

Intuition & how it works

Imagine walking across a gridded downtown from the southwest corner S = (0, 0) to an office at the northeast corner T = (6, 6) in Manhattan distance (city-block distance where you can only travel east-west or north-south, so d((x1, y1), (x2, y2)) = |x1 - x2| + |y1 - y2|). Your walk takes 6 + 6 = 12 blocks ONLY if every single block you walk goes east or north — the moment you step even 1 block west or south, you have to walk an extra block back later, adding at least 2 blocks of detour. Therefore, picking up and dropping off riders adds zero extra distance if and only if all visited stops form a monotone chain (a rising staircase where every stop is >= the previous stop in both east and north coordinates, after orienting axes toward T).

Why does the naive approach fail? First, simply checking whether a rider's pickup P and dropoff D lie inside the driver's bounding box (the rectangle spanned by S and T) fails because a rider inside the box might be traveling backward (D southwest of P), or two individually valid riders might sit off-diagonal to each other (such as (1, 4) and (4, 1)) so visiting both forces a backward step. Second, greedily matching the very first rider who fits can pinch a wide 6 x 6 box down to tiny corners and block three future riders. Finally, without versioned seat holds, a moving driver can pass a pickup corner or double-book a seat while an offer is waiting on their screen.

Let's trace a 1-seat commuter driving S = (0, 0) -> T = (6, 6) across three incoming ride requests:

Initial trip state: stops = [(0,0), (6,6)], load = [0], seats = 1, usable corners = 7 * 7 = 49

1. Request R1: P1=(4,2) -> D1=(2,5)
   Check: P1.x=4 > D1.x=2 (moves west while driver must go east/north).
   Result: REJECTED immediately (not a monotone rider).

2. Request R2: P2=(1,5) -> D2=(5,6)   vs.   Request R3: P3=(1,1) -> D3=(3,3)  (same 2 s batch)
   - R2 fits geometrically, but leaves usable corners only on [(0,0),(1,5)] (12) + [(5,6),(6,6)] (2) = 14
     (leg [(1,5),(5,6)] has load 1 == seats, so 0 new riders can board there).
   - R3 fits geometrically, and leaves [(0,0),(1,1)] (4) + [(3,3),(6,6)] (16) = 20 usable corners open!
   Result: Batch scorer picks R3 -> plan becomes [(0,0), P3(1,1), D3(3,3), (6,6)], load = [0, 1, 0], v = 2.

3. Request R4: P4=(3,3) -> D4=(5,6) arrives next batch
   Check: P4=(3,3) sits right at D3=(3,3). Dropoff-before-pickup rule lets R3 exit at (3,3) before R4
          boards at (3,3), keeping load <= 1 on every leg!
   Result: MATCHED -> plan [(0,0), P3(1,1), D3(3,3), P4(3,3), D4(5,6), (6,6)], total distance still 12!

Key trade-offs

  • Chain of stops vs. a single pre-fixed street route: Representing a driver's plan as an ordered chain of stops (leaving the exact east/north street turns between consecutive stops flexible) accepts every geometrically compatible rider and lets navigation route around live traffic, at the minor cost of slightly wider ETA estimates until the car commits to specific streets.
  • 2-second micro-batching vs. instant greedy matching: Waiting up to 2 seconds collects ~25–30 concurrent requests per metro so maximum-weight bipartite matching (an algorithm that pairs requests and trips one-to-one to maximize total score) can avoid high-opportunity-cost matches, trading a barely noticeable 1-second average wait for a higher overall match rate.
  • Opportunity-cost scoring vs. first-feasible-driver: Penalizing candidates that wipe out high-demand reachable grid corners preserves capacity for downstream riders, though it relies on historical 15-minute cell demand forecasts (lambda can be tuned via offline log replay and safely dialed toward 0 if demand shifts unexpectedly).
  • Tentative 15-second seat holds vs. auto-accept: Reserving tentative stops with a TTL (time-to-live expiration timer) guarantees zero double-booked seats while a driver decides, at the cost of freezing that car's supply for 15 seconds on declined offers; auto_accept eliminates the hold delay completely and fits naturally when detours are guaranteed to be zero.
  • Single metro leader + optimistic concurrency vs. distributed locks: Running one active matcher per metro with compare-and-set (CAS) (an atomic SQL update checking WHERE plan_version = :v and incrementing to v + 1) avoids slow cross-service locks; if a metro ever outgrows one CPU, partitioning by pickup region still stays race-free thanks to the per-trip plan_version check.
  • Lazy 500 m cell grid vs. per-ping spatial tree updates: Because a monotone driver's remaining rectangle [cur, T] only shrinks over time, updating grid cells only when the car crosses a 500 m boundary (~67 updates/s instead of 1,500/s) never misses a true match — stale cells only return extra candidates that the O(m) exact check filters out in microseconds.

Common mistakes

  • Checking only whether P and D fall inside [S, T]: A rider inside the rectangle can still travel backward in x or y, or conflict with an already-matched rider on the same trip; you must verify both leq(P, D) and insertion against all existing stops.
  • Counting seats per trip instead of per leg: A 1-seat commuter can serve three sequential riders ((0,0)->(2,2), (2,2)->(4,4), (4,4)->(6,6)), whereas two overlapping riders fail; capacity must be tracked as load[k] per leg, with dropoffs ordered before pickups at shared intersections.
  • Counting full legs as "free area" in opportunity-cost scoring: If all C seats are occupied between stops[k] and stops[k + 1], zero new riders can board or cross that leg regardless of how big its rectangle looks.
  • Confusing zero extra distance with zero extra time: Every stop adds ~60 seconds of curb dwell, and arriving before a rider's earliest_pickup forces idle waiting; always pair the exact geometric check with an ETA window check.
  • Offering a pickup the car is about to pass: Because GPS pings are up to 4 seconds old and manual acceptance takes up to 15 seconds, require P to sit ahead of the driver's extrapolated position by at least the distance traveled during the offer window (~80 m).
  • Mutating trip plans without plan_version checks: Driver accepts, rider cancellations, and new batch offers can hit the same trip simultaneously; omitting transactional version checks causes double-booked seats.

Follow-up questions

  • How would the spatial index and insertion algorithm change if drivers permit a small detour budget, such as up to 5% extra Manhattan distance? On a 1D segment [a, b], visiting a point x outside the interval adds 2 * distance(x, [a, b]) to total travel, so in 2D any single stop can sit at most 0.025 * d(S, T) outside [S, T] — expanding our grid lookup by that margin. Because stops no longer form a strict monotone chain, find_insertion tries every (i, j) pair in O(m^2) time (m <= 8, still microseconds), sums actual leg Manhattan lengths sum d(s_k, s_{k+1}) <= 1.05 * d(S, T), deducts used detour budget from the trip, and re-verifies that existing riders' promised dropoff ETAs are still honored.
  • How would you adapt zero-detour carpool matching from an idealized grid to a real road graph with one-way streets and curved arterials? Replace Manhattan arithmetic with shortest-path distances from a fast road-graph engine using contraction hierarchies (a graph preprocessing technique that adds shortcut edges so point-to-point shortest-path queries finish in sub-millisecond time). The exact zero-detour test remains the triangle-equality check d(cur, P) + d(P, D) + d(D, T) <= d(cur, T) + epsilon (using a tiny epsilon like 20 meters for GPS map-snapping noise), and stops along a trip are ordered simply by increasing road distance from S.
  • How can you incorporate short rider walk-to-curb segments (for instance, up to 2 blocks) to raise match rates while keeping driver detour at zero? For each leg [stops[k], stops[k + 1]] with a free seat, the closest point inside that rectangle to P in Manhattan distance is simply P with x and y clamped to [stops[k].x, stops[k + 1].x] and [stops[k].y, stops[k + 1].y]. If the walking distance d(P, P') <= 200 m and similarly d(D, D') <= 200 m with leq(P', D'), the virtual stops (P', D') achieve zero driver detour while dramatically increasing match rates, and we add rider walk time as a small penalty in the match score.

Follow-up questions

Similar questions

More Applovin interview questions

All 2 Applovin questions →