Video in progress
Which Redis feature do you use to quickly find free couriers nearby (say, within 3 km)?
Redis GEO commands: you write the courier's coordinates with GEOADD and fetch the nearest ones with GEOSEARCH ... BYRADIUS 3 km ASC COUNT 10. Internally it's a plain Sorted Set whose score is a geohash. Cleaning out inactive couriers is something you have to handle yourself.
📖 Answer
GEOADD couriers:free 69.2401 41.2995 courier:17 # longitude first, then latitude
GEOSEARCH couriers:free FROMLONLAT 69.2450 41.3110 BYRADIUS 3 km ASC COUNT 10 WITHDIST
ZREM couriers:free courier:17 # the courier took an order
The coordinate order is the most common mistake: Redis expects longitude latitude, while maps often give lat, lng. If you write them the other way around, there's no error, the courier just shows up on a different continent.
In Spring Data Redis:
var res = redis.opsForGeo().search("couriers:free",
GeoReference.fromCoordinate(69.2450, 41.3110),
new Distance(3, Metrics.KILOMETERS),
RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
.includeDistance().sortAscending().limit(10));
GEORADIUS has been marked deprecated since Redis 6.2, so use GEOSEARCH in new code.
What comes up in prod:
- a member has no TTL of its own. A courier whose app has been closed looks "free" forever. Usually you store the last signal time in a separate Sorted Set (
couriers:seen, score is a timestamp), and a background job doesZREMon old couriers from both sets; - Redis calculates distance with a spherical model, with an error of about 0.5%, which is enough for picking a courier;
- use a separate key per city or region, because one global key becomes big and hot.
Sign up to mark studied questions and save your progress.