# Matching riders to drivers with H3 hexagons, Redis sets and one Lua script

Source: https://systemdesignsim.com/blog/uber-driver-matching-h3-go

Build log

A ride-hailing dispatch core in Go: H3 hexagon cells in Redis, k-ring search and an atomic Lua claim, with measured latency and five fixes before production.

By [Winson GR](https://github.com/winsongr) · October 26, 2026 · 11 min read · [Source on GitHub](https://github.com/winsongr/uber-h3-matching)

A ride-hailing app answers one question all day: which available driver is closest to this rider, and how do we make sure two riders don’t get the same one? This post walks through a small Go service that answers it with H3 - the hexagonal grid over the whole planet that Uber open-sourced - plus Redis for live driver state and PostgreSQL for an audit log of matches. The full source, integration tests and Docker setup are [on GitHub](https://github.com/winsongr/uber-h3-matching).

The headline result: a match against a driver in the rider’s own cell takes **13.7 ms at p50 and 23.7 ms at p99**, a driver location update **9.5 ms at p50**, and a 20-goroutine race for one driver produces **exactly one claim**. All of those numbers include about 8 ms of Docker Desktop networking, by the repo’s own account. Five things need fixing before production, and two of them can put one driver in two cars - they are covered at the end.

## The constraints that shape the design

* **Writes dominate.** Every online driver sends a location every few seconds. The repo’s simulator uses 3 seconds, which is 333 writes per second for 1,000 drivers - far more than ride requests.
* **The search must stay small.** A ride request should look at drivers near the rider, not every driver in the city.
* **A driver goes to one rider.** Two simultaneous requests often find the same nearest driver. Only one can win.

## Why hexagons

H3 divides the Earth into hexagonal cells at 16 resolutions. At resolution 9, which this service uses, the average cell covers **0.105 km²** with an average edge of about 200 m, according to [H3’s published table](https://h3geo.org/docs/core-library/restable/). A latitude and longitude become a 64-bit cell ID with one in-process call, no network involved.

The useful property is the neighbourhood: every hexagon has six neighbours, all sharing an edge and all the same distance away, where a square grid has edge and corner neighbours at two distances. H3’s `GridDisk(cell, k)` returns the cell plus every cell within `k` steps: 1 cell at k = 0, 7 at k = 1, 19 at k = 2, and `3k² + 3k + 1` in general, so 91 at k = 5.

So the index is simple: each cell gets a Redis set, `h3:{cell}`, holding the IDs of available drivers in it.

![Match path of the H3 driver matcher. On the left, the rider’s resolution-9 cell with the first and second rings of hexagons around it, a few available drivers, and one stale entry left in a set. On the right, the six steps of a match request: convert the rider’s position to a cell, list the cells in the disk, read the cell sets in one pipeline, fetch each candidate’s hash, claim the nearest with a Lua script, and queue the audit record.](https://systemdesignsim.com/_astro/h3-match-path.CKkx5vDN_ZAHNWj.svg)![Match path of the H3 driver matcher. On the left, the rider’s resolution-9 cell with the first and second rings of hexagons around it, a few available drivers, and one stale entry left in a set. On the right, the six steps of a match request: convert the rider’s position to a cell, list the cells in the disk, read the cell sets in one pipeline, fetch each candidate’s hash, claim the nearest with a Lua script, and queue the audit record.](https://systemdesignsim.com/_astro/h3-match-path.dark.J9LvaLYQ_ZAHNWj.svg)

## The write path: a location update

`PUT /v1/drivers/{id}/location` converts the coordinates to a cell in Go, then runs one Lua script in Redis. The script has to move the driver from its old cell set to its new one, and nothing may observe the driver in both or neither:

```
local oldCell = redis.call('HGET', driverKey, 'h3cell')
if oldCell and oldCell ~= newCell then
    redis.call('SREM', 'h3:' .. oldCell, driverID)
end

local exists = redis.call('EXISTS', driverKey)
if exists == 0 then
    redis.call('HSET', driverKey, 'status', 'available')
end

redis.call('HSET', driverKey,
    'lat', lat,
    'lng', lng,
    'h3cell', newCell,
    'updated_at', updatedAt)
redis.call('EXPIRE', driverKey, driverTTL)

local status = redis.call('HGET', driverKey, 'status')
if status == 'available' then
    redis.call('SADD', newCellKey, driverID)
    redis.call('EXPIRE', newCellKey, cellTTL)
end
```

Redis runs a script without interleaving other commands, so the move happens as one step, in one round trip.

Two details matter later. A driver whose hash doesn’t exist is created as `available`. And there are two TTLs: 90 seconds on the driver hash, 60 on the cell set, so that - per the README - a silent driver drops out of matching after 60 seconds with no cleanup job.

## The read path: a match request

`POST /v1/matches` searches outwards from the rider’s cell, one ring at a time, and stops at the first ring that contains anyone:

```
for k := 0; k <= m.maxRings; k++ {
	cells, err := geo.GridDisk(riderCell, k)
	if err != nil {
		return nil, fmt.Errorf("grid disk k=%d: %w", k, err)
	}

	ids, err := m.drivers.AvailableInCells(ctx, cells)
	if err != nil {
		return nil, fmt.Errorf("available in cells: %w", err)
	}
	if len(ids) == 0 {
		continue
	}

	candidates := m.rankByDistance(ctx, ids, req.Lat, req.Lng)
	for _, c := range candidates {
		claimed, err := m.drivers.ClaimDriver(ctx, c.driver.ID, c.driver.H3Cell)
		if err != nil {
			return nil, fmt.Errorf("claim driver: %w", err)
		}
		if !claimed {
			metrics.ClaimConflicts.Inc()
			continue
		}
		_ = m.matches.InsertMatch(ctx, *result)
		return result, nil
	}
}
return nil, domain.ErrNoDriverFound
```

`AvailableInCells` sends one `SMEMBERS` per cell in a single pipeline, so each ring level costs one round trip. `rankByDistance` fetches each candidate’s hash with `HGETALL`, drops anyone not `available`, and sorts the rest by haversine distance to the rider.

If no ring up to k = 5 holds a driver, the API returns `204 No Content`. The search area is bounded however many drivers are online.

### The claim: one Lua script

Two requests can rank the same driver first. A plain `HGET status` followed by `HSET status matched` would let both read `available` and both write `matched`. The claim script checks and writes in one atomic step:

```
local status = redis.call('HGET', driverKey, 'status')
if status ~= 'available' then
    return 0
end

redis.call('HSET', driverKey, 'status', 'matched')
redis.call('SREM', cellKey, driverID)
return 1
```

The loser gets 0, counts a claim conflict in Prometheus, and tries its next candidate. The integration test `TestConcurrentMatchNoDoubleBooking` runs this for real against a Redis 7 container: one driver, 20 goroutines calling `Match` at once, and it asserts exactly one success.

### The audit log stays off the hot path

Once the claim succeeds, the rider gets the response. The match record goes to PostgreSQL through a buffered channel and a background worker that makes three attempts, waiting 100 ms and then 200 ms between them (the README’s third, 400 ms step is never reached):

```
func (s *Store) InsertMatch(ctx context.Context, result domain.MatchResult) error {
	metrics.PGQueueDepth.Set(float64(len(s.queue)))
	select {
	case s.queue <- result:
		return nil
	default:
		metrics.PGWriteDropped.Inc()
		s.log.Warn("pg write queue full, dropping match", "match_id", result.MatchID)
		return fmt.Errorf("pg write queue full")
	}
}
```

A slow database never delays a match. A full queue (256 records by default) drops the record, and the matcher ignores the error.

## Benchmarks

The repo reports single-request latency measured with curl on an Apple M4 against the Docker Compose stack, 50-100 samples per row, with drivers placed so that each row hits a known ring depth (checked with `rings_expanded` in each response). The README notes that Docker Desktop’s userspace proxy adds about 8 ms to every figure.

| Operation                             | p50         | p99         | What runs in Redis              |
| ------------------------------------- | ----------- | ----------- | ------------------------------- |
| Driver location update                | 9.5 ms      | 15.4 ms     | One Lua script                  |
| Match, driver in rider’s cell (k = 0) | **13.7 ms** | **23.7 ms** | SMEMBERS, HGETALL, Lua claim    |
| Match, driver one ring out (k = 1)    | 14.0 ms     | 18.7 ms     | 2 pipelines, HGETALL, Lua claim |
| Match, driver two rings out (k = 2)   | 14.7 ms     | 24.6 ms     | 3 pipelines, HGETALL, Lua claim |
| No driver within k = 5                | 11.2 ms     | 14.4 ms     | 6 pipelines, all sets empty     |

Ring depth barely matters: k = 2 is 1 ms slower than k = 0 at the median, because each extra ring is one more pipelined round trip. The not-found path is the fastest, because it never fetches a hash or runs a claim. Latency follows round trips, not search area.

These are latency samples, not throughput. The repo ships a k6 script but publishes no k6 results, so this post quotes no throughput figure.

## What to change before production

Reading the code against real dispatch situations turns up five issues. The first two concern the driver’s status, which lives only in Redis.

![Driver status in Redis. A new hash starts as available. The claim script moves it to matched. Location updates keep a matched driver matched and reset its 90-second TTL. If the hash expires, Redis restarts or the key is evicted, the next location update recreates the driver as available.](https://systemdesignsim.com/_astro/h3-match-driver-states.C2TU-5Dn_Z2f2qr0.svg)![Driver status in Redis. A new hash starts as available. The claim script moves it to matched. Location updates keep a matched driver matched and reset its 90-second TTL. If the hash expires, Redis restarts or the key is evicted, the next location update recreates the driver as available.](https://systemdesignsim.com/_astro/h3-match-driver-states.dark.DzQzoue3_Z2f2qr0.svg)

**1. A matched driver is never offered again.** The claim script sets `status` to `matched`, and nothing ever sets it back. There is no endpoint to accept, cancel or finish a trip; `in_trip` and `offline` are declared in `internal/domain/driver.go` but no code writes them. Every location update resets the hash’s 90-second TTL and keeps the status, so a driver who keeps their app open stays `matched` forever. The Docker setup’s simulator runs 500 drivers, so after 500 matches every request gets `204 No Content`. The fix is an explicit state machine - accept, cancel, start and end trip - each as a compare-and-set Lua script like the claim, with cancel and end trip putting the driver back in their cell set.

**2. A matched driver can silently become available again - and be booked twice.** The location script treats a missing hash as a new driver: `EXISTS == 0` sets `status` to `available`. A hash goes missing in three ordinary ways: the driver is in a tunnel for 90 seconds and it expires; Redis restarts, and `docker-compose.yml` runs it with `--save ""` and `--appendonly no`, so every key is lost; or Redis evicts it under `allkeys-lru`. Each time, the driver - still carrying the first rider - reappears as `available` on the next ping and can be claimed by a second rider. The atomic claim can only protect state that exists. The fix is to stop deriving “available” from absence: a new or returning driver should come back as `offline` until the app says otherwise, the active trip should be recorded durably (PostgreSQL, written before the response) and checked when a driver comes back, and Redis should run with `noeviction` and persistence for this data.

**3. Stale drivers stay matchable for up to 90 seconds, not 60.** A Redis TTL belongs to a whole key, not to a set member. The location script calls `EXPIRE h3:{cell} 60` on every update in that cell, so in a busy cell the set never expires, and a driver whose phone died stays in it. `rankByDistance` only checks `status`, not `updated_at`, so that driver is offered to riders until their hash expires at 90 seconds. With 3-second pings, that is 30 missed updates before the system notices. After the hash expires the ID stays in the set as long as the cell is busy, costing an `HGETALL` on every search. The repo’s `TestCellSetExpires` passes because it has one driver alone in a cell. The fix is a sorted set per cell scored by last update time, read with `ZRANGEBYSCORE` from a few pings ago and trimmed with `ZREMRANGEBYSCORE`. The cheap fix is to reject candidates whose `updated_at`, already in the hash, is older than about 15 seconds.

**4. A retried request claims a second driver.** `POST /v1/matches` has no idempotency key and nothing that links a rider to an active match. If the claim succeeds but the response is lost - a mobile timeout, a dropped connection - the app retries, and the retry claims the next nearest driver. The first driver is now matched to a rider who never heard about it, and by issue 1 stays that way. The concurrency test uses the same `rider_id` for all 20 goroutines and passes only because there is one driver; with two drivers, that one rider would get two. The fix is to record the match against the rider in the same script that claims the driver - `SET rider:{id}:match <match_id> NX` alongside the `HSET` - and return the existing match when it is already set.

**5. The search does more work than it reports, and doesn’t always find the nearest driver.** `GridDisk(riderCell, k)` returns the whole disk, not the ring at distance `k`, so every level re-reads the inner cells it has already found empty. A search that finds nobody sends 1 + 7 + 19 + 37 + 61 + 91 = **216** `SMEMBERS`, not the 91 the README describes. Candidates are then fetched with one sequential `HGETALL` each, so a cell with 30 drivers costs 30 round trips before the first claim. And stopping at the first non-empty ring is not the same as finding the nearest driver: a driver at the far edge of the rider’s own cell can be farther than one just across the boundary in ring 1. The fix is to call `GridDiskDistances(riderCell, maxRings)` once (h3-go v4 provides it) and query only the new ring at each step, fetch candidates with one pipelined `HMGET lat lng status updated_at`, and search one ring beyond the first hit before choosing.

Two smaller notes. The audit log is described as durable, but it is the only record of a match outside Redis and it is lossy by design: a full queue drops the record, a crash loses whatever is queued, and a single worker inserts one row at a time, so a slow PostgreSQL fills the queue quickly. And the README says `h3_match_duration_seconds` is labelled `matched` or `not_found`; the code always records the label `done`, so the two can’t be told apart on a dashboard.

## What a production dispatcher adds

| Production dispatch                                                        | This project                            |
| -------------------------------------------------------------------------- | --------------------------------------- |
| Location updates through a stream, fanned out to matching, ETA and pricing | Direct HTTP PUT into Redis              |
| Candidates ranked by road ETA                                              | Straight-line haversine distance        |
| Sharded, replicated in-memory state                                        | One Redis node                          |
| Trip state in a durable store                                              | Status field in a Redis hash with a TTL |

One detail blocks a move to Redis Cluster, which needs every key a script touches declared in `KEYS` and in one hash slot. The location script builds `'h3:' .. oldCell` inside Lua, and both scripts touch `driver:{id}` and `h3:{cell}`, which hash to different slots. Hash-tagging keys by city - `{blr}:driver:42`, `{blr}:h3:...` - keeps each city in one slot.

The core ideas carry over: a fixed grid that bounds the search, expansion that stops early, and one atomic compare-and-set as the only way a driver changes hands.

## Try the design yourself

Matching is the heart of ride-hailing, but the system around it - location ingestion, trip state, pricing - is where most of the scaling work happens. [Design Uber](https://systemdesignsim.com/system-design/uber) walks through that whole design. And since the worst bugs above appear when state disappears, [the Chaos Monkey challenge](https://systemdesignsim.com/challenges/chaos-monkey) is a good next step: keep a service up while its busiest API server group is killed mid-run, then compare your design with the reference.

The full source, with `docker compose up` to start Redis, PostgreSQL, Prometheus, the API and a 500-driver simulator, is at [github.com/winsongr/uber-h3-matching](https://github.com/winsongr/uber-h3-matching).

[GuideDesign an UberThe interview walkthrough, with a design you can run.](https://systemdesignsim.com/system-design/uber)[ChallengeChaos MonkeyA monkey will kill your busiest API server mid-run. Design for redundancy so users never notice.](https://systemdesignsim.com/challenges/chaos-monkey)

## One system design problem a week

A real scenario, its constraints, and where the obvious design breaks.

## Now break one yourself.

The first challenge takes about two minutes. No signup.

[Design your first system](https://systemdesignsim.com/challenges/hello-load-balancer)
