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:

http
GET /v1/restaurants?lat=13.0827&lng=80.2707&radius_km=5&limit=4&sort=distance

The 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

GET/v1/restaurants

Active restaurants near a point, one page at a time

Query parameters
  • latnumberrequired

    -90 to 90

  • lngnumberrequired

    -180 to 180

  • radius_kmnumber

    above 0, at most 50, default 5

  • limitinteger

    default 20. Integers below 1 count as 1 and above 50 as 50.

  • cursorstring

    next_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.

Response 200 OK
  • itemsRestaurantSummary[]required
    • idintegerrequired
    • namestringrequired
    • latnumberrequired
    • lngnumberrequired
    • is_openbooleanrequired

      Whether 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_minteger

      Optional W2O3, only with sort=distance. Great-circle distance in metres.

  • next_cursorstringrequired

    Empty on the last page.

Response 400 Bad Request

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_m that 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_cursor visits every matching restaurant exactly once, including restaurants with equal rounded distances. This works with limit values of 1, 2, 3 and 4.
  • A malformed cursor, invalid base64 cursor or cursor the API did not issue returns 400 Bad Request with error code invalid_cursor. An unsupported sort value such as name returns 400 Bad Request with error code invalid_parameter and field sort.
  • The distance query runs against restaurants, and MySQL EXPLAIN finds 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 0004 for 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_m agrees 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_cursor an 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:

bash
cd backend && make up
cd backend && make test W=2O3

Read the first failing assertion to identify whether the problem is distance ordering, distance accuracy, circular filtering, pagination, cursor validation or index use.

Finished Exercise 2.26?

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 3 · Authentication, orders and Kafka events

Week 2 done · Up next · 8 modules

Open week 3

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Return active restaurants nearest first, with ascending ID breaking equal-distance ties.
  2. Include distance_m within 2 metres of the haversine distance using an earth radius of 6371 km.
  3. Exclude restaurants outside the circular radius, even when they fall inside the bounding box.
  4. Page through equal-distance restaurants exactly once with limits 1, 2, 3 and 4.
  5. Reject invalid cursors with 400 invalid_cursor and unknown sort values with 400 invalid_parameter, field sort.
  6. Add the geographic index in migration 0004 and confirm EXPLAIN finds a usable index on restaurants.

Commands

terminal
cd backend && make up
terminal
cd backend && make test W=2O3

Tests

  1. 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=distance
    Params
    lat13.0827
    lng80.2707
    radius_km5
    limit50
    sortdistance
    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. Request sort=distance with 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_ResultsAreNearestFirstWithIDBreakingTies in backend/e2e/w2_o3_test.go