Redis GEO and SET NX PX
You can store rider coordinates with Redis GEO, search by distance, and reserve an order with a short-lived claim before implementing rider assignment.
Learning outcomes
- Explain how Redis GEO stores rider coordinates and why
riders:onlineneeds separate presence keys. - Construct GEOSEARCH queries that find the closest riders within a requested radius and count.
- Explain how SET NX PX prevents competing workers from acquiring the same order claim.
- Use atomic compare-and-delete to release a claim without deleting another rider's ownership.
A restaurant marks an order READY, and the worker needs to offer it to a nearby rider. A coordinate in Redis does not prove that the rider is still online, and two workers must not both believe they own the same order. You need geographic search for rider discovery and a temporary claim for assignment.
Rider presence service adds location and presence operations to the Riders service. Rider assignment worker uses those results to assign READY orders with a 30-second claim.
Rider coordinates in Redis GEO
Rider locations change frequently. Storing every location update in MySQL would add database work for information that is temporary and changes every few seconds.
Redis GEO provides commands to store geographic coordinates and search for nearby members. Redis manages the geographic indexing, so you do not need to calculate distances between every rider and the restaurant yourself.
The service uses one GEO key:
riders:onlineEach member is a rider ID represented as a decimal string. Redis stores its longitude and latitude.
For example, a rider reporting latitude 28.461 and longitude 77.031 produces this command:
GEOADD riders:online 77.031 28.461 101The argument order is important. Redis expects longitude before latitude, even though application code often receives latitude first.
In Go, the Redis client uses named fields:
location := &redis.GeoLocation{
Name: "101",
Longitude: 77.031,
Latitude: 28.461,
}
err := rdb.GeoAdd(ctx, "riders:online", location).Err()If rider 101 already exists, another GEOADD updates the existing member's coordinates. It does not create a second member.
This makes location updates inexpensive. Each new location report can update the same GEO member.
Location data and expiration
Redis GEO has an important limitation: individual GEO members cannot have their own TTL.
The riders:online key can expire as a whole, but that would remove every rider's position at once. You cannot ask Redis to expire only rider 101 because that rider stopped reporting.
A rider could close the application while their last coordinate remains in Redis. The assignment worker might then offer an order to someone who is no longer online.
You need a separate presence key.
Rider presence with a seen key
Store recent activity in a key for each rider:
rider:seen:101The key contains 1 and expires after 15 seconds:
SET rider:seen:101 1 EX 15Every location update refreshes this expiry. If the rider stops reporting, Redis removes the seen key automatically.
A location update therefore has two responsibilities:
- Update the rider's coordinates in
riders:online. - Refresh the rider's seen key with a 15-second TTL.
You can send both Redis commands through a pipeline:
pipe := rdb.Pipeline()
pipe.GeoAdd(ctx, "riders:online", &redis.GeoLocation{
Name: "101",
Longitude: 77.031,
Latitude: 28.461,
})
pipe.Set(ctx, "rider:seen:101", "1", 15*time.Second)
_, err := pipe.Exec(ctx)The pipeline reduces network round trips by sending the commands together. It does not make them one atomic transaction.
The 15-second TTL gives the rider some room for network delays. The location reporting mechanism must refresh the key before it expires.
Explicit offline operations
When a rider goes offline through the API, remove both pieces of data.
pipe := rdb.Pipeline()
pipe.ZRem(ctx, "riders:online", "101")
pipe.Del(ctx, "rider:seen:101")
_, err := pipe.Exec(ctx)ZREM works because Redis GEO uses sorted-set storage. DEL removes the corresponding presence key.
You also need to handle unexpected disconnections. A rider might lose connectivity without calling the offline endpoint. In that case, the seen key expires while the GEO member remains.
Searching for nearby riders
When a restaurant marks an order READY, the worker needs to find nearby riders. Redis provides GEOSEARCH for this operation.
The command searches around a geographic coordinate and supports a radius, distance ordering and result limit.
Consider a restaurant at longitude 77.031 and latitude 28.461. To find up to five riders within five kilometres, use:
GEOSEARCH riders:online FROMLONLAT 77.031 28.461 BYRADIUS 5 km ASC COUNT 5Each part has a specific purpose:
FROMLONLATsupplies the search center using longitude and latitude.BYRADIUS 5 kmrestricts the search to five kilometres.ASCorders results from nearest to farthest.COUNT 5limits the query to five members.
The result contains rider IDs, not proof that those riders are still online.
The Go Redis client exposes this through GeoSearch:
ids, err := rdb.GeoSearch(ctx, "riders:online",
&redis.GeoSearchQuery{
Longitude: 77.031,
Latitude: 28.461,
Radius: 5,
RadiusUnit: "km",
Sort: "ASC",
Count: 5,
},
).Result()The returned IDs are strings. Your service converts valid rider IDs to int64 before returning them to its caller.
Filtering stale riders
After the geographic search, check the seen key for every returned member.
A missing key means the rider stopped reporting. Exclude that rider and remove the stale GEO member.
The query therefore has two stages:
- Ask Redis for the nearest GEO members within the requested radius and count.
- Keep members with an existing seen key and remove members whose seen key has disappeared.
You can pipeline the presence checks rather than sending one Redis request per rider. This matters as the number of nearby candidates grows.
The cleanup operation uses ZREM against riders:online. Without cleanup, the same stale member could appear in future geographic searches.
The requested count applies to the GEO search. Filtering stale members afterwards can leave fewer results than the requested count.
For example, a search requesting two members might return two GEO members, but if one has expired, the final result contains only one rider.
The tests for Rider presence service check these behaviours. They check that the closest rider appears first, that a rider whose seen key disappears is excluded and cleaned up, and that a five-kilometre search excludes a rider approximately 55 kilometres away.
Exclusive claims with SET NX PX
Finding nearby riders does not decide who owns an order.
Imagine two worker processes handling the same READY event. Both discover the same nearest rider and both try to offer the order. Without coordination, they could proceed as though they independently acquired the same assignment.
You need an exclusive claim: a temporary Redis record that gives one rider ownership of an order offer.
Use a key specific to the order:
order:501:claimThe key stores the rider ID as a decimal string. Its expiry is 30 seconds.
Redis provides this behaviour through SET with NX and PX:
SET order:501:claim 101 NX PX 30000The options determine how Redis handles the operation:
NXcreates the key only when it does not already exist.PX 30000sets the expiry to 30,000 milliseconds.101identifies the rider holding the claim.
If the key does not exist, Redis creates it and returns OK.
If another worker already owns the claim, Redis leaves the existing value unchanged and returns a nil result.
The important property is atomicity. Redis checks the key and creates it as one operation. Two workers cannot both successfully create the same live claim.
Claim acquisition in Go
The Go Redis client provides SetNX for this operation:
key := "order:501:claim"
won, err := rdb.SetNX(
ctx,
key,
"101",
30*time.Second,
).Result()won tells you whether this call acquired the claim.
A successful call returns true. An existing claim returns false without an error.
The 30-second expiry prevents an abandoned offer from blocking an order indefinitely. Even if the worker crashes, Redis eventually removes the claim.
The claim is a lease, not permanent ownership.
Reading claim ownership
The claim value identifies the rider who currently holds the offer.
For example:
order:501:claim = 101ClaimedBy reads this value and converts it to an int64.
When the key does not exist, there is no claim holder. The method returns 0 without an error.
This is important for the acceptance endpoint. The authenticated rider's ID must match the current claim holder before the API attempts to assign the order.
Offer delivery and expiration
After the worker acquires a claim, it publishes an offer through Redis Pub/Sub to the rider's user channel:
user:101The fan-out from the previous module delivers the event to the correct connection on the rider's api instance.
The offer is JSON containing:
kindset toofferorder_idexpires_at, expressed as Unix milliseconds
The offer gives the rider 30 seconds to accept. If the claim expires without acceptance, the worker can offer the order to the next nearest rider.
The worker uses the nearest-rider results in order and requests at most five candidates within five kilometres. It must not publish an offer before acquiring the claim.
Releasing a claim safely
Redis removes a claim automatically when its TTL expires. Sometimes, however, the current claim holder needs to release it before expiration.
An unconditional delete is unsafe.
Consider this sequence:
- Worker A acquires a claim for an order.
- Worker A takes longer than expected, and its claim expires.
- Worker B acquires a new claim for the same order.
- Worker A finishes and deletes the claim key.
- Worker A has now deleted Worker B's claim.
Worker A must not release a claim that it no longer owns.
The release operation must compare the stored rider ID with the supplied rider ID before deleting the key.
Atomic compare-and-delete
Redis Lua scripts execute atomically on the Redis server. This lets you check ownership and delete the claim without another worker changing the key between those operations.
A compare-and-delete script looks like this:
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0KEYS[1] is the claim key. ARGV[1] is the decimal rider ID supplied by the caller.
The result is 1 when the key was deleted. It is 0 when the key is missing or belongs to another rider.
This is a Redis Lua script implementing compare-and-delete.
The ownership comparison matters even when a claim has a TTL. A worker can continue running after its lease expires. Its eventual cleanup must not interfere with the next claim holder.
Acceptance and the order state
The rider accepts an offer through:
POST /v1/orders/{id}/acceptThe endpoint is restricted to the rider role.
Before touching the order, the API compares ClaimedBy with the authenticated caller's rider ID. A rider who does not hold the claim cannot accept the order.
The API also checks that the order does not already have an assigned rider. It stores the accepted rider's ID when the assignment succeeds.
Use a conditional database update so concurrent acceptance requests cannot both assign the same order. The successful claim holder receives HTTP 200; a competing or invalid accept receives HTTP 409.
The existing order state machine must also restrict PICK_UP to the rider assigned to that order.
Redis and MySQL do not share one transaction. A successful Redis ownership check does not guarantee that the order assignment will succeed. The conditional database update remains necessary to protect the order's authoritative state.
Location-to-assignment flow
The two exercises following this lesson apply these ideas in separate responsibilities.
The rider presence service stores coordinates under riders:online, refreshes each rider's seen key, removes offline riders and returns nearby active riders.
The rider assignment worker uses those candidates when an order becomes READY. It tries the nearest rider first, acquires a 30-second claim, and publishes the offer through the user's channel. The acceptance endpoint verifies ownership and stores the assigned rider.
Keep the Redis structures separate:
| Key | Responsibility |
|---|---|
riders:online | Stores rider coordinates |
rider:seen:{id} | Tracks recent rider activity |
order:{id}:claim | Stores the current claim holder for an order |
Each key answers a different question. Combining these responsibilities would make expiration and ownership harder to reason about.
Check your understanding
A rider reports latitude 28.461 and longitude 77.031. Which command stores the coordinates for rider 101 correctly?
References
Everything above is explained on this page; these are where it comes from.