Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 28 of 44

Case study: design a ride-hailing service

A senior-level walkthrough of a ride-hailing service: a driver index that takes 250,000 reports a second, batched matching, reservations that prevent double booking, road ETAs, surge pricing and failure modes, with tested C#.

Case studyApplied44 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 2 data models
  • 2 API designs
  • 8 code samples
  • 10 interviewer follow-ups
  • 4 self-checks

Read first: A framework for system design interviews, Case study: design a proximity service

By the end you will be able to
  • Treat driver locations as ephemeral, in-memory state. Change the cell map only when a driver crosses a cell boundary (7% of reports with 500 m cells), and rebuild it from the stream after a failure.
  • Batch matching over a short window beats nearest-first when supply is tight, in the simulation by 19% on mean pickup distance and 34% on the worst pickup.
  • Prevent double booking with a compare-and-set reservation and a versioned ride state machine, and compensate when one side loses a race.
  • Retrieve candidates by straight-line distance and rank a short list by road ETA, because the straight-line nearest was the quickest to reach in only 86% of requests.
  • Pin quotes, smooth surge inputs by cell and by time, and prepare the senior answers on stadium crowds, a lost region and experiments that interfere.
Prefer to watch? · 11 min video

8 code samples (431 lines), collapsed so the explanation stays in focus.

A ride-hailing service looks like a map with cars on it. Underneath is a real-time marketplace with three hard problems: tracking a few hundred thousand moving drivers cheaply, deciding which driver serves which rider while thousands of other decisions happen at the same moment, and never letting two riders hold the same driver. Money, safety and trust sit on top. This lesson builds the design in that order and tests the key pieces in C#: a driver index that absorbs a quarter of a million location reports a second, batched matching, a reservation that cannot be double-booked, and road-based ETAs.

It uses the geospatial ideas from designing a proximity service (cells, covers, why a fixed cell map suits points that move) and the retry and ordering ideas from API design. For the live updates to the rider's phone, see designing a chat system, which solves the same problem of holding connections open.

HLD

Clarify the problem

Spend the first minutes on questions. Each answer changes the design.

AskWhy it matters
Which flows are in scope: request, match, track, pay, rate?Matching and location are the core. Payments, maps and ratings are services this design calls, and each has its own lesson
Single rides only, or shared rides and scheduled rides too?Sharing turns matching into routing with detours, which is a much harder problem. Scope it out and say so
What matters most when supply is short: wait time, driver earnings, fairness?It decides the objective of the matching step
How accurate must ETAs and prices be?A road-based ETA needs a routing engine. A price shown must be the price charged
Where do we run: one city or the world?Cities are nearly independent markets, which is the natural way to shard
What must never happen?A driver on two rides, a rider charged twice, a ride stuck in a state that nobody owns

A good scope for 45 minutes: a rider requests a ride, the system matches a nearby driver, both see each other move, the trip is priced and completed. Mention surge pricing, payments and fraud as extensions you will touch.

HLD

Estimate: the location reports are the write load

State assumptions out loud. They are illustrative and the interviewer may change them.

Example · estimate
drivers:      1M online at peak (assumed), one report every 4 s
reports:      1M / 4 s = 250,000 a second
payload:      ~100 B each = 25 MB/s, ~2.2 TB/day if everything were kept
cell moves:   ~7% of reports (500 m cells, measured below) = ~18,000/s
index size:   1M drivers x ~100 B = ~100 MB, which fits in memory
rides:        20M a day = ~230/s on average, ~1,200/s at peak (x5)
offers:       ~3 per ride = ~3,600/s at peak
ride rows:    20M x 2 KB = ~40 GB a day, ~10 state changes per ride

Five conclusions:

  1. The location reports are the write load, not the rides. 250,000 reports a second against 230 rides a second means driver positions must never travel through the transactional ride store. They go to memory.
  2. The index is tiny. A hundred megabytes holds every driver. Scale here means write throughput: 250,000 updates a second spread over tens of nodes, not storage.
  3. Most reports change nothing in the index. A driver at 30 km/h covers about 33 m in 4 seconds, so a report only crosses into another cell now and then. The experiment below puts it at 7.4% for 500 m cells. The latest position is overwritten in place, and the cell map changes rarely.
  4. The ride store is modest. 1,200 rides a second at the peak with ten state changes each is 12,000 small writes a second, which a sharded transactional database handles without trickery, as long as each ride is one row with a version.
  5. Peaks are local and sudden. A stadium emptying puts thousands of requests in a few cells within minutes. Design for hot cells, not only for the average city.

LLD

The contract and the data model

CallWho calls itMeaning
POST /v1/ridesRider appRequest a ride. The price quote is attached
GET /v1/rides/{id}Rider appThe state, the driver and the ETA, as a fallback to the pushed updates
POST /v1/rides/{id}/cancelRider or driver appCancel. What it costs depends on the state
PUT /v1/drivers/me/locationDriver appA location report, sent over a long-lived connection
POST /v1/offers/{id}/acceptDriver appAccept an offered ride
POST/v1/rides
auth
rider token
idempotency
Idempotency-Key header, so a double tap creates one ride
body
{ "pickup": { "lat": 37.7749, "lon": -122.4194 }, "dropoff": { "lat": 37.7849, "lon": -122.4094 }, "product": "standard", "quote_id": "q_71f" }
note
the quote id pins the price the rider saw, so surge cannot change between the quote and the request
  • 202accepted, returns { "ride_id": "r_91c", "state": "matching" }
  • 409the rider already has an active ride
  • 422the quote has expired, ask for a new one
PUT/v1/drivers/me/location
auth
driver token
body
{ "lat": 37.7751, "lon": -122.4189, "heading": 90, "speed": 8.3, "status": "available", "seq": 1042 }
note
sent about every 4 seconds over one open connection, and the sequence number lets the server drop a report that arrives late
  • 204recorded
ridesSQL, sharded by city or ride id
  • idbigint

    PK
  • rider_idbigint

    INDEX
  • driver_idbigint

    set when a driver is assigned

    NULLINDEX
  • statetext

    requested, matching, driver_assigned, driver_arrived, in_progress, completed, cancelled

  • versionint

    bumped on every change: a writer must present the version it read

  • pickup_latdouble

  • pickup_londouble

  • dropoff_latdouble

  • dropoff_londouble

  • quote_idtext

    the price the rider was shown, fixed when the ride was requested

  • fare_centsbigint

    computed from the trip trace when it completes

    NULL
  • requested_attimestamptz

  • updated_attimestamptz

One row per ride. Every change is a conditional update on (id, version), and the transition table says what may follow what.

offersSQL or key-value, short-lived
  • idbigint

    PK
  • ride_idbigint

    INDEX
  • driver_idbigint

  • statetext

    pending, accepted, declined or expired

  • expires_attimestamptz

    about 15 seconds after the offer is sent

Driver positions have no table at all: they live in memory and are rebuilt from the report stream.

The absence of a driver-location table is deliberate. A position is wrong within seconds, there are 250,000 writes a second, and nobody needs yesterday's idle positions. Only the positions during a trip are kept, in a stream, because they decide the fare and settle disputes.

HLD

The high-level design

Fig. Ride hailing: fast ephemeral side, durable ride side, matching in between
Fig. Ride hailing: fast ephemeral side, durable ride side, matching in between
Fig. From request to pickup
Fig. From request to pickup

Read it as two sides joined by a short, careful handshake. The Location service terminates the driver connections, drops reports that arrive out of order, overwrites the latest position and moves a driver between cells only when the cell changed. The Driver index is a sharded, in-memory map that exists for one purpose, answering "which available drivers are near here". The Ride service owns the durable ride: a state machine with a version, behind a transactional store. Matching is stateless: it asks the index for candidates, asks the ETA service to rank a short list, reserves a driver and sends the offer, and only then asks the Ride service to record the assignment.

Order matters in that last step. Reserving first and then recording means a crash in between leaves a held driver and an unassigned ride, which a lease will release. Recording first and then reserving would leave a ride that claims a driver who may be taken by another ride, which is the failure the design exists to prevent.

LLD

Deep dive: location reports and the driver index

A report carries a position, a heading and a status. The Location service must do four things cheaply: drop a stale or reordered report, overwrite the driver's latest position, check whether the driver's cell changed, and only if it did, move the driver between cells. The code below is that index over a plain square grid of meters. In production the cells are the geohash, S2 or H3 cells from the proximity lesson. Over one city the plane is flat enough for the logic to be identical, and a grid keeps the sample short.

C# · DriverStatus, DriverIndex73 lines
using System;
using System.Collections.Generic;
using System.Linq;

public enum DriverStatus { Available, Busy }

// The live position of every driver, and the drivers inside each cell. A square grid of meters stands in for the geohash or H3
// cells of the previous lesson: over one city the plane is flat enough, and the logic is the same.
public sealed class DriverIndex
{
    private readonly double _cell;
    private readonly Dictionary<int, (double X, double Y, long Seen, DriverStatus Status, (int, int) Cell)> _drivers = new();
    private readonly Dictionary<(int, int), HashSet<int>> _cells = new();

    public long Updates { get; private set; }          // location reports received
    public long CellWrites { get; private set; }       // reports that had to change the cell map

    public DriverIndex(double cell) { _cell = cell; }

    private (int, int) CellOf(double x, double y) => ((int)Math.Floor(x / _cell), (int)Math.Floor(y / _cell));

    public void Update(int id, double x, double y, long now, DriverStatus status)
    {
        Updates++;
        var cell = CellOf(x, y);
        if (!_drivers.TryGetValue(id, out var old)) { AddTo(cell, id); CellWrites++; }
        else if (old.Cell != cell)                      // only a move across a cell boundary touches the cell map
        {
            RemoveFrom(old.Cell, id);
            AddTo(cell, id);
            CellWrites++;
        }
        _drivers[id] = (x, y, now, status, cell);       // the latest position is always overwritten, in place
    }

    public void Remove(int id)
    {
        if (!_drivers.Remove(id, out var old)) return;
        RemoveFrom(old.Cell, id);
    }

    private void AddTo((int, int) cell, int id)
    {
        if (!_cells.TryGetValue(cell, out var set)) _cells[cell] = set = new HashSet<int>();
        set.Add(id);
    }

    private void RemoveFrom((int, int) cell, int id)
    {
        var set = _cells[cell];
        set.Remove(id);
        if (set.Count == 0) _cells.Remove(cell);
    }

    // Available drivers within `radius` of a point, nearest first. A driver not heard from for `maxAge` seconds is treated as gone.
    public List<(int Id, double Meters)> Nearby(double x, double y, double radius, long now, long maxAge, int limit)
    {
        var (cx0, cy0) = CellOf(x - radius, y - radius);
        var (cx1, cy1) = CellOf(x + radius, y + radius);
        var found = new List<(int Id, double Meters)>();
        for (int cx = cx0; cx <= cx1; cx++)
            for (int cy = cy0; cy <= cy1; cy++)
                if (_cells.TryGetValue((cx, cy), out var set))
                    foreach (int id in set)
                    {
                        var d = _drivers[id];
                        if (d.Status != DriverStatus.Available || now - d.Seen > maxAge) continue;
                        double meters = Math.Sqrt((d.X - x) * (d.X - x) + (d.Y - y) * (d.Y - y));
                        if (meters <= radius) found.Add((id, meters));
                    }
        return found.OrderBy(f => f.Meters).ThenBy(f => f.Id).Take(limit).ToList();
    }
}

There are two maps. _drivers holds the latest report of each driver and is overwritten on every report, which is a cheap in-place write. _cells holds the set of drivers in each cell and changes only when a driver crosses a boundary. Nearby visits the cells that the search square touches, skips drivers who are busy or not heard from lately (a driver who lost signal must not be offered rides), and checks the exact distance: the same cover-then-filter pattern as the proximity service, with the status check added.

The experiment drives 10,000 drivers around a 20 km square city for ten minutes at 2 to 14 m/s, one report every 4 seconds, and counts how many reports change the cell map for four cell sizes. It also checks the index against brute force for 20 searches at each size.

C# · 10,000 drivers drive around a 20 km square city for ten minutes and report every 4…39 lines
using System;
using System.Diagnostics;
using System.Linq;

// 10,000 drivers drive around a 20 km square city for ten minutes and report every 4 seconds, at 2 to 14 m/s (about 30 km/h on average).
const int Drivers = 10_000, Ticks = 150;
const double City = 20_000;
foreach (double cellSize in new[] { 100.0, 250.0, 500.0, 1_000.0 })
{
    var index = new DriverIndex(cellSize);
    var drive = new Random(5);                                  // the same journeys for every cell size
    var x = new double[Drivers]; var y = new double[Drivers]; var heading = new double[Drivers];
    for (int d = 0; d < Drivers; d++) { x[d] = drive.NextDouble() * City; y[d] = drive.NextDouble() * City; heading[d] = drive.NextDouble() * 2 * Math.PI; }
    long baseUpdates = 0, baseWrites = 0;
    for (int tick = 0; tick < Ticks; tick++)
    {
        for (int d = 0; d < Drivers; d++)
        {
            heading[d] += (drive.NextDouble() - 0.5) * 0.6;
            double speed = 2 + drive.NextDouble() * 12;
            x[d] = Math.Clamp(x[d] + Math.Cos(heading[d]) * speed * 4, 0, City - 1);
            y[d] = Math.Clamp(y[d] + Math.Sin(heading[d]) * speed * 4, 0, City - 1);
            index.Update(d, x[d], y[d], tick * 4, DriverStatus.Available);
        }
        if (tick == 0) { baseUpdates = index.Updates; baseWrites = index.CellWrites; }   // the first report of each driver always inserts
    }
    long updates = index.Updates - baseUpdates, writes = index.CellWrites - baseWrites;
    Console.WriteLine($"cells of {cellSize,5:F0} m: {updates} reports, {writes} changed the cell map ({writes / (double)updates:P1})");

    // The index must agree with brute force on who is within 1.5 km of a few points.
    for (int probe = 0; probe < 20; probe++)
    {
        double px = drive.NextDouble() * City, py = drive.NextDouble() * City;
        var expected = Enumerable.Range(0, Drivers).Select(d => (Id: d, Meters: Math.Sqrt((x[d] - px) * (x[d] - px) + (y[d] - py) * (y[d] - py))))
            .Where(t => t.Meters <= 1_500).OrderBy(t => t.Meters).ThenBy(t => t.Id).Take(8).ToList();
        var actual = index.Nearby(px, py, 1_500, (Ticks - 1) * 4, 20, 8);
        Debug.Assert(actual.Select(a => a.Id).SequenceEqual(expected.Select(e => e.Id)));
    }
}
Cell sizeReports after the firstChanged the cell map
100 m1,490,00034.8%
250 m1,490,00014.7%
500 m1,490,0007.4%
1,000 m1,490,0003.7%

Every report is a cheap overwrite of the latest position at every cell size. The expensive operation is the cell move: remove from one set, add to another, and drop an empty set. Halving the cell size roughly doubles the moves, because the boundary a driver must cross is half as far away. Larger cells cut the writes but give each search more drivers to check, which is the cell-size trade-off from the proximity lesson with a write cost on one side. For a pickup search that starts at 1 km and widens only when there are too few drivers, 500 m cells are a sensible middle: 16 cells for the first search, and about 7 moves in every 100 reports.

What these numbers imply for the design:

  • Index writes follow cell moves, not reports. 250,000 reports a second at 7.4% is about 18,500 cell moves a second for the whole fleet, spread over many shards.
  • Shard by area, not by driver id. A shard owns a block of cells, so a search touches one shard or a few at a boundary, and a driver crosses a shard boundary even more rarely than a cell boundary. Hashing by driver id would send every search to every shard.
  • Do not make the index durable. A replica that misses a report is corrected by the next one four seconds later, so keep a hot standby per shard that consumes the same reports, or rebuild a lost shard from live reports within a few intervals. Writing the index to disk would add cost and protect nothing.
  • Freshness is part of the query. Nearby ignores a driver not heard from for a few report intervals, and a sweeper removes drivers that have been silent for a minute. Use the server's receipt time, not the phone's clock.
  • Order matters per driver. Each report carries a sequence number, and the index ignores a report older than the newest it holds, so a delayed packet cannot move a driver backwards.
  • Reporting can adapt. An idle, parked driver can report less often and a driver on a trip or near a rider more often, and the server can set the interval in each response. That saves battery and data without hurting matching.
  • The same reports feed a stream for trip history, ETA models and fraud checks. Idle positions can be sampled, and positions during a trip are kept in full, because they decide the fare.

LLD

Deep dive: matching, and why nearest-first is not enough

Finding candidates is the easy half: ask the index for available drivers within a radius, and widen it if there are too few. Choosing is the hard half. Giving each rider the nearest driver is simple and fast, and it is wrong in aggregate. When two riders ask within seconds of each other, the first takes the nearest driver even if that driver is the only good option for the second, whose next best driver is far away. First come, first served ignores the other decisions being made at the same moment.

Batching fixes it. Collect the requests in an area for a short window (two seconds, say) and choose the assignment of drivers to riders that minimizes the total cost for the whole batch. That is the assignment problem, and the Hungarian algorithm solves it exactly in O(n³).

C# · Matching60 lines
using System;
using System.Linq;

public static class Matching
{
    // Each rider, in arrival order, takes the nearest driver who is still free. cost[rider, driver] is the pickup distance.
    public static int[] Greedy(double[,] cost)
    {
        int riders = cost.GetLength(0), drivers = cost.GetLength(1);
        var taken = new bool[drivers];
        var assignment = new int[riders];
        for (int r = 0; r < riders; r++)
        {
            int best = -1;
            for (int d = 0; d < drivers; d++)
                if (!taken[d] && (best < 0 || cost[r, d] < cost[r, best])) best = d;
            assignment[r] = best;
            taken[best] = true;
        }
        return assignment;
    }

    // The assignment with the smallest total cost for the whole batch (the Hungarian algorithm, O(riders^2 x drivers));
    // it needs at least as many drivers as riders.
    public static int[] Optimal(double[,] cost)
    {
        int n = cost.GetLength(0), m = cost.GetLength(1);
        var u = new double[n + 1];                      // a price for each rider and each driver; they prove the answer optimal
        var v = new double[m + 1];
        var owner = new int[m + 1];                     // owner[j] = the rider (1-based) currently holding driver j, 0 if free
        var way = new int[m + 1];
        for (int i = 1; i <= n; i++)
        {
            owner[0] = i;
            int j0 = 0;
            var slack = Enumerable.Repeat(double.PositiveInfinity, m + 1).ToArray();
            var used = new bool[m + 1];
            do
            {
                used[j0] = true;
                int i0 = owner[j0], j1 = 0;
                double delta = double.PositiveInfinity;
                for (int j = 1; j <= m; j++)
                {
                    if (used[j]) continue;
                    double reduced = cost[i0 - 1, j - 1] - u[i0] - v[j];
                    if (reduced < slack[j]) { slack[j] = reduced; way[j] = j0; }
                    if (slack[j] < delta) { delta = slack[j]; j1 = j; }
                }
                for (int j = 0; j <= m; j++)
                    if (used[j]) { u[owner[j]] += delta; v[j] -= delta; } else slack[j] -= delta;
                j0 = j1;
            } while (owner[j0] != 0);
            do { int j1 = way[j0]; owner[j0] = owner[j1]; j0 = j1; } while (j0 != 0);   // flip the path: re-seat earlier riders
        }
        var assignment = new int[n];
        for (int j = 1; j <= m; j++) if (owner[j] != 0) assignment[owner[j] - 1] = j - 1;
        return assignment;
    }
}

The first loop of the next sample checks the solver against every possible assignment on 200 small random cases, so the code is known to find the true minimum. Then 30 riders ask in the same window in a 10 km square, and the number of available drivers goes from plenty to barely enough. Each setting is repeated 200 times.

C#50 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

double Pickup(double[,] cost, int[] assignment, out double worst)
{
    double total = 0; worst = 0;
    for (int r = 0; r < assignment.Length; r++) { total += cost[r, assignment[r]]; worst = Math.Max(worst, cost[r, assignment[r]]); }
    return total;
}
double[,] RandomCosts(Random random, int riders, int drivers)
{
    var rp = Enumerable.Range(0, riders).Select(_ => (X: random.NextDouble() * 10_000, Y: random.NextDouble() * 10_000)).ToArray();
    var dp = Enumerable.Range(0, drivers).Select(_ => (X: random.NextDouble() * 10_000, Y: random.NextDouble() * 10_000)).ToArray();
    var cost = new double[riders, drivers];
    for (int r = 0; r < riders; r++) for (int d = 0; d < drivers; d++) cost[r, d] = Math.Sqrt((rp[r].X - dp[d].X) * (rp[r].X - dp[d].X) + (rp[r].Y - dp[d].Y) * (rp[r].Y - dp[d].Y));
    return cost;
}

// First, the Hungarian code must find the true minimum: compare it with every possible assignment on small random cases.
var check = new Random(1);
for (int trial = 0; trial < 200; trial++)
{
    var cost = RandomCosts(check, 5, 7);
    double best = double.MaxValue;
    void Permute(int rider, bool[] used, double sum)
    {
        if (rider == 5) { best = Math.Min(best, sum); return; }
        for (int d = 0; d < 7; d++) if (!used[d]) { used[d] = true; Permute(rider + 1, used, sum + cost[rider, d]); used[d] = false; }
    }
    Permute(0, new bool[7], 0);
    Debug.Assert(Math.Abs(Pickup(cost, Matching.Optimal(cost), out _) - best) < 1e-6);
}

// Thirty riders ask within the same short window. Hand each the nearest free driver in arrival order, or solve the batch at once.
var dispatch = new Random(3);
foreach (int drivers in new[] { 200, 60, 40, 32 })
{
    double greedyTotal = 0, optimalTotal = 0, greedyWorst = 0, optimalWorst = 0;
    for (int trial = 0; trial < 200; trial++)
    {
        var cost = RandomCosts(dispatch, 30, drivers);
        greedyTotal += Pickup(cost, Matching.Greedy(cost), out double gw);
        optimalTotal += Pickup(cost, Matching.Optimal(cost), out double ow);
        greedyWorst += gw; optimalWorst += ow;
    }
    Console.WriteLine($"{drivers,3} drivers for 30 riders: mean pickup {greedyTotal / 6000:F0} m greedy, {optimalTotal / 6000:F0} m batch ({1 - optimalTotal / greedyTotal:P0} less); worst pickup {greedyWorst / 200:F0} m greedy, {optimalWorst / 200:F0} m batch");
    Debug.Assert(optimalTotal <= greedyTotal + 1e-6);
}
Drivers for 30 ridersMean pickup, greedyMean pickup, batchLessWorst pickup, greedyWorst pickup, batch
200387 m379 m2%937 m911 m
60857 m785 m8%2,345 m2,014 m
401,317 m1,136 m14%3,970 m3,010 m
321,844 m1,489 m19%6,279 m4,124 m

With plentiful supply greedy is nearly as good (2% worse), because there are enough good drivers for everyone. The gap opens as supply tightens: with 32 drivers for 30 riders the batch has 19% shorter pickups on average, and the worst pickup falls by a third, from 6.3 km to 4.1 km, because greedy leaves the last riders with whatever remains. Batching helps most when the market is under stress, which is when it matters.

The design choices around it:

  • The window is a trade. Waiting two seconds costs every rider two seconds but lets the solver see more of the market. Make it adaptive: short when supply is plentiful, since there is little to gain, and longer in a hot cell. A batch of one is just greedy.
  • The cost is rarely just distance. Use the road ETA, and add terms: the chance that the driver accepts, the driver's heading, how long the rider has waited, fairness to drivers who have been idle. The algorithm minimizes whatever number you give it, so the objective is a business decision.
  • Scale by splitting. O(n³) is fine for a few hundred riders and drivers per batch. Split a city into regions solved independently, restrict each rider to its few nearest drivers (a sparse problem), and use a min-cost flow solver for the big dense regions.
  • The offer is a request, not an assignment. The driver may decline, ignore it or lose signal. Offering to one driver at a time with a short timeout (10 to 15 seconds) is polite to drivers and slow for riders. Offering to several at once is faster and wastes drivers' attention, and "the ride was taken" becomes common. A common compromise is one at a time with the next candidates ready, and several at once only when the market is tight.

LLD

Deep dive: never two rides for one driver

Two matchers in different processes can both decide that driver 7 is the best choice for different riders at the same instant. Without coordination both make an offer, one rider is promised a driver who is busy, and the system has to explain itself. The fix has two parts: a reservation that only one caller can win, and a ride state machine that refuses stale and illegal moves.

C# · RideState, Outcome, Ride, …59 lines
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

public enum RideState { Requested, Matching, DriverAssigned, DriverArrived, InProgress, Completed, Cancelled }
public enum Outcome { Applied, Duplicate, Conflict, Illegal }

// One ride as a state machine. The table of allowed moves is the only place that says what can follow what, and every change goes
// through Apply, which checks the version the caller saw, the table and the idempotency key.
public sealed class Ride
{
    private static readonly Dictionary<RideState, RideState[]> Moves = new()
    {
        [RideState.Requested] = new[] { RideState.Matching, RideState.Cancelled },
        [RideState.Matching] = new[] { RideState.DriverAssigned, RideState.Cancelled },
        [RideState.DriverAssigned] = new[] { RideState.DriverArrived, RideState.Matching, RideState.Cancelled },   // back to Matching if the driver drops out
        [RideState.DriverArrived] = new[] { RideState.InProgress, RideState.Cancelled },
        [RideState.InProgress] = new[] { RideState.Completed },
        [RideState.Completed] = Array.Empty<RideState>(),
        [RideState.Cancelled] = Array.Empty<RideState>(),
    };

    private readonly HashSet<string> _applied = new();
    public RideState State { get; private set; } = RideState.Requested;
    public int Version { get; private set; }

    public static bool CanMove(RideState from, RideState to) => Moves[from].Contains(to);

    // Applies a move once. A retry with the same key is a harmless duplicate, a caller that read an old version gets a conflict
    // and must look again, and a move the table does not allow is refused.
    public Outcome Apply(string key, int expectedVersion, RideState to)
    {
        if (_applied.Contains(key)) return Outcome.Duplicate;
        if (expectedVersion != Version) return Outcome.Conflict;
        if (!CanMove(State, to)) return Outcome.Illegal;
        State = to;
        Version++;
        _applied.Add(key);
        return Outcome.Applied;
    }
}

// Who holds each driver. In production this is a conditional write in the store that owns the driver's state, with a lease that
// expires if the dispatcher dies. An atomic compare-and-set in memory has the same meaning.
public sealed class Reservations
{
    private readonly int[] _owner;                                   // 0 = free, otherwise the id of the trip holding the driver

    public Reservations(int drivers) { _owner = new int[drivers]; }

    // Succeeds for exactly one caller when several race: only the one who sees "free" and swaps in its trip id wins.
    public bool TryReserve(int driver, int trip) => Interlocked.CompareExchange(ref _owner[driver], trip, 0) == 0;

    // Only the holder can release, so a late or duplicate release by someone else changes nothing.
    public bool Release(int driver, int trip) => Interlocked.CompareExchange(ref _owner[driver], 0, trip) == trip;

    public int Owner(int driver) => Volatile.Read(ref _owner[driver]);
}

The reservation is a compare-and-set: swap the owner from free to the trip id, and succeed only if it was free. In production it is a conditional write in the store that owns the driver's state, with a lease so that a dispatcher that dies cannot hold a driver forever. Ride is a table of allowed moves plus three checks in Apply: has this key been applied (a retry is a harmless duplicate), did the caller see the current version (otherwise a conflict, and it must read again), and is the move in the table.

C# · Check, then act: two dispatchers both read "free" before either one writes, so both…70 lines
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;

// Check, then act: two dispatchers both read "free" before either one writes, so both believe they hold driver 1.
var naiveOwner = new int[3];
bool freeForA = naiveOwner[1] == 0;
bool freeForB = naiveOwner[1] == 0;
if (freeForA) naiveOwner[1] = 101;                      // dispatcher A assigns trip 101
if (freeForB) naiveOwner[1] = 202;                      // dispatcher B assigns trip 202, silently replacing A
Console.WriteLine($"check-then-act: driver 1 ends up with trip {naiveOwner[1]}, yet trip 101 was told it had them too");
Debug.Assert(freeForA && freeForB && naiveOwner[1] == 202);

// Compare-and-set: eight dispatcher threads, released together, race for the same 1,000 drivers, each for its own trip.
var reservations = new Reservations(1_000);
var wins = new int[8];
var gate = new ManualResetEventSlim(false);
var threads = Enumerable.Range(0, 8).Select(dispatcher => new Thread(() =>
{
    gate.Wait();
    for (int driver = 0; driver < 1_000; driver++)
        if (reservations.TryReserve(driver, dispatcher + 1)) wins[dispatcher]++;
})).ToList();
threads.ForEach(t => t.Start());
gate.Set();
threads.ForEach(t => t.Join());
Console.WriteLine($"compare-and-set: {wins.Sum()} reservations won by 8 dispatchers for 1,000 drivers");
Debug.Assert(wins.Sum() == 1_000);                                      // how the wins are split varies from run to run, the total never does
Debug.Assert(Enumerable.Range(0, 1_000).All(driver => reservations.Owner(driver) is >= 1 and <= 8));
int holder = reservations.Owner(7);
Debug.Assert(!reservations.Release(7, holder + 100));                  // only the holder can release
Debug.Assert(reservations.Release(7, holder) && reservations.TryReserve(7, 99) && reservations.Owner(7) == 99);

// The table of moves is the only authority: try every pair of states, each on a ride that was walked into the first state.
RideState[] path = { RideState.Matching, RideState.DriverAssigned, RideState.DriverArrived, RideState.InProgress, RideState.Completed };
Ride RideIn(RideState target)
{
    var walked = new Ride();
    if (target == RideState.Cancelled) { walked.Apply("c", 0, RideState.Cancelled); return walked; }
    for (int i = 0; walked.State != target; i++) walked.Apply("m" + i, walked.Version, path[i]);
    return walked;
}
int pairs = 0;
foreach (var from in Enum.GetValues<RideState>())
    foreach (var to in Enum.GetValues<RideState>())
    {
        var probe = RideIn(from);
        var outcome = probe.Apply("probe", probe.Version, to);
        Debug.Assert(outcome == (Ride.CanMove(from, to) ? Outcome.Applied : Outcome.Illegal));
        pairs++;
    }
Console.WriteLine($"{pairs} state pairs checked against the table");

// A retried request is a duplicate and changes nothing.
var trip = new Ride();
Debug.Assert(trip.Apply("req-1", 0, RideState.Matching) == Outcome.Applied);
Debug.Assert(trip.Apply("req-1", 0, RideState.Matching) == Outcome.Duplicate && trip.Version == 1);

// The race that matters: the matcher reserves a driver while the rider cancels. Both acted on version 1.
var contested = new Ride();
var seats = new Reservations(10);
contested.Apply("a", 0, RideState.Matching);
bool reserved = seats.TryReserve(7, 555);                                               // matcher: driver 7 is held for trip 555
var cancel = contested.Apply("rider-cancel", 1, RideState.Cancelled);                    // rider cancels first
var assign = contested.Apply("match-7", 1, RideState.DriverAssigned);                    // matcher's move now conflicts
if (assign != Outcome.Applied) seats.Release(7, 555);                                    // compensation: give the driver back
Console.WriteLine($"cancel {cancel}, assign {assign}: ride is {contested.State}, driver 7 held by {seats.Owner(7)}");
Debug.Assert(reserved && cancel == Outcome.Applied && assign == Outcome.Conflict);
Debug.Assert(contested.State == RideState.Cancelled && seats.Owner(7) == 0);

The check-then-act version tells two trips they have the same driver, which is the bug. With compare-and-set, eight threads racing for 1,000 drivers won exactly 1,000 reservations between them, one per driver, whatever the interleaving. How the wins are split changes from run to run, and the total never does. The 49 pairs show that the table is the only authority: the ride accepted exactly the moves it lists and refused every other one.

The last scenario is the race that matters in practice: a rider cancels while the matcher reserves a driver. The cancel wins, the matcher's assignment conflicts, and the matcher compensates by releasing driver 7. The ride ends cancelled and the driver is free, and the system never reaches "ride cancelled, driver still held". A few rules make this work in a real deployment:

  • A conflict is the system working. It means someone else changed the ride first. The loser reads again and decides again: the matcher gives up and looks for another ride, and a cancel after assignment is a legal move whose cost (a fee, perhaps) is a business rule evaluated on the current state.
  • Every reservation has a lease. If the matcher dies after reserving, the lease expires and the driver is available again. An offer has an expiry for the same reason.
  • Every external call is idempotent. The ride request carries an Idempotency-Key, the offer has an id, and a retried accept is a duplicate and not a second assignment.
  • A change and its event travel together. Other services must learn that a ride was assigned (push to the rider, stop location sharing, start the payment). Write the state change and the event in one transaction, a transactional outbox (see queues and async work), so that an assignment is never recorded without its event or announced without being recorded.

LLD

Deep dive: ETA and routing

Straight-line distance finds candidates quickly and ranks them badly. Rivers, rail lines, highways without exits, one-way streets and traffic make the driver nearest in a straight line sometimes the slowest to arrive. The next sample builds a toy city of 60 by 60 blocks in which every street segment takes 1 to 3 time units, a river splits the city in two, and only three bridges cross it. It compares the driver nearest in a straight line with the driver who is quickest to reach, found with Dijkstra's algorithm.

C# · A city of square blocks. Every street segment takes between 1 and 3 time units…52 lines
using System;
using System.Collections.Generic;

// A city of square blocks. Every street segment takes between 1 and 3 time units (traffic), and a river that splits the city in
// two can be crossed only on a few bridges.
public sealed class RoadGrid
{
    public int Width { get; }
    public int Height { get; }
    private readonly double[] _east;                        // time to drive from (x, y) to (x + 1, y)
    private readonly double[] _north;                       // time to drive from (x, y) to (x, y + 1)

    public RoadGrid(int width, int height, Random random, int riverAfterColumn, int[] bridgeRows)
    {
        Width = width; Height = height;
        _east = new double[width * height];
        _north = new double[width * height];
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
            {
                _east[y * width + x] = 1 + random.NextDouble() * 2;
                _north[y * width + x] = 1 + random.NextDouble() * 2;
                if (x == riverAfterColumn && Array.IndexOf(bridgeRows, y) < 0) _east[y * width + x] = double.PositiveInfinity;
            }
    }

    // Dijkstra's algorithm: the driving time from one corner to every other corner of every block.
    public double[] TimesFrom(int sx, int sy)
    {
        var time = new double[Width * Height];
        Array.Fill(time, double.PositiveInfinity);
        var queue = new PriorityQueue<int, double>();
        time[sy * Width + sx] = 0;
        queue.Enqueue(sy * Width + sx, 0);
        while (queue.TryDequeue(out int node, out double t))
        {
            if (t > time[node]) continue;                   // a stale queue entry
            int x = node % Width, y = node / Width;
            void Relax(int nx, int ny, double cost)
            {
                if (double.IsPositiveInfinity(cost)) return;
                int next = ny * Width + nx;
                if (t + cost < time[next]) { time[next] = t + cost; queue.Enqueue(next, t + cost); }
            }
            if (x + 1 < Width) Relax(x + 1, y, _east[node]);
            if (x > 0) Relax(x - 1, y, _east[node - 1]);
            if (y + 1 < Height) Relax(x, y + 1, _north[node]);
            if (y > 0) Relax(x, y - 1, _north[node - Width]);
        }
        return time;
    }
}
C# · A 60 x 60 city with a river after column 29 and bridges at rows 8, 30 and 52. For 1,000…28 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// A 60 x 60 city with a river after column 29 and bridges at rows 8, 30 and 52. For 1,000 requests, 25 free drivers are scattered
// around. Compare the driver closest in a straight line with the driver who is quickest to reach by road.
var cityRandom = new Random(17);
var city = new RoadGrid(60, 60, cityRandom, 29, new[] { 8, 30, 52 });
int straightRight = 0, shortlist3Right = 0, shortlist5Right = 0;
double wrongExtra = 0, wrongBest = 0;
for (int trial = 0; trial < 1_000; trial++)
{
    int rx = cityRandom.Next(60), ry = cityRandom.Next(60);
    var driversAt = Enumerable.Range(0, 25).Select(_ => (X: cityRandom.Next(60), Y: cityRandom.Next(60))).ToArray();
    var time = city.TimesFrom(rx, ry);
    double[] byRoad = driversAt.Select(d => time[d.Y * 60 + d.X]).ToArray();
    int[] byLine = Enumerable.Range(0, 25).OrderBy(i => (driversAt[i].X - rx) * (driversAt[i].X - rx) + (driversAt[i].Y - ry) * (driversAt[i].Y - ry)).ToArray();
    int quickest = Enumerable.Range(0, 25).OrderBy(i => byRoad[i]).First();

    if (byRoad[byLine[0]] == byRoad[quickest]) straightRight++;
    else { wrongExtra += byRoad[byLine[0]] - byRoad[quickest]; wrongBest += byRoad[quickest]; }
    if (byLine.Take(3).Min(i => byRoad[i]) == byRoad[quickest]) shortlist3Right++;
    if (byLine.Take(5).Min(i => byRoad[i]) == byRoad[quickest]) shortlist5Right++;
}
Console.WriteLine($"the straight-line nearest is the quickest to reach in {straightRight / 10.0:F1}% of requests; when it is not, the pick takes {wrongExtra / wrongBest:P0} longer");
Console.WriteLine($"the quickest of the 3 nearest in a straight line is the overall quickest in {shortlist3Right / 10.0:F1}%, of the 5 nearest in {shortlist5Right / 10.0:F1}%");
Debug.Assert(straightRight < 900 && shortlist3Right >= 980 && shortlist5Right >= shortlist3Right);

The driver nearest in a straight line was the quickest to reach in 86.3% of requests, and when it was not, the pick took 28% longer than the best. The quickest of the 3 nearest in a straight line was the overall quickest in 99.3% of requests, and of the 5 nearest in 99.9%. That is the pattern to use: retrieve by geometry, which is cheap, then re-rank a short list by road time, which is expensive, and never route to every driver.

How a real routing service answers quickly:

  • The graph is preprocessed. One Dijkstra search from a rider settles a large part of a city, and real road graphs have tens of millions of nodes. Engines add shortcut edges ahead of time (contraction hierarchies are the best-known technique, and OSRM is an open-source engine that uses them), so a query touches a few hundred nodes instead of millions.
  • Traffic is data on the edges. Live and historical speeds change the edge costs, and the graph's answer is then corrected by a learned model for what a graph misses: pickup friction, parking, turn costs.
  • Matching uses an approximate table first. A table of travel times between coarse cells ranks thousands of candidate pairs cheaply, and the exact router runs only for the final short list and for the number shown to the rider.
  • Cache the answers. Many riders in one cell ask for the time from the same drivers' cells, so cell-to-cell results are reused for a minute or two.

HLD

Pricing, quotes and surge

A price is a promise. Quote first and pin it: the rider app asks for a quote (a route estimate times the rates times the surge multiplier at that moment), the server stores it with an expiry and returns a quote_id, and the ride request carries that id. The fare charged is the quote, unless the trip deviates materially under rules the rider was shown, so the price never changes between "see" and "tap".

The surge multiplier is a market signal. Where demand outruns supply, a higher price reduces demand and draws drivers in. It is computed per cell per minute from two streams, requests and available drivers, as a function of demand over supply clipped to a range. Three engineering problems decide whether it works:

  • Noise. Counts per cell per minute are small and jumpy, so a raw ratio flickers, and drivers chase prices that vanish. Smooth the inputs (average a cell with its neighbours, and over the last few minutes), then divide. Smoothing the output instead hides the same noise less well.
  • Borders. A rider one street away sees a different price, and walks. Spatial smoothing softens the cliffs, and hexagonal cells, whose six neighbours are all the same distance away (the property that makes H3 popular for this), make the smoothing uniform.
  • Feedback. A price change changes the demand and supply it is measured from. Ramp changes, cap them, add hysteresis so a multiplier does not flip at a threshold, and tell drivers where demand is. Caps in emergencies and in some cities are policy and law, not algorithm output, so keep them as configuration.

HLD

Trips, tracking and payments

  • Tracking. After assignment the Location service forwards the driver's reports to the rider's connection, one to one and cheap. The app interpolates between reports every 4 seconds so the car moves smoothly. Holding millions of connections open is the problem solved in the chat system lesson.
  • The trip trace. During the trip, reports are kept in full. GPS is noisy, with errors of tens of meters and worse in tunnels and between tall buildings, so the trace is snapped to the road network (map matching, usually with a hidden Markov model) before distance is computed, and the fare is base plus time plus distance plus fees, or the pinned quote where one applies.
  • Payments. At completion the Ride service emits a ride.completed event and a payments service charges with an idempotency key derived from the ride id, so a retry never charges twice (see API design). A failed charge must not strand the ride: the trip is complete, the debt is recorded and collection retries later.
  • Everything else is a consumer. Receipts, ratings, emails and analytics read the event stream and are allowed to be late.

HLD

Failure modes and edge cases

CaseWhat goes wrongHandle it
A driver loses signal after an offerThe rider waits for an answer that never comesAn offer timeout of 10 to 15 seconds, then the next candidate. Heartbeats and maxAge drop silent drivers from candidate lists
A dispatcher dies between reserving and offeringThe driver is held and nobody offers anythingA lease on every reservation that releases it on expiry, and an expiry on every offer
Two riders pick the same driver at onceDouble bookingA compare-and-set reservation: one wins and the other moves to its next candidate
The rider cancels while the matcher assignsA cancelled ride with a busy driverVersioned transitions, and compensation (release the driver) when the assignment conflicts
A double tap or a retry on a bad networkTwo rides and two chargesAn idempotency key on the request and on the payment
Stale or out-of-order reportsA driver appears where they were a minute ago, or jumps backwardsSequence numbers, server receipt time, maxAge, and dropping reports that imply an impossible speed
GPS jumps in tunnels and street canyonsTeleporting drivers and wrong faresA speed sanity check, map matching, and the fare from the snapped trace
A stadium emptiesThousands of requests land in a few cells, offers fail and nobody can reach the crowdLonger adaptive batch windows, queued requests with honest ETAs, staged pickup zones, surge to draw supply, extra replicas and load shedding for the hot shard, bulkheads so other cells are untouched
A region failsReports stop, the index is gone, rides in progress lose trackingDrivers reconnect to another region and the index refills within a few report intervals, the rides store is replicated (see multi-region design), and clients retry with the same keys
Fraud and spoofingFake drivers, fake positions, collusionServer-side plausibility checks, device attestation, anomaly detection on the report stream
Clock skew between phone and serverReports look old or come from the futureUse the server's receipt time for freshness, and the device time only to order one driver's reports

Senior depth

What senior interviews ask about a ride-hailing service

Interviewer follow-upL5How do you find nearby drivers when 250,000 positions arrive every second?How to answer

Keep them in memory and never in the ride database. A map holds each driver's latest position, overwritten in place, and a second map holds the drivers in each cell, which changes only when a driver crosses a cell boundary. In the simulation that was 7.4% of reports with 500 m cells. Shard the cells by area so that a search touches one shard or a few, keep a hot standby per shard, and rebuild a lost shard from live reports, because the data is wrong within seconds anyway.

Interviewer follow-upL5Why not store driver locations in the main database?How to answer

It is 250,000 writes a second of data that is out of date in four seconds and has no value once a driver has moved. A transactional store would pay for durability, indexing and replication that nobody needs. Memory plus a stream gives the same answers at a fraction of the cost, and only the positions during a trip are kept in full, because they decide the fare.

Interviewer follow-upL6Why not simply assign the nearest driver?How to answer

Because each decision ignores the others. Batch the requests in an area over a short window and solve the assignment problem for the whole batch. In the simulation the gain was 2% with plentiful supply and 19% on mean pickup distance with barely enough drivers, and the worst pickup fell by a third. Make the window adaptive, use road ETA and other terms in the cost, and split a city into regions so each batch stays small.

Interviewer follow-upL6How do you stop a driver from being offered two rides?How to answer

Reserve with a compare-and-set before offering: swap the owner from free to the trip, and only one caller wins. Put a lease on the reservation, so a dead dispatcher does not hold the driver, and record the assignment on the ride through a versioned state machine. If that step conflicts (the rider cancelled), release the driver as a compensation. A check-then-act version fails in the simplest interleaving, as the test shows.

Interviewer follow-upL6The driver never answers the offer. What happens?How to answer

The offer has an expiry of 10 to 15 seconds. When it passes, the reservation is released, the driver's reliability counts against them, and the matcher offers the ride to the next candidate, which it prepared in advance. Silent drivers also drop out of candidate lists because the index ignores drivers it has not heard from lately. A timer, or a scheduler over offers with their expiry, makes sure a ride is never stuck waiting.

Interviewer follow-upL6How do you compute ETAs for matching at scale?How to answer

In two steps. Rank candidates by geometry or a table of travel times between coarse cells, then ask the routing engine for the road time of a short list. In the simulation the straight-line nearest was the quickest to reach in only 86.3% of requests, and the best of the 3 nearest was right 99.3% of the time. The engine itself uses a preprocessed graph (contraction hierarchies), live traffic on the edges and a model that corrects the graph's time, and results are cached by cell pair.

Interviewer follow-upL6How does surge pricing work, and how do you stop it from flickering?How to answer

Compute demand over supply per cell per minute, clipped to a range. Counts are small and noisy, so smooth the inputs over neighbouring cells and over time before dividing, ramp and cap changes, and add hysteresis. Pin the price in a quote with an expiry, so what the rider sees is what is charged. Caps in emergencies are policy and belong in configuration.

Interviewer follow-upL7A stadium empties: 50,000 requests in one cell in a few minutes. What breaks?How to answer

The hot shard of the index and the matcher for that region, then the offers, because there are not enough drivers nearby. Protect the rest of the system with bulkheads and load shedding for that region, give the hot cell extra replicas, lengthen the batch window, queue riders with an honest ETA, send drivers and riders to staged pickup zones, and let surge draw supply. A forecast from the event calendar can move supply there before the end.

Interviewer follow-upL7A region goes down. What happens to rides in progress?How to answer

Drivers and riders reconnect to another region, and the driver index refills within a few report intervals, since it is ephemeral. The ride records are replicated, so the other region reads the ride's last committed state, and clients retry with the same idempotency keys. Some tracking is lost for a short time, and the trip trace may have a gap that map matching or the fare logic must tolerate. See multi-region design for the replication choices and what a failover costs.

Interviewer follow-upL7How would you test a new matching algorithm?How to answer

Riders and drivers share one pool of supply, so randomizing riders into two groups contaminates the control: the treated riders take the drivers that the control riders would have used. Replay historical requests offline first, then run a switchback experiment (alternate the algorithm by time window within a city) or randomize by region, and compare marketplace metrics such as wait time, completed rides and driver utilization, over long enough to see delayed effects.

HLD

How to present this design in an interview

  1. Clarify: single rides only, what must never happen, what matters when supply is short.
  2. Estimate: 250,000 reports a second against about 230 rides a second, and an index of about 100 MB.
  3. Split by data lifetime: driver positions in memory, rides behind a state machine in a transactional store.
  4. Draw it: gateway, location service, driver index sharded by cell, ride service, matching, ETA, pricing, push.
  5. Go deep on location: a cell map that changes on cell moves only (about 7% of reports), shards by area, rebuilt from the stream.
  6. Match: candidates from the index, a short batch window and the assignment problem, offers with timeouts.
  7. Prevent double booking: a compare-and-set reservation with a lease, a versioned state machine and compensation.
  8. Rank by road time on a short list, pin quotes and smooth surge by cell and time.
  9. Close with failures: the stadium, a lost region, GPS, fraud, and how you would test a change to matching.

Summary

A ride-hailing service separates data by how long it lives. Driver positions are ephemeral: 250,000 reports a second go to an in-memory index that overwrites the latest position and changes its cell map only when a driver crosses a boundary (7.4% of reports with 500 m cells), is sharded by area and is rebuilt from the stream after a failure. Rides are durable: one row each, changed through a versioned state machine behind a transactional store. Matching joins the two. It retrieves candidates by cell, ranks a short list by road ETA (the straight-line nearest was the quickest to reach in only 86.3% of requests), solves a batch as an assignment problem (19% shorter pickups and a worst pickup a third shorter when supply is tight), and claims the driver with a compare-and-set reservation and a lease before recording the assignment, compensating when a cancel wins the race. Quotes are pinned, surge is smoothed by cell and by time, payments are idempotent and asynchronous, and the failure answers are stadium crowds, a lost region, GPS errors and fraud.

Check yourself

Try answering out loud before you reveal each answer.

QuestionWhy does the driver index change its cell map for only a small part of the reports, and what does that mean for sharding and replication?Reveal answer

A driver moving at about 30 km/h covers roughly 33 m between reports, so most reports stay inside a cell. With 500 m cells 7.4% of reports crossed a boundary, 14.7% with 250 m cells and 34.8% with 100 m cells. The latest position is overwritten in place, and the cell map changes rarely, so index writes are a small fraction of 250,000 reports a second. Shard by area so a search touches few shards, and do not make the index durable: a replica or a rebuilt shard is corrected by the next report within seconds.

QuestionWhy batch the requests of a short window instead of giving each rider the nearest driver at once?Reveal answer

Each greedy decision ignores the others, so an early rider can take the only good driver for a later one. Solving the assignment for the whole batch minimizes the total cost. With plentiful supply the gain was small (2%), and with 32 drivers for 30 riders mean pickup distance fell 19% and the worst pickup fell from 6.3 km to 4.1 km. The window is a trade-off, since waiting costs every rider time, so make it adaptive.

QuestionTwo dispatchers pick the same driver at the same moment, and the rider cancels while one of them assigns. What prevents a double booking and a stuck driver?Reveal answer

A compare-and-set reservation: only one dispatcher swaps the owner from free to its trip, and the other moves to its next candidate. A lease frees the driver if the winner dies. The assignment is recorded through a versioned state machine, so when the cancel landed first, the matcher's assignment conflicts and it releases the driver as a compensation. The test shows a ride that ends cancelled with the driver free.

QuestionWhy is the straight-line nearest driver not good enough for the final choice, and what do you do about it cheaply?Reveal answer

Rivers, rail, highways and traffic make straight-line distance a poor guide: in the toy city the straight-line nearest was the quickest to reach in only 86.3% of requests, and the wrong pick took 28% longer. Retrieve candidates by geometry, then ask the routing engine for the road time of a short list, because the best of the 3 nearest was right 99.3% of the time. Do not route to every driver, and use cell-to-cell time tables for the first ranking.

Sources and further reading

  • Uber, H3: Uber's Hexagonal Hierarchical Spatial Index (opens in a new tab) (2018): why equal-distance neighbours suit pricing and dispatch analysis.
  • Google, S2 Geometry (opens in a new tab): the cell system behind many geospatial indexes, covered in the proximity service lesson.
  • Lyft Engineering, Matchmaking in Lyft Line (2016, in two parts): matching riders in windows and the cost terms beyond distance.
  • Lyft Engineering, Experimentation in a Ridesharing Marketplace (a series): interference between riders who share drivers, and switchback experiments.
  • Harold Kuhn, The Hungarian method for the assignment problem, Naval Research Logistics Quarterly, 1955, and James Munkres, Algorithms for the Assignment and Transportation Problems, 1957.
  • Robert Geisberger, Peter Sanders, Dominik Schultes and Daniel Delling, Contraction Hierarchies: Faster and Simpler Hierarchical Routing in Road Networks, 2008, and the OSRM project (opens in a new tab), an open-source routing engine.
  • Paul Newson and John Krumm, Hidden Markov Map Matching Through Noise and Sparseness, ACM SIGSPATIAL, 2009: snapping noisy GPS traces to roads.
  • Chris Richardson, Transactional outbox (opens in a new tab): writing a state change and its event together.
  • Alex Xu and Sahn Lam, System Design Interview, Volume 2 (ByteByteGo, 2022): the nearby friends and Google Maps chapters cover neighbouring problems.
Lesson 28 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 29Case study: design a video streaming serviceA senior-level walkthrough of video streaming in the YouTube and Netflix style: resumable uploads, chunked parallel transcoding with backups for stragglers, bitrate ladders and manifests, adaptive players and CDN delivery, with tested C#.

Send a message

It goes straight to my inbox. I usually reply within a few days.