GET /v1/restaurants: sort by distance
You add sort=distance to GET /v1/restaurants, returning active restaurants inside the requested circle, nearest first, with each restaurant's distance in metres.
Ticket
You extend GET /v1/restaurants with sort=distance. It returns active restaurants inside the requested circular radius, ordered by great-circle distance with ascending restaurant ID breaking ties. Each item includes distance_m, the distance from the requested coordinates in metres.
For example, this request searches around Chennai and asks for the four nearest restaurants:
GET /v1/restaurants?lat=13.0827&lng=80.2707&radius_km=5&limit=4&sort=distanceThe response keeps the existing items and next_cursor fields. Each item also contains distance_m. This mode builds on W2B4's geographic filtering and pagination. Keep it compatible with W2O1's signed cursors and W2O2's q search.
Endpoint
Active restaurants near a point, one page at a time
latnumberrequired-90 to 90
lngnumberrequired-180 to 180
radius_kmnumberabove 0, at most 50, default 5
limitintegerdefault 20. Integers below 1 count as 1 and above 50 as 50.
cursorstringnext_cursor from the previous page of the same query.
atstring (date-time)RFC 3339 time that is_open is evaluated at. Defaults to now.
sort"distance"distance orders by distance from the point, then by id.
itemsRestaurantSummary[]requiredidintegerrequirednamestringrequiredlatnumberrequiredlngnumberrequiredis_openbooleanrequiredWhether one of the restaurant's open_slots contains the request's at time, in Asia/Kolkata local minutes. A slot covers open_min up to but not including close_min; when close_min is not after open_min the slot runs past midnight. Before the hours are first loaded this is false.
distance_mintegerOptional W2O3, only with sort=distance. Great-circle distance in metres.
next_cursorstringrequiredEmpty on the last page.
invalid_parameterinvalid_cursor
Acceptance criteria
- With
sort=distance, the restaurant list returns active restaurants inside the requested radius, ordered by nearest distance first and ascending restaurant ID for equal distances. - Every returned item includes a positive integer
distance_mthat agrees with the haversine distance using an earth radius of 6371 km, within 2 metres. - The radius is a circle, not its bounding box. A restaurant inside the bounding box but outside the requested radius must not appear.
- Following
next_cursorvisits every matching restaurant exactly once, including restaurants with equal rounded distances. This works withlimitvalues of 1, 2, 3 and 4. - A malformed cursor, invalid base64 cursor or cursor the API did not issue returns
400 Bad Requestwith error codeinvalid_cursor. An unsupported sort value such asnamereturns400 Bad Requestwith error codeinvalid_parameterand fieldsort. - The distance query runs against
restaurants, and MySQLEXPLAINfinds a usable index for it.
Constraints
- Use an earth radius of 6371 km for distance calculations.
- The bounding box must contain every point within the requested radius. Use it as a prefilter, not as the final inclusion check.
- Reserve migration version
0004for the geographic index.
Design direction
Keep geographic calculations, database access and HTTP handling separate. Add the geographic index through migration 0004, and keep the distance query in the database query layer. Put distance calculations and distance-mode pagination with the nearby-restaurant behaviour.
Use the Bounding box to narrow the candidate set before calculating exact distances. A Composite index can help MySQL filter by active status and geographic ranges. Check the actual query plan with EXPLAIN; the existence of an index does not prove MySQL uses it.
Consider these trade-offs:
- Distance calculation: You can calculate the Haversine distance in SQL or Go. Keep the earth radius consistent at 6371 km, and make sure the returned
distance_magrees with the value used for ordering. - Pagination order: Round distances to integer metres consistently. Use both distance and restaurant ID to distinguish equal-distance results. A cursor based only on distance can skip or repeat restaurants when several share the same value.
- Cursor handling: Keep
next_cursoran Opaque cursor for clients. The server owns its format and must reject malformed values. Preserve the existing Keyset pagination behaviour in the other restaurant-list modes.
Any internal layout that meets the contract passes.
How to check your work
Run these commands from the repository root:
cd backend && make up
cd backend && make test W=2O3Read the first failing assertion to identify whether the problem is distance ordering, distance accuracy, circular filtering, pagination, cursor validation or index use.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Restaurant list extensions
6 items
- 2.21HMAC signing for cursorsnot completed
- 2.22GET /v1/restaurants: signed cursorsnot completed
- 2.23MySQL FULLTEXT searchnot completed
- 2.24GET /v1/restaurants: search by namenot completed
- 2.25Haversine distance and geo indexesnot completed
- 2.26GET /v1/restaurants: sort by distancenot completed
Week 2 done · Up next · 8 modules
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Return active restaurants nearest first, with ascending ID breaking equal-distance ties.
- Include
distance_mwithin 2 metres of the haversine distance using an earth radius of 6371 km. - Exclude restaurants outside the circular radius, even when they fall inside the bounding box.
- Page through equal-distance restaurants exactly once with limits 1, 2, 3 and 4.
- Reject invalid cursors with
400 invalid_cursorand unknown sort values with400 invalid_parameter, fieldsort. - Add the geographic index in migration
0004and confirmEXPLAINfinds a usable index onrestaurants.
Commands
cd backend && make upcd backend && make test W=2O3Tests
Results are ordered from nearest to farthest, with ascending restaurant ID breaking equal-distance ties.
GET/v1/restaurants?lat=13.0827&lng=80.2707&radius_km=5&limit=50&sort=distanceParamslat 13.0827 lng 80.2707 radius_km 5 limit 50 sort distance Response 200 OK{ "items": [ { "id": …, "distance_m": 501, … }, { "id": …, "distance_m": 1000, … }, … ], "next_cursor": "…" }Input Create active restaurants around
(13.0827, 80.2707)at the following approximate offsets: 0.5 km north, 1 km east, 1.5 km southwest, two restaurants 2.5 km east, and 3 km north. Requestsort=distancewith a 5 km radius.Expected All six active restaurants appear in nearest-first order. The two restaurants at equal distances appear in ascending ID order.
TestW2O3_ResultsAreNearestFirstWithIDBreakingTiesinbackend/e2e/w2_o3_test.go