System Design

C22

Ride matching and nearby

Drivers move, and their positions change every few seconds. A rider wants a car now. The design question is how to match them fast on data that is always a little old, without ever giving one driver two trips.

Not startedSaved in this browser only.
  1. 1Keep only the newest position of each driver, in memory. A position is cheap to lose, because the next report replaces it. A trip is never cheap to lose.
  2. 2Postgres decides who gets a trip, with conditional updates and partial unique indexes. The Redis lease only saves wasted offers.
  3. 3Batching pays when supply is short. A 5 s window halved the mean pickup when riders outnumbered drivers, and it did almost nothing when drivers were plentiful.
  4. 4Search a small circle first. A wide sorted GEOSEARCH in a dense core blocks the event loop for every position update.
C22
    A

    The prompt

    as the interviewer says it
    Design the matching of riders to nearby drivers whose locations change every few seconds.
    questionanswer assumed
    How many drivers?1 million online at peak; 100,000 in the largest city.
    How often do they report?Every 4 s while online.
    How many rides?20 million a day.
    Who chooses?The system offers a trip to one driver at a time, for 15 s.
    Shared rides?Out of scope. One rider, one driver.
    Payment, routing?Out of scope. Other services own them.
    What may never happen?One driver on two trips; one rider with two cars.

    I confirm the number of drivers, how often they report, and what happens when a driver does not answer. I scope payment and routing out.

    B

    Requirements

    as numbers
    functional
    Drivers report positions and go online or offline.
    Riders request a ride and see the car.
    Offer a trip; a driver accepts or declines.
    Track a trip from request to completion.
    non-functionaltarget
    Position in the indexp99 < 2 s after a report
    Request to first offerp99 < 2 s, plus any batch window
    Double bookings0
    Trip stateStrong: one writer, in Postgres
    PositionsBest effort: the next report repairs a loss
    Availability99.95%, per city

    Positions can be a few seconds old, and a lost one costs nothing. Matches must be exactly right.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Position updates1 M drivers ÷ 4 s250k/s; largest city 25k/s
    Ride requests20 M ÷ 86,400≈ 231/s; 3× peak ≈ 694/s
    Largest citya tenth of the peak≈ 69 requests/s
    Index memory1 M × 80 B (measured)80 MB
    Trips20 M × 300 B (assumed row)6 GB a day ≈ 2.2 TB a year
    Position history250k/s × 50 B × 86,400, at peak rateup to 1.1 TB a day, to a log
    Socket traffic in250k/s × 100 B200 Mbit/s

    Inputs are the assumed answers in panel A. Bytes per driver measured on Redis in the lab. Method: R2.

    Position updates are the load: 250k a second, against 694 ride requests. The index itself is only 80 MB, so the rate is the limit, not the size.

    D

    API

    endpoints, status codes, retries
    callforretry safe bysuccesserrors
    WS /v1/driver/stream {lat, lng, seq}position reportsseq: older reports loseno replySocket closes; the app reconnects
    POST /v1/trips {pickup, dropoff} + Idempotency-Keyrequest a ridethe key201 + trip, surge409 open trip, 422 outside the area
    POST /v1/offers/{id}/acceptdriver acceptsa repeat returns the trip200 + trip410 offer gone
    POST /v1/offers/{id}/declinedriver declineschanges only a pending offer204410
    POST /v1/trips/{id}/events {type}arrived, started, endeda repeat changes 0 rows200 + state409 wrong state
    GET /v1/me/currentthe first call after a reconnecta read200 + trip or offer401

    A request carries an idempotency key. An accept is safe to retry, because a repeat returns the same trip.

    E

    Data model

    truth in Postgres, positions in Redis
    the truth: two tables in Postgres1 : ntripsPKidrider_iddriver_idnull until matchedstatethe machinepickup_lat, _lngsurgefixed at requestversion+1 per stepunique: 1 active per driveroffersPKidFKtrip_iddriver_idstatepending, accepted...expires_atoffer windowunique: 1 pending per driver
    Redis keyholdslives
    drivers:{region}GEO set of idle driversUntil matched or silent
    seen:{city}Sorted set: driver, last report timeSwept after 30 s
    lock:{driver:id}The lease during an offer20 s
    surge:{cell}Multiplier30 s
    trips, offerssql
    CREATE TABLE trips (
      id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      rider_id     bigint NOT NULL,
      driver_id    bigint,
      state        text NOT NULL DEFAULT 'requested' CHECK (state IN
                     ('requested', 'matched', 'arrived', 'in_progress', 'completed', 'cancelled')),
      pickup_lat   double precision NOT NULL,
      pickup_lng   double precision NOT NULL,
      surge        numeric(3,1)1 NOT NULL DEFAULT 1.0,
      version      int NOT NULL DEFAULT 1,
      requested_at timestamptz NOT NULL
    );
    
    CREATE UNIQUE INDEX one_active_trip_per_driver2 ON trips (driver_id)
      WHERE state IN ('matched', 'arrived', 'in_progress');
    CREATE UNIQUE INDEX one_active_trip_per_rider3 ON trips (rider_id)
      WHERE state IN ('requested', 'matched', 'arrived', 'in_progress');
    
    CREATE TABLE offers (
      id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      trip_id    bigint NOT NULL REFERENCES trips,
      driver_id  bigint NOT NULL,
      state      text NOT NULL DEFAULT 'pending' CHECK (state IN
                   ('pending', 'accepted', 'declined', 'expired', 'withdrawn')),
      expires_at timestamptz NOT NULL4
    );
    
    CREATE UNIQUE INDEX one_pending_offer_per_driver5 ON offers (driver_id) WHERE state = 'pending';
    CREATE UNIQUE INDEX one_accepted_offer_per_trip ON offers (trip_id) WHERE state = 'accepted';
    1. 1Fixed at request time, so a later change in surge never changes a quoted price.
    2. 2The index that makes a double booking impossible, whatever the application does.
    3. 3One open trip per rider, so a double tap cannot book two cars.
    4. 4The accept compares this with the time in its own WHERE clause. No timer has to fire.
    5. 5A driver sees one offer at a time, even if two dispatchers try.

    A trip and its offers live in Postgres, with indexes that make a double booking impossible. Positions live only in Redis, where a loss costs one report.

    F

    The architecture

    click a step; its path lights up
    Driver appposition, offersRider apprequest, mapSocket gatewaylatest position onlyTrip APIstatelessDispatcherone per regionSurge jobper cellRedisGEO keys, leases, surgePostgrestrips, offersEvent logevents, history

    Step 1: Report a position

    • The phone sends a position every 4 s on an open socket.
    • The gateway keeps the newest report of each driver.
    • Once a second it writes a batch: GEOADD, and ZADD to the seen set.

    If it fails

    The gateway dies: phones reconnect to another one. The index misses a few seconds of reports, and the next report repairs it.

    Positions flow through a gateway into Redis. A dispatcher per region finds candidates in Redis and commits the match in Postgres.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    RedisGEOADD with many membersA new position replaces the old one; 281k updates a second in batches of 100.Store and venue lookups
    RedisGEOSEARCH BYRADIUS ASC COUNTThe nearest k, with distance and position.Nearby search
    RedisA GEO key is a sorted setLimit No TTL per member, so a sweeper removes silent drivers. ZREM removes a match.
    RedisSET NX PX with a tokenA lease on a driver during an offer.Locks, idempotency
    RedisSorted set by timeThe seen set: drivers silent for 30 s, in one range read.Delay queues
    RedisPipeliningOne round trip for a batch of reports, or for a rider's regions.Any batch
    PostgresUPDATE ... WHERE state = expectedAccept and each trip step happen once. The row count reports the winner.Bookings, inventory
    PostgresPartial unique indexAt most one active trip per driver, enforced by the database.One open order per user
    PostgresTransactionsThe offer and the trip change together, or not at all.Every multi-row rule
    ServiceHungarian methodThe lowest total pickup for one batch: 2.3 ms for 200 riders, measured.Task assignment
    GatewaySticky sockets, in-memory bufferPushes offers, and drops old reports before they reach Redis.Chat, presence
    KafkaPartitioned logTrip events and position history for billing and analysis.Feeds, stream jobs

    Redis GEO gives me a fast index of moving points. Postgres gives me conditional updates and partial unique indexes, which make double bookings impossible.

    H

    Deep dive: positions that move

    ingest and the geo index
    index for moving pointsstatuswhy
    Postgres row per driver, GiST indexSmall fleetEach update writes a row and its index, and leaves a dead tuple
    Redis GEO, one key per cityTo start281k batched updates a second
    Redis GEO, one key per regionApprovedSmall keys, one dispatcher per region
    Quadtree in process memoryHot core onlyFast, but a restart loses it (B11)
    Fixed-radius searchNot approvedSlow where drivers are dense, empty where they are not
    Circle that widensApprovedSmall where dense, wide only where it must be
    report everyindex errormean pickup
    1 s0 m881 m
    4 s7 m888 m
    16 s34 m914 m
    60 s109 m1,048 m
    core searchp50, alonesearches/supdates/s
    3 km fixed6.1 ms171/s2,095/s
    500 m, then wider0.5 ms2,059/s25,827/s

    Index error: the mean distance from a driver's last report to the true position at match time. Report rows: 80% of drivers busy, a 5 s batch, 4 seeds. Search rows: 100,000 drivers on one Redis; 8 searching clients and one batched writer run at the same time.

    one GEO key and one dispatcher per regiontdr0tdr1tdr2tdr3tdr4tdr5tdr6tdr7tdr8tdr9tdratdrbtdrctdrdtdre4.9 km cells25 bits, 5 characters500 m circle38% cross a border1.46 keys a search3 km circle100% cross a border5.02 keys a search100,000 drivers in 81 regions: the core holds 11.96× the mean.
    ingestpseudo code
    on report from a driver:                  // every 4 s
      drop it if a newer report of this driver is here
      buffer[driver] = report                  // only the newest stays1
    
    every 1 s, per gateway:
      skip drivers who moved less than 20 m2
      IN ONE ROUND TRIP:
        GEOADD drivers:{region} lng lat driver // replaces the old position
        ZREM   drivers:{old region} driver     // only after a border crossing3
        ZADD   seen now driver
    
    every 10 s, sweeper:
      remove drivers silent for 30 s           // a GEO member has no TTL4
    1. 1Reports arrive faster than matches need them. Report every 4 s, and the index is only 7 m off on average.
    2. 2A parked car costs no write. The seen set still needs a heartbeat, which a real gateway sends less often.
    3. 3A driver must be in one region only, or a search could return them twice.
    4. 4It is one member of a sorted set, so nothing expires by itself.
    Tested source Go: keep the newest report · Go: regions, search, sweep
    Go: keep the newest reportgo
    
    // Latest keeps only the newest report of each driver between flushes. Reports arrive far more
    // often than a dispatcher needs them, and an older position has no value once a newer one exists.
    type Latest struct {
      pending map[int]Update
      written map[int]Update
      MinMove float64 // metres; a driver who moved less is not written again
    }
    
    // NewLatest returns an empty buffer.
    func NewLatest(minMove float64) *Latest {
      return &Latest{pending: map[int]Update{}, written: map[int]Update{}, MinMove: minMove}
    }
    
    // Add keeps u unless a newer report of the same driver is already here. A report that arrives
    // late, after a reconnect, loses to the one that overtook it.
    func (l *Latest) Add(u Update) bool {
      if old, ok := l.pending[u.Driver]; ok && old.Seq >= u.Seq {
        return false
      }
      if old, ok := l.written[u.Driver]; ok && old.Seq >= u.Seq {
        return false
      }
      l.pending[u.Driver] = u
      return true
    }
    
    // Drain returns the reports to write, in driver order, and empties the buffer. A driver who has
    // not moved far stays off the batch: a parked car costs no write.
    func (l *Latest) Drain() []Update {
      out := make([]Update, 0, len(l.pending))
      for d, u := range l.pending {
        if old, ok := l.written[d]; ok && geo.Distance(old.Lat, old.Lng, u.Lat, u.Lng) < l.MinMove {
          continue
        }
        l.written[d] = u
        out = append(out, u)
      }
      l.pending = map[int]Update{}
      slices.SortFunc(out, func(a, b Update) int { return cmp.Compare(a.Driver, b.Driver) })
      return out
    }
    
    Go: regions, search, sweepgo
    
    // Write stores a batch of reports in one round trip. GEOADD on a known member replaces its
    // position, so the index holds one entry per driver. A driver who crossed into a new region leaves
    // the old key in the same round trip. The seen set records the time of each report.
    func (r *Regions) Write(ctx context.Context, batch []Update, nowMS int64) error {
      byKey := map[string][]*redis.GeoLocation{}
      var moved []struct {
        key string
        id  string
      }
      seen := make([]redis.Z, 0, len(batch))
      r.mu.Lock()
      for _, u := range batch {
        key, id := r.Key(u.Lat, u.Lng), strconv.Itoa(u.Driver)
        byKey[key] = append(byKey[key], &redis.GeoLocation{Name: id, Latitude: u.Lat, Longitude: u.Lng})
        if old, ok := r.where[u.Driver]; ok && old != key {
          moved = append(moved, struct {
            key string
            id  string
          }{old, id})
        }
        r.where[u.Driver] = key
        seen = append(seen, redis.Z{Score: float64(nowMS), Member: id})
      }
      r.mu.Unlock()
      _, err := r.RDB.Pipelined(ctx, func(p redis.Pipeliner) error {
        for key, locs := range byKey {
          p.GeoAdd(ctx, key, locs...)
        }
        for _, m := range moved {
          p.ZRem(ctx, m.key, m.id)
        }
        if len(seen) > 0 {
          p.ZAdd(ctx, r.seenKey(), seen...)
        }
        return nil
      })
      if err != nil {
        return fmt.Errorf("write %d reports: %w", len(batch), err)
      }
      return nil
    }
    
    // Hit is a driver a search found, with the straight-line distance in metres.
    type Hit struct {
      Driver int
      Dist   float64
      Pos    geo.Point
    }
    
    // ByETA sorts hits by the time to reach the pickup, the fastest first. A search sorts by the
    // straight line; a car drives the streets.
    func ByETA(hits []Hit, pickup geo.Point) {
      slices.SortStableFunc(hits, func(a, b Hit) int { return cmp.Compare(ETA(a.Pos, pickup), ETA(b.Pos, pickup)) })
    }
    
    // Rings are the radii a search tries, in metres.
    var Rings = []float64{500, 1_000, 2_000, 4_000, 8_000}
    
    // Nearby widens the circle until it holds k drivers or reaches limit metres. A sorted GEOSEARCH
    // reads every member inside its circle, so a wide circle in a dense core is slow and blocks the
    // Redis event loop for every other client. A small circle answers the dense core at once, and only
    // a sparse area pays for the wider ones.
    func (r *Regions) Nearby(ctx context.Context, lat, lng, limit float64, k int) ([]Hit, int, error) {
      calls := 0
      for _, radius := range Rings {
        radius = min(radius, limit)
        hits, _, err := r.Search(ctx, lat, lng, radius, k)
        if err != nil {
          return nil, calls, err
        }
        calls++
        if len(hits) >= k || radius >= limit {
          return hits, calls, nil
        }
      }
      return nil, calls, nil
    }
    
    // Keys lists the regions that a circle touches: the region of the centre, and each neighbour whose
    // box meets the circle's box. A search near a border reads more than one region.
    func (r *Regions) Keys(lat, lng, radius float64) []string {
      cell := geo.Encode(lat, lng, RegionBits)
      keys := []string{r.cellKey(cell)}
      box := geo.BoundingBox(lat, lng, radius)
      near, ok := geo.Neighbours(cell, RegionBits)
      for i, c := range near {
        if ok[i] && geo.Decode(c, RegionBits).Intersects(box) {
          keys = append(keys, r.cellKey(c))
        }
      }
      return keys
    }
    
    // Search reads the nearest k drivers from every region the circle touches, in one round trip, and
    // merges them by distance.
    func (r *Regions) Search(ctx context.Context, lat, lng, radius float64, k int) ([]Hit, int, error) {
      keys := r.Keys(lat, lng, radius)
      cmds := make([]*redis.GeoSearchLocationCmd, len(keys))
      _, err := r.RDB.Pipelined(ctx, func(p redis.Pipeliner) error {
        for i, key := range keys {
          cmds[i] = p.GeoSearchLocation(ctx, key, &redis.GeoSearchLocationQuery{
            GeoSearchQuery: redis.GeoSearchQuery{Latitude: lat, Longitude: lng, Radius: radius, RadiusUnit: "m", Sort: "ASC", Count: k},
            WithDist:       true,
            WithCoord:      true,
          })
        }
        return nil
      })
      if err != nil {
        return nil, 0, fmt.Errorf("search %d regions: %w", len(keys), err)
      }
      var hits []Hit
      for _, c := range cmds {
        for _, l := range c.Val() {
          id, err := strconv.Atoi(l.Name)
          if err != nil {
            return nil, 0, fmt.Errorf("driver %q: %w", l.Name, err)
          }
          hits = append(hits, Hit{Driver: id, Dist: l.Dist, Pos: geo.Point{ID: id, Lat: l.Latitude, Lng: l.Longitude}})
        }
      }
      slices.SortFunc(hits, func(a, b Hit) int { return cmp.Or(cmp.Compare(a.Dist, b.Dist), cmp.Compare(a.Driver, b.Driver)) })
      return hits[:min(k, len(hits))], len(keys), nil
    }
    
    // Remove takes a driver out of the index, for example when a trip starts.
    func (r *Regions) Remove(ctx context.Context, driver int) error {
      id := strconv.Itoa(driver)
      r.mu.Lock()
      key, ok := r.where[driver]
      delete(r.where, driver)
      r.mu.Unlock()
      _, err := r.RDB.Pipelined(ctx, func(p redis.Pipeliner) error {
        if ok {
          p.ZRem(ctx, key, id)
        }
        p.ZRem(ctx, r.seenKey(), id)
        return nil
      })
      if err != nil {
        return fmt.Errorf("remove driver %d: %w", driver, err)
      }
      return nil
    }
    
    // Sweep removes every driver not seen since cutoffMS. A GEO member has no TTL of its own, because
    // it is a member of a sorted set, so a job has to do this.
    func (r *Regions) Sweep(ctx context.Context, cutoffMS int64) ([]int, error) {
      silent, err := r.RDB.ZRangeArgs(ctx, redis.ZRangeArgs{Key: r.seenKey(), Start: "-inf", Stop: "(" + strconv.FormatInt(cutoffMS, 10), ByScore: true}).Result()
      if err != nil {
        return nil, fmt.Errorf("find silent drivers: %w", err)
      }
      out := make([]int, 0, len(silent))
      for _, s := range silent {
        id, err := strconv.Atoi(s)
        if err != nil {
          return nil, fmt.Errorf("driver %q: %w", s, err)
        }
        if err := r.Remove(ctx, id); err != nil {
          return nil, err
        }
        out = append(out, id)
      }
      return out, nil
    }
    
    searchpseudo code
    nearby(pickup, k):
      FOR r IN 500 m, 1 km, 2 km, 4 km, 8 km1:
        keys = regions that the circle of r touches2
        hits = GEOSEARCH each key BYRADIUS r ASC COUNT k
        IF k hits found: RETURN merged by distance
      RETURN what was found
    1. 1A sorted GEOSEARCH reads every member in the circle. In the lab core, 500 m already held 20 drivers.
    2. 2A 500 m circle reads 1.46 keys on average; a 3 km circle reads 5.02.

    I keep the newest position only and write in batches. I shard by region, and I search small circles first: 0.5 ms in the core, against 6.1 ms for 3 km.

    I

    Deep dive: greedy or batched

    who gets which driver
    mean pickup, road metres; "now" is greedy, the others are batch windows439now4392 s4355 s44015 smany idle drivers40 a minute, 42% busy903now8792 s8885 s86115 sfew idle drivers70 a minute, 80% busy2,993now1,5412 s1,5025 s1,43915 smore riders than drivers85 a minute, 98% busy
    supplymethodmean pickupwait for a matchriders served
    Many idleGreedy439 m0.0 s100.0%
    5 s batch435 m2.0 s100.0%
    Few idleGreedy903 m0.1 s100.0%
    15 s batch861 m7.0 s100.0%
    Too fewGreedy2,993 m82.5 s76.7%
    5 s batch1,502 m30.7 s90.5%
    methodstatususe it when
    Greedy nearest, at onceMany idleMost riders have a driver close by
    Batch, lowest total costShort supplyRiders queue for few drivers
    Batch with a long windowFew idleA 15 s window adds about 7 s of wait
    Fixed region quotaNot approvedSupply moves faster than a quota
    • Under short supply, greedy serves the oldest rider, however far away. A batch chooses which rider gets each freed driver.
    • The total falls, but a single rider can get a longer pickup than greedy gave. Cap the cost per rider to limit that.
    • Switch per region: batch where the queue is long, and match at once where it is empty.

    Simulation: 1,000 drivers, a 16 km square city, 45 minutes, the first 15 ignored, 4 seeds. Every method meets the same riders. Pickups are from the true position. The rates of 40, 70 and 85 requests a minute give 42%, 80% and 98% of drivers busy.

    batched assignmentpseudo code
    every 5 s, per region:
      riders  = requests not yet matched
      FOR EACH rider: GEOSEARCH 20 nearest idle drivers
      cost[rider][driver] = road ETA from the last report1
      plan = lowest total cost (Hungarian method, O(n³)2)
      FOR EACH pair (rider, driver) in plan:
        send an offer
      riders with no pair wait for the next batch3
    
    greedy, for comparison:
      FOR EACH rider in request order:
        take the nearest free driver4
    1. 1The dispatcher sees reports, not cars. The run measures the pickup from where the car really is.
    2. 2Measured: 0.16 ms for 50 riders, 2.3 ms for 200, 21 ms for 500. Fast enough, because one region batches few riders. Tests compare it with brute force.
    3. 3A rider with no pair keeps their place. A rider who waits too long gives up, which the simulation counts.
    4. 4An early rider can take the only driver near a later rider. Panel L shows one such batch.
    Tested source Go: assignment · Go: greedy · Go: one run of the city
    Go: assignmentgo
    
    // Assign finds the assignment with the lowest total cost (the Hungarian method, O(n²m)). Each row
    // gets one column and no column is used twice. With more rows than columns, some rows get -1.
    func Assign(cost [][]float64) []int {
      n := len(cost)
      if n == 0 {
        return nil
      }
      m := len(cost[0])
      if n > m { // solve the transpose: every column gets a row
        t := make([][]float64, m)
        for j := range t {
          t[j] = make([]float64, n)
          for i := range n {
            t[j][i] = cost[i][j]
          }
        }
        out := make([]int, n)
        for i := range out {
          out[i] = -1
        }
        for j, i := range Assign(t) {
          out[i] = j
        }
        return out
      }
      // Potentials u, v keep cost - u - v >= 0, and an augmenting path adds one row at a time.
      u, v := make([]float64, n+1), make([]float64, m+1)
      match, way := make([]int, m+1), make([]int, m+1) // match[j]: the row in column j
      for i := 1; i <= n; i++ {
        match[0] = i
        j0 := 0
        minv := make([]float64, m+1)
        used := make([]bool, m+1)
        for j := range minv {
          minv[j] = math.Inf(1)
        }
        for {
          used[j0] = true
          i0, delta, j1 := match[j0], math.Inf(1), 0
          for j := 1; j <= m; j++ {
            if used[j] {
              continue
            }
            if c := cost[i0-1][j-1] - u[i0] - v[j]; c < minv[j] {
              minv[j], way[j] = c, j0
            }
            if minv[j] < delta {
              delta, j1 = minv[j], j
            }
          }
          for j := 0; j <= m; j++ {
            if used[j] {
              u[match[j]] += delta
              v[j] -= delta
            } else {
              minv[j] -= delta
            }
          }
          j0 = j1
          if match[j0] == 0 {
            break
          }
        }
        for j0 != 0 {
          j1 := way[j0]
          match[j0] = match[j1]
          j0 = j1
        }
      }
      out := make([]int, n)
      for j := 1; j <= m; j++ {
        if match[j] > 0 {
          out[match[j]-1] = j - 1
        }
      }
      return out
    }
    
    Go: greedygo
    
    // Greedy serves rows in order. Each row takes the cheapest column still free. It returns the column
    // of each row, or -1 where none is left. The cost is what a first-come, first-served dispatcher pays.
    func Greedy(cost [][]float64) []int {
      out := make([]int, len(cost))
      used := map[int]bool{}
      for i, row := range cost {
        out[i] = -1
        best := math.Inf(1)
        for j, c := range row {
          if !used[j] && c < best {
            best, out[i] = c, j
          }
        }
        if out[i] >= 0 {
          used[out[i]] = true
        }
      }
      return out
    }
    
    Go: one run of the citygo
    
    // Run plays the city second by second on a real Redis GEO key. Idle drivers move and report their
    // position. Riders appear at seeded times. A match takes the candidates from GEOSEARCH and ranks
    // them by the last reported position, because that is all a dispatcher knows. The pickup a rider
    // gets is measured from the true position.
    func Run(ctx context.Context, rdb *redis.Client, key string, cfg Config) (Result, error) {
      s := &sim{cfg: cfg, ctx: ctx, rdb: rdb, key: key, arrive: riders(cfg)}
      if err := rdb.Del(ctx, key).Err(); err != nil {
        return Result{}, fmt.Errorf("clear %s: %w", key, err)
      }
      start := geo.City(cfg.Drivers, cfg.HalfM, cfg.Seed+1)
      s.drivers = make([]driver, cfg.Drivers)
      for i := range s.drivers {
        m := rand.New(rand.NewPCG(cfg.Seed, uint64(i)+1000)) // each driver has their own stream
        s.drivers[i] = driver{pos: start[i], head: m.Float64() * 2 * math.Pi, legLeft: 30 + m.IntN(150), moves: m}
      }
      if err := s.report(0, true); err != nil {
        return Result{}, err
      }
      end := cfg.Minutes * 60
      warm := cfg.WarmupMin * 60
      for t := 1; t <= end; t++ {
        s.move(t)
        if err := s.report(t, false); err != nil {
          return Result{}, err
        }
        for s.next < len(s.arrive) && s.arrive[s.next].at <= t {
          s.pending = append(s.pending, s.arrive[s.next])
          s.next++
          if t > warm {
            s.res.Requests++
          }
        }
        if cfg.WindowS == 0 || t%cfg.WindowS == 0 {
          if err := s.match(t, warm); err != nil {
            return Result{}, err
          }
        }
        s.expire(t, warm)
        if t > warm {
          busy := 0
          for i := range s.drivers {
            if s.drivers[i].busyUntil > t {
              busy++
            }
          }
          s.busy += float64(busy) / float64(cfg.Drivers)
          s.ticks++
        }
      }
      return s.finish(), nil
    }
    
    // match gives the pending riders drivers, greedily or as one batch.
    func (s *sim) match(t, warm int) error {
      if len(s.pending) == 0 {
        return nil
      }
      cands, order, err := s.candidates()
      if err != nil {
        return err
      }
      if len(order) == 0 {
        return nil
      }
      col := map[int]int{}
      for j, d := range order {
        col[d] = j
      }
      const none = 1e9 // not a candidate of this rider
      cost := make([][]float64, len(s.pending))
      for i, r := range s.pending {
        cost[i] = make([]float64, len(order))
        for j := range cost[i] {
          cost[i][j] = none
        }
        for _, d := range cands[i] {
          cost[i][col[d]] = s.cost(d, r)
        }
      }
      var picked []int
      if s.cfg.WindowS == 0 {
        picked = Greedy(cost)
      } else {
        picked = Assign(cost)
      }
      var gone []int
      var rest []rider
      for i, r := range s.pending {
        j := picked[i]
        if j < 0 || cost[i][j] >= none {
          rest = append(rest, r)
          continue
        }
        d := order[j]
        s.assign(d, r, cands[i], t, warm)
        gone = append(gone, d)
      }
      s.pending = rest
      if len(gone) == 0 {
        return nil
      }
      names := make([]any, len(gone))
      for i, d := range gone {
        names[i] = d
      }
      if err := s.rdb.ZRem(s.ctx, s.key, names...).Err(); err != nil {
        return fmt.Errorf("remove matched drivers: %w", err)
      }
      return nil
    }
    

    Batching gains little when drivers are plentiful. When riders outnumber drivers, a 5 s window cut the mean pickup from 2,993 m to 1,502 m, and it served 91% of riders, not 77%.

    J

    Deep dive: one driver, one trip

    offers, leases, conditional updates
    driver acceptscar at pickuprider in cartrip endsrequestedmatchedarrivedin progresscompleteddriver cancels: find anothercancelledrider or driver, or no-show
    designstatusdouble bookedoffers refusedstopped by lease
    Read, then writeNot approved16 drivers--
    Conditional update, unique indexApproved064-
    Lease, then bothApproved0089
    Lease aloneNot approvedAn expired or lost lease allows a second trip
    • A lease can expire or vanish in a failover, so it can never be the only guard (T6).
    • The lease outlives the offer by 5 s, so a late reply still finds it.
    • Offer to one driver at a time. Two offers for one trip leave one driver with an empty promise.
    • An expiry needs no timer: the accept compares expires_at with the time. A job only tidies rows.

    Lab: 300 riders, 60 drivers, 32 dispatchers in parallel, real Redis and Postgres. Each guarded run matched all 60 drivers once. Counts vary between runs. The same test passes under the race detector. Tests also fire 16 taps at one offer and race a cancel against an accept 60 times.

    offer and acceptpseudo code
    dispatch(trip):
      FOR EACH candidate, best ETA first:
        IF NOT SET lease:driver token NX PX 200001: CONTINUE
        INSERT offer, expires in 15 s          // 1 open offer per driver
        wait for the reply
        RELEASE the lease IF it still holds token
        IF accepted: RETURN the driver
      RETURN no driver
    
    accept(offer, driver, now):
      IN ONE TRANSACTION:
        UPDATE offers SET state = 'accepted'
          WHERE id = offer AND state = 'pending' AND expires_at > now2
        UPDATE trips SET state = 'matched', driver_id = driver
          WHERE id = trip AND state = 'requested'3
      0 rows: offer gone, or the rider cancelled
      a repeat of a win: return the same trip4
    1. 1A fast filter, about one Redis call. A dispatcher that loses it moves to the next candidate.
    2. 2The time is part of the condition, so a late tap changes 0 rows.
    3. 3A rider who cancelled first wins. The transaction then rolls the offer back too.
    4. 4The phone cannot tell a lost reply from a failure. A safe repeat removes the question.
    Tested source Go: dispatch · Go: accept · SQL: win the offer, then the trip · Go: trip steps
    Go: dispatchgo
    
    // Dispatch offers the trip to one driver at a time, nearest first by ETA. The lease in Redis stops a
    // second dispatcher from offering the same driver during the offer window. It is a fast filter:
    // the conditional updates in Accept and the unique indexes are what make the match correct.
    func (d *Dispatcher) Dispatch(ctx context.Context, trip int64, pickup geo.Point, now time.Time, ask func(driver int) Reply) (int, time.Time, error) {
      hits, _, err := d.Index.Nearby(ctx, pickup.Lat, pickup.Lng, d.Radius, d.Count)
      if err != nil {
        return 0, now, err
      }
      ByETA(hits, pickup)
      token := d.Token + ":" + strconv.FormatInt(trip, 10)
      for _, h := range hits {
        if !d.NoLease {
          ok, err := distlocks.TryLock(ctx, d.RDB, LeaseName(h.Driver), token, d.OfferTTL+d.Grace)
          if err != nil {
            return 0, now, fmt.Errorf("lease driver %d: %w", h.Driver, err)
          }
          if !ok {
            d.log("lease", h.Driver, "held by another dispatcher")
            continue
          }
          d.log("lease", h.Driver, "taken")
        }
        won, next, err := d.offer(ctx, trip, h.Driver, now, ask)
        now = next
        if !d.NoLease {
          if _, uerr := distlocks.Unlock(ctx, d.RDB, LeaseName(h.Driver), token); uerr != nil {
            return 0, now, fmt.Errorf("release driver %d: %w", h.Driver, uerr)
          }
        }
        if err != nil {
          return 0, now, err
        }
        if won {
          return h.Driver, now, nil
        }
      }
      return 0, now, ErrNoDriver
    }
    
    // offer runs one offer to its end. It returns true when the driver has the trip.
    func (d *Dispatcher) offer(ctx context.Context, trip int64, driver int, now time.Time, ask func(int) Reply) (bool, time.Time, error) {
      id, err := d.Store.CreateOffer(ctx, trip, driver, now.Add(d.OfferTTL))
      if errors.Is(err, ErrBusy) {
        d.log("offer", driver, "refused: driver is busy")
        return false, now, nil
      }
      if err != nil {
        return false, now, err
      }
      switch ask(driver) {
      case Accepts:
        if _, err := d.Store.Accept(ctx, id, driver, now); errors.Is(err, ErrBusy) || errors.Is(err, ErrGone) {
          d.log("accept", driver, "refused: 0 rows")
          return false, now, d.Store.CloseOffer(ctx, id, "withdrawn")
        } else if err != nil {
          return false, now, err
        }
        err := d.Index.Remove(ctx, driver)
        d.log("accept", driver, "won: 1 row")
        return true, now, err
      case Declines:
        err := d.Store.CloseOffer(ctx, id, "declined")
        d.log("offer", driver, "declined")
        return false, now, err
      default:
        now = now.Add(d.OfferTTL)
        if _, err := d.Store.ExpireOffer(ctx, id, now); err != nil {
          return false, now, err
        }
        d.log("offer", driver, "expired")
        return false, now, nil
      }
    }
    
    Go: acceptgo
    
    // Accept turns an open offer into a matched trip, in one transaction with two conditional updates.
    // The offer moves only if it is pending and not expired; the trip moves only if it is still
    // requested. A repeat of a call that won returns the same trip, so a phone can retry after a lost
    // reply. The partial unique index refuses a driver who already has an active trip.
    func (s Store) Accept(ctx context.Context, offer int64, driver int, now time.Time) (trip int64, err error) {
      tx, err := s.DB.Begin(ctx)
      if err != nil {
        return 0, fmt.Errorf("begin: %w", err)
      }
      defer func() {
        if rerr := tx.Rollback(ctx); rerr != nil && !errors.Is(rerr, pgx.ErrTxClosed) {
          err = errors.Join(err, fmt.Errorf("rollback accept: %w", rerr))
        }
      }()
    
      err = tx.QueryRow(ctx, sqls["win_offer"], offer, driver, now).Scan(&trip)
      if errors.Is(err, pgx.ErrNoRows) {
        return s.repeatedAccept(ctx, tx, offer, driver)
      }
      if isUnique(err) {
        return 0, ErrGone // another offer of this trip won at the same moment
      }
      if err != nil {
        return 0, fmt.Errorf("win offer: %w", err)
      }
      tag, err := tx.Exec(ctx, sqls["win_trip"], trip, driver)
      if isUnique(err) {
        return 0, ErrBusy
      }
      if err != nil {
        return 0, fmt.Errorf("win trip: %w", err)
      }
      if tag.RowsAffected() == 0 {
        return 0, ErrGone // the rider cancelled first; the rollback undoes the offer
      }
      if err := tx.Commit(ctx); err != nil {
        return 0, fmt.Errorf("commit accept: %w", err)
      }
      return trip, nil
    }
    
    func (s Store) repeatedAccept(ctx context.Context, tx pgx.Tx, offer int64, driver int) (int64, error) {
      var state string
      var trip int64
      err := tx.QueryRow(ctx, sqls["offer_state"], offer, driver).Scan(&state, &trip)
      if errors.Is(err, pgx.ErrNoRows) {
        return 0, ErrGone
      }
      if err != nil {
        return 0, fmt.Errorf("read offer: %w", err)
      }
      if state == "accepted" {
        return trip, nil
      }
      return 0, ErrGone
    }
    
    SQL: win the offer, then the tripsql
    UPDATE offers SET state = 'accepted'
    WHERE id = $1 AND driver_id = $2 AND state = 'pending' AND expires_at > $3
    RETURNING trip_id;
    
    UPDATE trips SET state = 'matched', driver_id = $2, version = version + 1
    WHERE id = $1 AND state = 'requested';
    Go: trip stepsgo
    
    // Legal lists the steps a trip may take. A driver who cancels before arrival puts the trip back
    // to requested, so a dispatcher can find another driver.
    var Legal = map[State][]State{
      Requested:  {Matched, Cancelled},
      Matched:    {Arrived, Requested, Cancelled},
      Arrived:    {InProgress, Cancelled},
      InProgress: {Completed},
    }
    
    
    
    // Move takes one step of the state machine with a conditional update. It returns true if this call
    // made the step. A repeat of a step already made returns false and no error, so a retried event is
    // harmless. A step from any other state returns ErrStale, and a step the machine does not have
    // returns ErrIllegal.
    func (s Store) Move(ctx context.Context, trip int64, from, to State) (bool, error) {
      if !slices.Contains(Legal[from], to) {
        return false, ErrIllegal
      }
      tag, err := s.DB.Exec(ctx, sqls["move_trip"], trip, string(from), string(to))
      if err != nil {
        return false, fmt.Errorf("move trip %d: %w", trip, err)
      }
      if tag.RowsAffected() == 1 {
        return true, nil
      }
      var now string
      if err := s.DB.QueryRow(ctx, sqls["trip_state"], trip).Scan(&now); err != nil {
        return false, fmt.Errorf("read trip %d: %w", trip, err)
      }
      if State(now) == to {
        return false, nil
      }
      return false, fmt.Errorf("%w: trip %d is %s, not %s", ErrStale, trip, now, from)
    }
    

    A lease in Redis stops wasted offers. A conditional update and a partial unique index in Postgres make the match correct, even if Redis lies.

    K

    Deep dive: ETA, surge, reconnects

    the parts around the match
    ETA methodstatususe
    Straight line ÷ speedFirst filter onlyWrong pick in 13% of matches, about 64 m worse each
    Road model by cell and hourApprovedRanking many candidates
    Routing service, live trafficFew candidatesThe final choice and the rider's screen
    cellopen requestsidle driverssurge
    tdr1x6629×2.3
    tdr1w14264×2.2
    tdr1s2318×1.3
    tdr1v6871×1.0
    tdr1t4041×1.0

    One seeded moment: 450 requests with a spike near one hub, 400 idle drivers. 3 of 16 cells priced above 1. The rule is an illustration; a pricing team fits it to how riders and drivers respond.

    phone comes back and ...server says
    Has an active tripThe trip and its state, from Postgres
    Had an offer, still openThe offer and the time left
    Had an offer, now expiredIdle. The trip went to someone else
    Sends old positionsOlder reports lose to newer ones
    Was swept from the indexThe next report puts it back
    eta, surge, resumepseudo code
    eta(driver, pickup):
      rough = road distance / speed by cell and hour   // cheap, for ranking1
      exact = routing service                          // for the rider's screen
    
    surge(cell):                                       // an illustration
      ratio = open requests / idle drivers
      RETURN max(1, min(3, ratio rounded to 0.12))
    
    resume(driver), first call after a reconnect:
      active trip?  show it3
      open offer?   show it, with the time left
      otherwise     idle: report a position again
    1. 1The lab ranks by a street grid at a fixed speed, a stand-in for this model.
    2. 2A step per 0.1 keeps a price from flickering. A real system also smooths it over time.
    3. 3The phone holds no truth. It asks, and the server answers from Postgres.
    Tested source Go: resume · Go: surge by cell
    Go: resumego
    
    // Resume answers the first call from a phone that reconnects. The server state decides what the
    // app shows: the active trip, the offer that is still open, or nothing. The phone holds no truth.
    func (s Store) Resume(ctx context.Context, driver int, now time.Time) (Status, error) {
      var st Status
      var state string
      err := s.DB.QueryRow(ctx, sqls["resume_trip"], driver).Scan(&st.Trip, &state)
      if err == nil {
        st.Kind, st.State = "trip", State(state)
        return st, nil
      }
      if !errors.Is(err, pgx.ErrNoRows) {
        return st, fmt.Errorf("resume trip: %w", err)
      }
      err = s.DB.QueryRow(ctx, sqls["resume_offer"], driver, now).Scan(&st.Offer, &st.Trip)
      if err == nil {
        st.Kind = "offer"
        return st, nil
      }
      if !errors.Is(err, pgx.ErrNoRows) {
        return st, fmt.Errorf("resume offer: %w", err)
      }
      return Status{Kind: "idle"}, nil
    }
    
    Go: surge by cellgo
    
    // Surge is the price multiplier of a cell: demand over supply, between 1 and a cap, in steps of 0.1.
    // The rule is an illustration. A real pricing team fits it to how riders and drivers respond.
    func Surge(demand, supply int) float64 {
      if demand == 0 {
        return 1
      }
      ratio := float64(demand) / float64(max(supply, 1))
      return max(1, min(3, math.Round(ratio*10)/10))
    }
    
    // Cells counts requests and idle drivers per geohash cell. A job runs this every few seconds and
    // stores the result, so a price lookup reads one key.
    func Cells(requests, idle []geo.Point, bits int) []Cell {
      type tally struct{ d, s int }
      at := map[uint64]*tally{}
      get := func(p geo.Point) *tally {
        c := geo.Encode(p.Lat, p.Lng, bits)
        if at[c] == nil {
          at[c] = &tally{}
        }
        return at[c]
      }
      for _, p := range requests {
        get(p).d++
      }
      for _, p := range idle {
        get(p).s++
      }
      out := make([]Cell, 0, len(at))
      for c, t := range at {
        out = append(out, Cell{Code: geo.String(c, bits), Box: geo.Decode(c, bits), Demand: t.d, Supply: t.s, Surge: Surge(t.d, t.s)})
      }
      slices.SortFunc(out, func(a, b Cell) int { return cmp.Compare(a.Code, b.Code) })
      return out
    }
    

    I rank with a cheap ETA and show a routed one. I price surge per cell and fix it at request time. After a reconnect, the server tells the phone what is true.

    L

    See it: step through a dispatch

    recorded from real Redis and Postgres
    1 km
    step 1 of 19t = 0 s
    1. requested
    2. matched
    3. arrived
    4. in progress
    5. completed

    A rider asks for a car. Postgres stores the trip as requested.

    offer tostate in Postgres
    No offers yet.

    40 of 40 drivers in the index · trip version 1

    • idle
    • under another lease
    • offered
    • no answer or declined
    • matched

    Each frame is what the lab read back after that step, in a seeded city of 40 drivers. The drivers do not move in this view, so the steps stay easy to follow. The best ETA was 69 s, driver 9, 551 m by road.

    The nearest driver was under another lease, the next stayed silent, the third declined, and the fourth accepted. Every step left the trip in a known state.

    M

    Failure cases

    what breaks, and why trips stay right
    eventresultwhy it is safesaved by
    Two dispatchers pick one driverBoth try to offer.The lease stops one. If it fails, the unique index does.Unique index
    A driver stays silentThe offer waits.It expires in 15 s, and the next candidate gets one.expires_at
    A late accept arrivesThe offer has expired.The condition fails: 0 rows, and the app says the trip is gone.Conditional update
    Accept and cancel raceBoth act on one trip.One conditional update wins; the lab ran this 60 times.Row lock
    Redis fails over and loses keysPositions and leases vanish.Reports rebuild the index in about 4 s. Postgres still guards every match.Unique index
    A driver loses signalThey stay in the index.The sweeper removes them after 30 s; an offer to them expires.Seen set
    A dispatcher dies with a leaseThe driver looks taken.The lease ends in 20 s; another dispatcher takes the region.Lease TTL
    Old reports arrive after a reconnectThey could move the car back.Each report has a sequence number; older reports lose.seq
    A surge job stopsMultipliers go stale.They expire, and the price falls back to 1.TTL
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1GEO key, Postgres2+ gateway batches3+ regions, leases4+ batch matching5+ city shardsmore load →
    Capacity against this prompt's demand1001k10k100k1MDemand: updates, world: 250,000 operations per secondDemand: updates, world250,000Demand: updates, one city: 25,000 operations per secondDemand: updates, one city25,000Demand: requests, world: 694 operations per secondDemand: requests, world694Redis: updates, single: 26,241 operations per secondRedis: updates, single26,241Redis: updates, batched: 280,600 operations per secondRedis: updates, batched280,600Redis: search, core: 2,204 operations per secondRedis: search, core2,204Redis: search, suburb: 16,116 operations per secondRedis: search, suburb16,116Postgres: one match: 6,492 operations per secondPostgres: one match6,492operations per second, log scale
    stepaddit handlesmove up when you see
    1One GEO key per city, greedy matching, Postgres with conditional updates.About 26k single updates and 2,200 core searches a second.Updates near that rate, about 100k drivers.
    2Gateways that keep the newest report and write batches.About 281k updates a second on one Redis.Searches and updates slow each other in a dense core.
    3Region keys, a dispatcher per region, leases.Busy regions move to their own nodes. Searches read 1.46 keys on average.Riders queue in a region and pickups grow long.
    4Batched assignment where supply is short.Half the pickup, and 91% of riders served, not 77%, in the short-supply run.One Postgres cannot take the match writes, or one region fails.
    5Shards by city: Redis and Postgres per city, a global account service (X2).One city failing leaves the others running. 694 peak requests spread over cities.Top of the ladder.

    Demand from panel C. Capacity measured in the lab on 100,000 seeded drivers, 8 clients, one shared 8-core laptop. Repeat runs varied, so read these as orders of magnitude. One match is a trip, an offer and an accept.

    I start with one GEO key and greedy matching, with Postgres guarding every trip. I add batched ingest, then regions, and I batch matches only where supply is short.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    Why not a quadtree or H3 instead of Redis GEO?A quadtree adapts to density in process memory. Hexagons give equal neighbour distances, which suits surge. Redis GEO needs no code and survives a dispatcher restart.B11
    How does the rider see the car move?The gateway forwards the driver's reports to the rider's socket during a trip. It can drop frames, because only the newest position matters.C6
    A dispatcher for a region dies. Now what?A lease on the region lets another dispatcher take over within seconds. Open offers live in Postgres, so nothing is lost.X6
    How do you bill surge fairly?Fix the multiplier on the trip at request time. The rider confirms that price, and later changes cannot touch it.T9
    How do you run this in several regions of the world?Each city lives in one region, because riders and drivers there are near each other. Only accounts need global reach.X2
    How do you store location history?Send every report to a partitioned log, then to object storage for analysis. The index never holds history.B6
    How do you test matching changes?Replay recorded requests through the new logic in a simulation, then run a test by region. A rider's experience is the metric.O4
    P

    Drill

    predict, then reveal

    0 of 10 known

    1. A phone sends a position every 4 s. Why store only the newest one in the index?

    2. Two dispatchers see one idle driver. What stops a double booking?

    3. If the database alone is correct, why keep the lease?

    4. A driver taps accept twice because the reply was lost. What happens?

    5. A driver taps accept one second after the offer expired. What happens?

    6. Does batching always beat greedy nearest?

    7. Why did the same fleet serve 91% of riders with batching, against 77% greedy?

    8. Why not search 3 km around every rider?

    9. Why rank by road ETA and not by straight line?

    10. A driver loses signal and never reports again. What removes them from the index?

    Q

    Numbers to say

    measured, derived or simulated
    demand
    250k updates and about 694 requests a second at peak.
    index
    80 B a driver: 80 MB for 1 M.
    updates
    26k a second one by one; 281k in batches of 100.
    search
    0.5 ms at 500 m; 6.1 ms at 3 km, in the core.
    staleness
    Reports every 4 s: 7 m off. Every 60 s: 109 m.
    batching
    Short supply: 2,993 → 1,502 m. Many idle: no gain.
    solver
    2.3 ms for 200 riders.
    one match
    About 6,500 a second in Postgres.
    a batch
    Largest recorded gap: 15,915 m greedy, 10,383 m assigned.

    Redis 8 and Postgres 16 on an 8-core laptop shared with other jobs. The simulation is seeded and repeats exactly; rates vary between runs.