Audit a Flawed Proximity-Search Module in Python
Data Structure DesignModel answerLast updated
Review a small Python module for finding and labeling nearby places, spotting correctness, speed and design problems, then propose and justify concrete refactors.
Review a proximity-search module
A teammate opened a pull request for a small Python module that returns places close to a given coordinate and looks up the city name for a coordinate. You are the reviewer. Here is the code:
import math
def find_nearby(listings, lat, lon, radius_km=5, results=[]):
for l in listings:
d = math.sqrt((l['lat'] - lat)**2 + (l['lon'] - lon)**2) * 111
if d < radius_km:
results.append(l)
results.sort(key=lambda x: math.sqrt((x['lat']-lat)**2 + (x['lon']-lon)**2))
return results
def get_city(lat, lon):
resp = requests.get(f"https://geo.example/reverse?lat={lat}&lon={lon}")
return resp.json()['city']
listings is a list of dicts with lat and lon in degrees. The service handles many queries per second against a large, mostly static set of listings.
What to deliver
- Review the code. Identify problems under four headings: correctness, performance, scalability, and readability/design. Mark each finding as a blocker, should-fix, or nit.
- Propose concrete fixes. Show rewritten code for the most important issues, not just names of techniques. Consider data structures, vectorization, caching, and module structure.
- Explain scaling. Describe how your approach changes at roughly 10 thousand, 10 million, and 1 billion points.
- Say how you would test it. Name the edge cases you would cover.
Talk through your review in a deliberate order, and justify the priority you give each item.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Review order
I would walk through the code as correctness, then performance and scalability, then design and readability, then testing, labeling each item as blocker, should-fix, or nit. Correctness comes first because geo bugs usually produce plausible-looking but wrong output, which is worse than a crash.
Correctness
Blockers
- Mutable default argument.
results=[]is created once and shared by every call, so results from earlier queries leak into later ones. UseNoneand create a fresh list inside the function (or just build and return a new list). - Euclidean distance on raw degrees. A degree of latitude is about 111 km, but a degree of longitude is about
111 * cos(lat)km. At 60°N the code overstates east-west distances by about 2x, so nearby places are wrongly excluded. Use haversine, or the chord-distance trick below. - Antimeridian wraparound. Points at lon 179.9 and -179.9 are about 20 km apart at the equator, but the naive difference gives roughly 360 degrees. Bounding-box prefilters fail the same way. Poles have a similar degeneracy.
Should-fix
- No input validation. Check lat in [-90, 90], lon in [-180, 180], and reject NaN or
None. A NaN makes every comparison false, so rows silently disappear. - Boundary semantics.
d < radius_kmexcludes points exactly at the radius. Decide and document whether the boundary is inclusive (usually<=), and use the same rule everywhere. - Lat/lon ordering. GeoJSON and PostGIS use
(lon, lat), while this code uses(lat, lon). Swapped arguments at module boundaries are a classic bug, so name parameters explicitly. get_cityfailure handling. No timeout, noraise_for_status, and['city']raisesKeyErrorfor ocean or unmapped points. Coordinates are also interpolated into a URL without usingparams=.- Missing import.
requestsis never imported. - Numerical clamp. In haversine,
acan exceed 1 by rounding error; clamp withmin(1.0, a)beforesqrt/asin.
Performance and scalability
- O(N) scan per query. With Q queries the cost is O(N*Q). Build a spatial index once, then each query is about O(log N + k). Options: a KD-tree on 3D unit vectors, a BallTree with the haversine metric, geohash/S2/H3 cells, or PostGIS / Elasticsearch
geo_distancein production. - Distance computed twice. The sort recomputes every distance. Compute once, store it, and sort on the stored value. If only the top k are needed, use
heapq.nsmallestor a k-nearest query. - Python loops over dicts. Store coordinates as columnar NumPy arrays and vectorize; a 50-100x speedup is typical.
- Network call per point. Fixes:
- set a timeout and retry with backoff;
- cache on rounded coordinates (
round(x, 3)is about 110 m), withfunctools.lru_cachelocally or Redis if shared; - batch requests where the API allows;
- at volume, do offline reverse geocoding with point-in-polygon against city boundaries, accelerated by an R-tree.
- Memory. 100M rows as a list of dicts costs many gigabytes. Use typed arrays (float64 is 8 bytes per coordinate; float32 halves it at the cost of roughly meter-level precision) and stream or chunk input.
Scaling tiers
| Size | Approach |
|---|---|
| ~10K | Vectorized NumPy brute force is fine; no index needed. |
| ~10M | In-memory KD-tree or BallTree, built once, rebuilt on batch updates. |
| ~1B | Partition by S2/H3 cell across shards; a query fans out only to cells intersecting the search disc, then does exact distance filtering locally. Use a database or search engine with geo indexes. |
Design and readability
- Use a frozen
dataclassfor points at the edges and arrays internally. - Replace the magic
111withEARTH_RADIUS_KM = 6371.0088. - Separate pure math, indexing, and I/O. Inject the geocoder so tests can mock it.
- Add type hints and docstrings that state units (km vs m, degrees vs radians).
- Rename
l, which is easy to confuse with1.
Refactor
Map every point to a 3D unit vector. Chord length and great-circle distance are related exactly by chord = 2 * sin(d / (2R)), so a Euclidean radius query on unit vectors returns exactly the points within great-circle distance d. There are no longitude distortions and no antimeridian or pole special cases.
from __future__ import annotations
from dataclasses import dataclass
from typing import Sequence
import numpy as np
from scipy.spatial import cKDTree
EARTH_RADIUS_KM = 6371.0088
def _to_unit_vectors(lat_deg, lon_deg):
lat, lon = np.radians(lat_deg), np.radians(lon_deg)
c = np.cos(lat)
return np.column_stack((c * np.cos(lon), c * np.sin(lon), np.sin(lat)))
def haversine_km(lat1, lon1, lat2, lon2):
lat1, lon1, lat2, lon2 = map(np.radians, (lat1, lon1, lat2, lon2))
a = (np.sin((lat2 - lat1) / 2) ** 2
+ np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1) / 2) ** 2)
return 2 * EARTH_RADIUS_KM * np.arcsin(np.sqrt(np.clip(a, 0.0, 1.0)))
def _validate(lat, lon):
if np.isnan(lat).any() or np.isnan(lon).any():
raise ValueError("NaN coordinates")
if (np.abs(lat) > 90).any() or (np.abs(lon) > 180).any():
raise ValueError("coordinates out of range")
@dataclass(frozen=True)
class Neighbor:
id: str
distance_km: float
class GeoIndex:
"""Build once in O(N log N); radius queries in O(log N + k)."""
def __init__(self, ids: Sequence[str], lat: Sequence[float], lon: Sequence[float]):
self._ids = np.asarray(ids)
self._lat = np.asarray(lat, dtype=np.float64)
self._lon = np.asarray(lon, dtype=np.float64)
_validate(self._lat, self._lon)
self._tree = cKDTree(_to_unit_vectors(self._lat, self._lon))
def within(self, lat: float, lon: float, radius_km: float) -> list[Neighbor]:
if radius_km < 0:
raise ValueError("radius_km must be non-negative")
_validate(np.array([lat]), np.array([lon]))
angle = min(radius_km / EARTH_RADIUS_KM, np.pi)
chord = 2 * np.sin(angle / 2)
q = _to_unit_vectors(np.array([lat]), np.array([lon]))[0]
idx = np.asarray(self._tree.query_ball_point(q, r=chord + 1e-12), dtype=int)
if idx.size == 0:
return []
d = haversine_km(lat, lon, self._lat[idx], self._lon[idx]) # computed once
keep = d <= radius_km
idx, d = idx[keep], d[keep]
order = np.argsort(d, kind="stable")
return [Neighbor(str(self._ids[i]), float(x)) for i, x in zip(idx[order], d[order])]
The tiny epsilon on the chord keeps boundary points from being lost to floating-point error. The exact haversine pass then applies the true inclusive cutoff, and distances are computed once and reused for sorting.
For the geocoder, wrap it in a small class with a session, timeout, retry, raise_for_status, a cache keyed on rounded coordinates, and a clear return of None for unmapped points rather than a KeyError.
Testing
- Known distances: London to Paris is about 344 km; equator and pole cases.
- Antimeridian pair (179.9, -179.9) and a query at a pole.
- Radius 0, radius larger than half the Earth, and a point exactly on the boundary.
- Empty index, duplicate points, NaN and out-of-range input.
- Repeated calls to confirm no state leaks between queries (the mutable default regression).
- Property test: the index result equals a brute-force haversine scan on random points.
- Mocked geocoder for timeout, 500, and missing-key responses.
Common mistakes in this kind of review
- Listing style nits before the correctness bugs.
- Recommending "use a spatial index" without saying which and why.
- Forgetting that degrees must be converted to radians before trig functions.
- Using a lat/lon bounding box for the prefilter and breaking at the antimeridian.