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.
- 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.
- 2Postgres decides who gets a trip, with conditional updates and partial unique indexes. The Redis lease only saves wasted offers.
- 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.
- 4Search a small circle first. A wide sorted GEOSEARCH in a dense core blocks the event loop for every position update.
Design the matching of riders to nearby drivers whose locations change every few seconds.
| question | answer 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.
| 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-functional | target |
|---|---|
| Position in the index | p99 < 2 s after a report |
| Request to first offer | p99 < 2 s, plus any batch window |
| Double bookings | 0 |
| Trip state | Strong: one writer, in Postgres |
| Positions | Best effort: the next report repairs a loss |
| Availability | 99.95%, per city |
Positions can be a few seconds old, and a lost one costs nothing. Matches must be exactly right.
| quantity | arithmetic | result |
|---|---|---|
| Position updates | 1 M drivers ÷ 4 s | 250k/s; largest city 25k/s |
| Ride requests | 20 M ÷ 86,400 | ≈ 231/s; 3× peak ≈ 694/s |
| Largest city | a tenth of the peak | ≈ 69 requests/s |
| Index memory | 1 M × 80 B (measured) | 80 MB |
| Trips | 20 M × 300 B (assumed row) | 6 GB a day ≈ 2.2 TB a year |
| Position history | 250k/s × 50 B × 86,400, at peak rate | up to 1.1 TB a day, to a log |
| Socket traffic in | 250k/s × 100 B | 200 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.
| call | for | retry safe by | success | errors |
|---|---|---|---|---|
| WS /v1/driver/stream {lat, lng, seq} | position reports | seq: older reports lose | no reply | Socket closes; the app reconnects |
| POST /v1/trips {pickup, dropoff} + Idempotency-Key | request a ride | the key | 201 + trip, surge | 409 open trip, 422 outside the area |
| POST /v1/offers/{id}/accept | driver accepts | a repeat returns the trip | 200 + trip | 410 offer gone |
| POST /v1/offers/{id}/decline | driver declines | changes only a pending offer | 204 | 410 |
| POST /v1/trips/{id}/events {type} | arrived, started, ended | a repeat changes 0 rows | 200 + state | 409 wrong state |
| GET /v1/me/current | the first call after a reconnect | a read | 200 + trip or offer | 401 |
A request carries an idempotency key. An accept is safe to retry, because a repeat returns the same trip.
| Redis key | holds | lives |
|---|---|---|
| drivers:{region} | GEO set of idle drivers | Until matched or silent |
| seen:{city} | Sorted set: driver, last report time | Swept after 30 s |
| lock:{driver:id} | The lease during an offer | 20 s |
| surge:{cell} | Multiplier | 30 s |
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';- 1Fixed at request time, so a later change in surge never changes a quoted price.
- 2The index that makes a double booking impossible, whatever the application does.
- 3One open trip per rider, so a double tap cannot book two cars.
- 4The accept compares this with the time in its own WHERE clause. No timer has to fire.
- 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Redis | GEOADD with many members | A new position replaces the old one; 281k updates a second in batches of 100. | Store and venue lookups |
| Redis | GEOSEARCH BYRADIUS ASC COUNT | The nearest k, with distance and position. | Nearby search |
| Redis | A GEO key is a sorted set | Limit No TTL per member, so a sweeper removes silent drivers. ZREM removes a match. | |
| Redis | SET NX PX with a token | A lease on a driver during an offer. | Locks, idempotency |
| Redis | Sorted set by time | The seen set: drivers silent for 30 s, in one range read. | Delay queues |
| Redis | Pipelining | One round trip for a batch of reports, or for a rider's regions. | Any batch |
| Postgres | UPDATE ... WHERE state = expected | Accept and each trip step happen once. The row count reports the winner. | Bookings, inventory |
| Postgres | Partial unique index | At most one active trip per driver, enforced by the database. | One open order per user |
| Postgres | Transactions | The offer and the trip change together, or not at all. | Every multi-row rule |
| Service | Hungarian method | The lowest total pickup for one batch: 2.3 ms for 200 riders, measured. | Task assignment |
| Gateway | Sticky sockets, in-memory buffer | Pushes offers, and drops old reports before they reach Redis. | Chat, presence |
| Kafka | Partitioned log | Trip 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.
| index for moving points | status | why |
|---|---|---|
| Postgres row per driver, GiST index | Small fleet | Each update writes a row and its index, and leaves a dead tuple |
| Redis GEO, one key per city | To start | 281k batched updates a second |
| Redis GEO, one key per region | Approved | Small keys, one dispatcher per region |
| Quadtree in process memory | Hot core only | Fast, but a restart loses it (B11) |
| Fixed-radius search | Not approved | Slow where drivers are dense, empty where they are not |
| Circle that widens | Approved | Small where dense, wide only where it must be |
| report every | index error | mean pickup |
|---|---|---|
| 1 s | 0 m | 881 m |
| 4 s | 7 m | 888 m |
| 16 s | 34 m | 914 m |
| 60 s | 109 m | 1,048 m |
| core search | p50, alone | searches/s | updates/s |
|---|---|---|---|
| 3 km fixed | 6.1 ms | 171/s | 2,095/s |
| 500 m, then wider | 0.5 ms | 2,059/s | 25,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.
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- 1Reports arrive faster than matches need them. Report every 4 s, and the index is only 7 m off on average.
- 2A parked car costs no write. The seen set still needs a heartbeat, which a real gateway sends less often.
- 3A driver must be in one region only, or a search could return them twice.
- 4It is one member of a sorted set, so nothing expires by itself.
Tested source Go: keep the newest report · Go: regions, search, sweep
// 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
}
// 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
}
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- 1A sorted GEOSEARCH reads every member in the circle. In the lab core, 500 m already held 20 drivers.
- 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.
| supply | method | mean pickup | wait for a match | riders served |
|---|---|---|---|---|
| Many idle | Greedy | 439 m | 0.0 s | 100.0% |
| 5 s batch | 435 m | 2.0 s | 100.0% | |
| Few idle | Greedy | 903 m | 0.1 s | 100.0% |
| 15 s batch | 861 m | 7.0 s | 100.0% | |
| Too few | Greedy | 2,993 m | 82.5 s | 76.7% |
| 5 s batch | 1,502 m | 30.7 s | 90.5% |
| method | status | use it when |
|---|---|---|
| Greedy nearest, at once | Many idle | Most riders have a driver close by |
| Batch, lowest total cost | Short supply | Riders queue for few drivers |
| Batch with a long window | Few idle | A 15 s window adds about 7 s of wait |
| Fixed region quota | Not approved | Supply 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.
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- 1The dispatcher sees reports, not cars. The run measures the pickup from where the car really is.
- 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.
- 3A rider with no pair keeps their place. A rider who waits too long gives up, which the simulation counts.
- 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
// 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
}
// 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
}
// 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%.
| design | status | double booked | offers refused | stopped by lease |
|---|---|---|---|---|
| Read, then write | Not approved | 16 drivers | - | - |
| Conditional update, unique index | Approved | 0 | 64 | - |
| Lease, then both | Approved | 0 | 0 | 89 |
| Lease alone | Not approved | An 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.
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- 1A fast filter, about one Redis call. A dispatcher that loses it moves to the next candidate.
- 2The time is part of the condition, so a late tap changes 0 rows.
- 3A rider who cancelled first wins. The transaction then rolls the offer back too.
- 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
// 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
}
}
// 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
}
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';
// 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.
| ETA method | status | use |
|---|---|---|
| Straight line ÷ speed | First filter only | Wrong pick in 13% of matches, about 64 m worse each |
| Road model by cell and hour | Approved | Ranking many candidates |
| Routing service, live traffic | Few candidates | The final choice and the rider's screen |
| cell | open requests | idle drivers | surge |
|---|---|---|---|
| tdr1x | 66 | 29 | ×2.3 |
| tdr1w | 142 | 64 | ×2.2 |
| tdr1s | 23 | 18 | ×1.3 |
| tdr1v | 68 | 71 | ×1.0 |
| tdr1t | 40 | 41 | ×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 trip | The trip and its state, from Postgres |
| Had an offer, still open | The offer and the time left |
| Had an offer, now expired | Idle. The trip went to someone else |
| Sends old positions | Older reports lose to newer ones |
| Was swept from the index | The next report puts it back |
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- 1The lab ranks by a street grid at a fixed speed, a stand-in for this model.
- 2A step per 0.1 keeps a price from flickering. A real system also smooths it over time.
- 3The phone holds no truth. It asks, and the server answers from Postgres.
Tested source Go: resume · Go: surge by cell
// 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
}
// 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.
- requested
- matched
- arrived
- in progress
- completed
A rider asks for a car. Postgres stores the trip as requested.
| offer to | state in Postgres |
|---|---|
| No offers yet. | |
- 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.
| event | result | why it is safe | saved by |
|---|---|---|---|
| Two dispatchers pick one driver | Both try to offer. | The lease stops one. If it fails, the unique index does. | Unique index |
| A driver stays silent | The offer waits. | It expires in 15 s, and the next candidate gets one. | expires_at |
| A late accept arrives | The offer has expired. | The condition fails: 0 rows, and the app says the trip is gone. | Conditional update |
| Accept and cancel race | Both act on one trip. | One conditional update wins; the lab ran this 60 times. | Row lock |
| Redis fails over and loses keys | Positions and leases vanish. | Reports rebuild the index in about 4 s. Postgres still guards every match. | Unique index |
| A driver loses signal | They stay in the index. | The sweeper removes them after 30 s; an offer to them expires. | Seen set |
| A dispatcher dies with a lease | The driver looks taken. | The lease ends in 20 s; another dispatcher takes the region. | Lease TTL |
| Old reports arrive after a reconnect | They could move the car back. | Each report has a sequence number; older reports lose. | seq |
| A surge job stops | Multipliers go stale. | They expire, and the price falls back to 1. | TTL |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One 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. |
| 2 | Gateways 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. |
| 3 | Region 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. |
| 4 | Batched 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. |
| 5 | Shards 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 10 known
A phone sends a position every 4 s. Why store only the newest one in the index?
Two dispatchers see one idle driver. What stops a double booking?
If the database alone is correct, why keep the lease?
A driver taps accept twice because the reply was lost. What happens?
A driver taps accept one second after the offer expired. What happens?
Does batching always beat greedy nearest?
Why did the same fleet serve 91% of riders with batching, against 77% greedy?
Why not search 3 km around every rider?
Why rank by road ETA and not by straight line?
A driver loses signal and never reports again. What removes them from the index?
- 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.