Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Nearby Spatial Search and Tenant Filter

Last updated: 4 Oct 20268 min read
tutorial
IntermediateBy AITrove Editorial

A nearby search combines a point, radius, and visibility rule. The radius has units; the stored geometry has a reference system; the results belong to a tenant and a permission scope. An index can narrow candidate facilities before an exact distance check. Calculating distance for every row and sorting the entire table is wasteful at scale. The server must cap radius, result count, and query time. A map viewport can suggest the search center but cannot decide which private facilities the caller may see.

Working case

A district reviewer searches for pumps within 2,900 meters of an inspection site. The table contains 830,000 facility points across several tenants. A naive query computes distance for every row, then filters tenant after the fact, consuming CPU and risking leakage through counts. The revised endpoint authenticates the reviewer, applies tenant and record visibility inside the candidate query, uses a spatial index-aware radius predicate, orders only the bounded candidate set, and returns a stable cursor. The response carries an approximate distance and a documented unit. A client request for a 900-kilometer radius is rejected before database work.

Implementation boundary

javascript
function validNearbyRequest(query) {
  return Number.isFinite(query.latitude) && Number.isFinite(query.longitude) &&
    query.latitude >= -90 && query.latitude <= 90 &&
    query.longitude >= -180 && query.longitude <= 180 &&
    Number.isFinite(query.radiusMeters) && query.radiusMeters > 0 && query.radiusMeters <= 2900;
}
console.log(validNearbyRequest({ latitude: 13.036, longitude: 77.610, radiusMeters: 900000 }));
// Output: false

Validate finite center coordinates and radius before constructing SQL. Define the geographic type and meter semantics at the database boundary; do not compare an angular degree difference with a meter radius. Put tenant and authorization predicates in the query that selects candidates, not only in application code after rows have been fetched. Use an index-aware radius predicate and inspect the actual query plan for representative data. Cap radius and returned rows; if a user needs a region-wide view, use a different aggregated endpoint. Stable ordering needs a secondary key after distance so pagination does not duplicate equal-distance facilities. A changing facility set can still shift pages, so document snapshot or cursor behavior. Return only fields needed for map and list, keeping private coordinates out of unrelated telemetry.

Cost and boundaries

Without an index, a radius filter is O(N) distance evaluations for N facilities. With a useful spatial and tenant strategy, the database narrows candidates, then pays O(K) or O(K log K) work for K matches depending on ordering and limit. Performance depends on density, radius, index selectivity, and permission joins; a theoretical index does not guarantee a fast plan. Exact distance sorting over a huge radius may still be costly. Measure candidates visited, rows returned, p95 latency, CPU, tenant predicate selectivity, and denied oversized radii. Cache only with tenant, permission, center precision, radius, and data revision considered.

Failure trace

Send a radius expressed in kilometers where the endpoint expects meters and require schema rejection or explicit conversion. Request an infinite or negative radius. Search near a tenant boundary and verify no other tenant’s point, count, or timing-derived list detail is disclosed. Add many dense facilities at the same distance and page through results without duplicates. Remove the spatial index in a staging database and compare plans and latency. Revoke a reviewer while their next-page cursor is waiting and deny the continuation. Ask for a huge radius and confirm it is blocked before an expensive scan.

Verification

  • Radius units and input bounds are enforced.
  • Tenant scope enters the candidate query.
  • Pagination remains stable for tied distances.

Practice drill

Store 83,000 synthetic facilities across three tenants. Query a 2,900-meter circle centered on case 47 and cap results at 63. Compare a full distance scan to an index-aware candidate predicate using the database plan and measured latency. Add two facilities tied on distance and verify stable cursor order. Switch tenant between pages and reject the old cursor. Report exact returned count, candidate count, query time, and whether any private location entered routine logs.

Decision note

The nearby endpoint owns units, work limits, and permission; the map supplies only a requested view.

Common Mistakes

  • Calculating distance over every table row.
  • Filtering tenant after fetching candidates.
  • Caching private results by center alone.

Related lessons

Geospatial Web Interfaces and Spatial Queries; Coordinate Validation, Projection, and the Antimeridian; Map Viewport Tiles and Request Lifecycle; Location Consent, Precision, and Map Alternatives; Data Persistence; Authorization and Tenant Boundaries.

Connected practice

Build Project: authorized facility map and nearby search and review Web Development: geospatial decisions quiz.

web-tech
web-development
Storage details