# System Design Drill Day 19: Geospatial Search and "What's Near Me?"

You open a delivery app in Baneshwor and it lists shops "near you". A few minutes after you order, a rider somewhere in the valley gets a ping, and somehow the same order is never offered to two riders at once.

"Find things within X km" shows up everywhere, from Uber and Yelp to Foodmandu and Pathao. The version here is same-day delivery for an online marketplace in Kathmandu Valley: store search, live rider locations, and dispatching each order to the nearest free rider.

## Core concepts

The naive query is `WHERE haversine(lat, lng, :me) < 3` over the whole table. It runs the distance maths on every row, and a normal B-tree index can't help, because the filter covers two dimensions at once.

A bounding box is the cheap first fix. Draw a square around the user (`lat BETWEEN a AND b AND lng BETWEEN c AND d`) to cut the rows down, then run the exact distance check only on what's left.

A geohash goes further. It turns a lat/lng into a short string in which a shared prefix means a nearby cell, and each extra character shrinks the cell. Five characters cover about 4.9 × 4.9 km, six about 1.2 × 0.6 km, and seven about 150 × 150 m. "Nearby" becomes a prefix lookup, which ordinary indexes handle well.

The catch is cell edges. Two points a few metres apart can sit in different cells with different prefixes, so the search always covers the user's cell plus its 8 neighbours and then filters by real distance.

![A 3 by 3 grid of geohash cells with the user's cell in the middle: a nearby point just across the cell border has a different prefix, so the search covers the center cell plus all 8 neighbours and then filters by real distance](https://cdn.hashnode.com/uploads/covers/5fdde6221485f22e24b34a2c/131b8c55-86e7-4ab4-9d4c-7ea117138981.png align="center")

*Figure 1: Search the cell and its 8 neighbours, then filter by actual distance.*

Quadtrees, S2 and H3 are other ways to split the map into cells. Quadtrees split crowded areas more finely, and H3 (Uber's hexagon grid) is popular because every neighbouring hexagon is the same distance away. For an interview, knowing they exist is usually enough.

MySQL can do this natively. A `POINT SRID 4326` column with a `SPATIAL INDEX` (an R-tree underneath) is queried with `MBRContains` for the box and `ST_Distance_Sphere` for the exact check. It suits things that don't move, like shops. Watch the axis order: with SRID 4326, MySQL expects `POINT(lat lng)`, latitude first, while Redis `GEOADD` takes longitude first. Mixing the two up silently swaps your points.

Redis GEO suits things that move every few seconds, like riders. `GEOADD` and `GEOSEARCH ... BYRADIUS` store geohash scores in a sorted set and are very fast. Stale entries are removed with `ZREM`.

Straight-line distance also isn't travel time. It ignores the Bagmati, one-way streets and Kathmandu traffic, so use it to find candidates and rank only the top few by road ETA.

> **Pause and think:** You search only the user's own geohash-6 cell for shops, and the user is standing right at its edge. What do you miss?

<details><summary>Show answer</summary>
<p>Shops a few metres away that happen to fall in the neighbouring cell, because their geohash has a different prefix. Always include the 8 neighbouring cells and then filter by real distance.</p>
</details>

## The design problem

An online marketplace is launching same-day delivery in Kathmandu Valley. Customers should see "stores near me" within 3 km, out of about 20,000 merchants. About 2,000 riders are active at peak, and each rider app sends GPS every 5 seconds.

When an order is ready, the nearest available rider should be offered it within 2 minutes. The rider has 20 seconds to accept, after which the offer moves to the next rider. A rider must never hold two offers at once, and an order must never end up with two riders. Live tracking for customers already exists (Day 15), and the stack is 3 Laravel app servers, MySQL and Redis.

Sketch where merchant and rider locations live, the dispatch flow from "order ready" to "rider accepted", and what happens when a rider ignores the offer or their phone dies.

> **Try the problem before reading the solution.**

## Questions to think about

1. Why is a geohash prefix search alone wrong near cell edges, and how do you fix it?
2. Why shouldn't rider locations be a MySQL row updated every 5 seconds, and where should they live instead?
3. How do you guarantee one rider gets one offer at a time, and what happens when they don't respond?

## Model solution

### Stores near me (they don't move)

Store a MySQL `POINT` with a `SPATIAL INDEX`. Query with `MBRContains` for the 3 km box, then `ST_Distance_Sphere <= 3000`, order by distance and limit to 50. Many nearby customers share a geohash-6 cell, so cache the results per cell in Redis for about 10 minutes. If merchants only deliver inside a zone, add an `ST_Contains` check against the zone polygon.

### Rider locations (moving)

2,000 riders pinging every 5 seconds is about 400 writes per second. Redis handles that trivially, while MySQL row updates would bring lock churn, binlog volume and replication lag (Day 4). A thin ping endpoint, with no Eloquent model loading, runs three commands:

- `HSET rider:{id}` with lat, lng, timestamp and status
- `ZADD riders:heartbeat now rider_id`
- `GEOADD riders:available:ktm lng lat rider_id`, but only when the rider's status is available

That condition matters. Dispatch removes a rider from the available set while they hold an offer, and without the status check their next ping, about 5 seconds later, would add them straight back and they could be offered a second order while busy. The status check and the `GEOADD` belong in one small Lua script so they can't race with dispatch. Live tracking of busy riders reads the position from `rider:{id}`.

A scheduled job every 30 seconds removes riders not seen for 60 seconds from the available set, so dead phones drop out. Pings can be adaptive, every 5 seconds while moving and every 30 while idle. Location history goes to a queue or Redis stream and is batch-inserted into MySQL or object storage; Redis holds only live state and refills from pings within seconds if it's lost.

![Where each kind of location lives: static merchant locations in a MySQL POINT column with a spatial index and per-cell Redis cache, moving rider locations in Redis GEO plus heartbeat and hash keys, with history batched to MySQL or object storage](https://cdn.hashnode.com/uploads/covers/5fdde6221485f22e24b34a2c/c24e98db-dea7-4247-829f-47829722aa6b.png align="center")

*Figure 2: Static data in MySQL with a spatial index, hot moving data in Redis GEO.*

### Dispatch

1. When an order is marked ready, the outbox (Day 11) queues a `DispatchRider` job.
2. The job runs `GEOSEARCH riders:available:ktm FROMLONLAT ... BYRADIUS 2 km ASC COUNT 20`, widening to 4 km and then 6 km if there are too few results.
3. It ranks the top 5 by road ETA from a routing API (with cached results), breaks ties by fairness (idle time or trips today) and rating, and skips anyone in `order:{id}:declined`.
4. A Lua script claims a rider atomically: if the rider is still in the available set, it runs `SET offer:rider:{id} order_id NX EX 20` and `ZREM`s them from the set in one step. If the claim fails, the job tries the next rider. This is the Day 8 lock idea, kept small and short-lived.
5. The offer is pushed over WebSocket or FCM.
6. On accept, the server checks that `offer:rider:{id}` still equals this order. MySQL is the source of truth, so it runs `UPDATE orders SET rider_id=? WHERE id=? AND rider_id IS NULL`; zero changed rows means someone else already got it. On success the rider's status in `rider:{id}` becomes busy, so pings stop adding them to the available set until the delivery is done.
7. A delayed job fires at 20 seconds. If the order is still unassigned, the rider goes into the declined set, their status goes back to available (so their next ping re-adds them) if they're still sending heartbeats, and the next rider gets the offer. After about 5 attempts or 2 minutes, the order is offered to the top 3 at once (the first conditional `UPDATE` wins) or escalated to ops.

![Dispatch sequence: order ready triggers the DispatchRider job, GEOSEARCH finds nearby riders, the top candidates are ranked by ETA, a Lua script atomically claims one rider with a 20 second offer, the rider accepts and a conditional UPDATE assigns the order, or the offer times out and moves to the next rider](https://cdn.hashnode.com/uploads/covers/5fdde6221485f22e24b34a2c/221f2cb3-9229-4f5c-900c-618d788844d2.png align="center")

*Figure 3: From "order ready" to "rider assigned", with the 20 second timeout path.*

> **Pause and think:** Two dispatch jobs for two different orders pick the same rider at the same moment. What stops that rider from getting both offers?

<details><summary>Show answer</summary>
<p>The Lua claim. It checks the rider is still in the available set, sets <code>offer:rider:{id}</code> with <code>NX</code> and removes them from the set in one atomic step. The second job's claim fails, so it moves on to its next candidate.</p>
</details>

### Answers to the questions

<details><summary>Show answer</summary>
<p><strong>1.</strong> Two points a few metres apart can sit in different cells with different prefixes, so a search of one cell misses shops just across the border. Search the user's cell plus its 8 neighbours, then filter by real distance.</p>
<p><strong>2.</strong> 2,000 riders every 5 seconds is about 400 writes per second, which as MySQL row updates means lock churn, binlog volume and replication lag. Live positions belong in Redis GEO, with a heartbeat set and a hash per rider, and history is batch-inserted into MySQL or object storage.</p>
<p><strong>3.</strong> A Lua script claims the rider atomically: it checks they're still in the available set, sets <code>offer:rider:{id}</code> with <code>NX EX 20</code> and removes them from the set in one step, so a second dispatch job fails its claim. If the rider doesn't accept within 20 seconds, a delayed job adds them to the order's declined set and offers the order to the next rider, escalating after about 5 attempts or 2 minutes.</p>
</details>

### Scaling later

Kathmandu fits in one Redis. For more cities, use one geo set per city or shard by geohash prefix, which is Day 6 sharding again with the city as a natural partition key.

## Interview one-liner

> "Shops are static, so they go in a spatial index in the DB and get cached per cell. Riders are hot moving state, so they live in Redis GEO with heartbeats. Find candidates by straight-line distance, rank them by ETA, claim atomically, and let the DB make the final assignment with a conditional update."

## Conclusion

Keep static locations in a spatial index and moving ones in Redis, and never search a single geohash cell without its neighbours. For dispatch, the atomic claim in Redis prevents double offers, but only the conditional `UPDATE` in MySQL should decide who actually gets the order.

## Try it yourself

Start Redis locally and `GEOADD` a few dozen fake riders around Kathmandu (any coordinates in the valley will do). Run `GEOSEARCH ... FROMLONLAT ... BYRADIUS 2 km ASC COUNT 5` from a point of your choice and check that the results make sense.

Then write the Lua claim script from step 4 and call it twice for the same rider from two terminals. Only one call should win.

---

This is part of my daily [System Design Drills](https://blog.anishansari.com.np/series/system-design-drills) series.
