System Design Part 3 Storage basics

Geohash and Geospatial Indexes: Cell Boundaries in Nearby Search, Redis GEO, and How Distance Leaks Location

Bill.Lin 23 min read

System Design series Part 3-8 | Previous: Full-Text Search and Inverted Indexes | Next: Replication and Replication Lag | Series map

Read first: Part 3-2 Indexes and B+Trees, Part 3-7 Full-Text Search and Inverted Indexes.

Scenario and problem

The talk platform has started running in-person talks, with 100,000 partner venues across Taiwan (classrooms, coworking spaces, bookstores). The app needs a new “nearby in-person talks” feature:

  1. With the user’s current location as the center, list the venues within 3 km, nearest first
  2. 2,000 queries per second at peak
  3. The next phase is “nearby peers”, which lets learners who choose to make their location public find each other
Find in-person talks within 3 km1 / 4
Find in-person talks within 3 kmUserNearby talks100k venuesUserNearby talksYour locationWithin 3 km, nearest firstUserNearby talks100k venues2,000 QPS100k distances200M per second at peakNearby talks100k venueslat/lng indexOnly 43 of 1,500+ in rangeUserNearby talksNearby peersLearners sharing location
  1. Nearby in-person talksThere are 100,000 partner venues across Taiwan. With the user's current location as the center, list the venues within 3 km, nearest first.
  2. One distance per venueThe simplest approach computes the distance to every venue and keeps the ones within 3 km. Each query computes 100,000 distances; at a peak of 2,000 queries per second, that is 200 million per second.
  3. An index barely helpsA B+Tree is one-dimensional. On a (latitude, longitude) index, once latitude uses a range condition, longitude can no longer narrow the range, so the index only finds a whole latitude band: of the 1,500-plus rows, only 43 are inside the circle.
  4. Next: nearby peersThe next phase also lets learners who choose to make their location public find each other. The real problem: turn a two-dimensional location into a form a one-dimensional index can handle.

The simplest approach and its limits

Store latitude and longitude as two DOUBLE columns, and on every query compute the distance to each venue and keep the ones within 3 km. Each query computes 100,000 distances; at peak that is 200 million per second.

An index does not help much either. A B+Tree is one-dimensional: on a composite index on (latitude, longitude), once latitude uses a range condition, longitude can no longer narrow the scan (the leftmost-prefix rule from the Indexes and B+Trees post). The index can only narrow the search to a “latitude band” that runs east to west. In the measurements below, the band holds more than 1,500 rows, and only 43 of them are actually inside the circle.

The heart of the problem: turn a two-dimensional location into a form that a one-dimensional index can handle.

Core mechanism

Geohash: turning coordinates into a string

  1. Split the longitude range [-180, 180] in half; write 1 if the coordinate falls in the right half and 0 if it falls in the left, then keep splitting the half it fell into
  2. Split the latitude range [-90, 90] the same way
  3. Interleave the longitude and latitude bits (bits 1, 3, 5… are longitude, bits 2, 4, 6… are latitude)
  4. Turn every 5 bits into one base32 character

Each extra character splits the cell into 32 smaller ones. The most important property: points with the same prefix fall in the same cell. The geohash of Taipei 101 is wsqqqm29d: it is inside the cell wsqqq, and also inside the larger cell wsqq. So “find the venues in cell wsqqq” is just geohash LIKE 'wsqqq%', which an ordinary B+Tree index can handle.

wsqqq and the 8 cells around it:

West Center East
North wsqqt wsqqw wsqqx
Center wsqqm wsqqq wsqqr
South wsqqj wsqqn wsqqp

Place 100,000 venues at random within a latitude and longitude range around Taiwan, store them sorted by geohash (equivalent to a B+Tree index on a geohash column in a database), and compare several ways to query:

Geohash implementation (Geohash.java)
java
package geo;

import java.util.ArrayList;
import java.util.List;

/** Geohash: interleave the bisection bits of longitude and latitude into one bit string, and write every 5 bits as one base32 character. */
public final class Geohash {

    private static final String BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
    private static final double EARTH_RADIUS_KM = 6371.0088;

    private Geohash() {
    }

    public static String encode(double latitude, double longitude, int length) {
        double[] lat = {-90, 90};
        double[] lng = {-180, 180};
        StringBuilder hash = new StringBuilder(length);
        boolean evenBit = true;                                     // even bits hold longitude, odd bits latitude
        int bits = 0;
        int ch = 0;
        while (hash.length() < length) {
            double[] range = evenBit ? lng : lat;
            double value = evenBit ? longitude : latitude;
            double mid = (range[0] + range[1]) / 2;
            ch <<= 1;
            if (value >= mid) {
                ch |= 1;
                range[0] = mid;
            } else {
                range[1] = mid;
            }
            evenBit = !evenBit;
            if (++bits == 5) {
                hash.append(BASE32.charAt(ch));
                bits = 0;
                ch = 0;
            }
        }
        return hash.toString();
    }

    /** Returns {minLat, maxLat, minLng, maxLng}. */
    public static double[] bounds(String hash) {
        double[] lat = {-90, 90};
        double[] lng = {-180, 180};
        boolean evenBit = true;
        for (char c : hash.toCharArray()) {
            int value = BASE32.indexOf(c);
            for (int bit = 4; bit >= 0; bit--) {
                double[] range = evenBit ? lng : lat;
                double mid = (range[0] + range[1]) / 2;
                if ((value >> bit & 1) == 1) {
                    range[0] = mid;
                } else {
                    range[1] = mid;
                }
                evenBit = !evenBit;
            }
        }
        return new double[] {lat[0], lat[1], lng[0], lng[1]};
    }

    /** The cell itself plus the 8 around it. As long as the cell's width and height are both at least the search radius, these 9 cells always cover the whole circle. */
    public static List<String> cellAndNeighbors(String hash) {
        double[] b = bounds(hash);
        double height = b[1] - b[0];
        double width = b[3] - b[2];
        double centerLat = (b[0] + b[1]) / 2;
        double centerLng = (b[2] + b[3]) / 2;
        List<String> cells = new ArrayList<>(9);
        for (int dy = -1; dy <= 1; dy++) {
            for (int dx = -1; dx <= 1; dx++) {
                cells.add(encode(centerLat + dy * height, centerLng + dx * width, hash.length()));
            }
        }
        return cells;
    }

    /** Picks the longest precision whose cells are no smaller than the radius. */
    public static int precisionFor(double radiusKm, double latitude) {
        for (int length = 9; length >= 1; length--) {
            double[] b = bounds(encode(latitude, 0, length));
            double heightKm = distanceKm(b[0], 0, b[1], 0);
            double widthKm = distanceKm(latitude, b[2], latitude, b[3]);
            if (Math.min(heightKm, widthKm) >= radiusKm) {
                return length;
            }
        }
        throw new IllegalArgumentException("Radius too large");
    }

    /** Haversine: great-circle distance, treating the Earth as a sphere. */
    public static double distanceKm(double lat1, double lng1, double lat2, double lng2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.pow(Math.sin(dLat / 2), 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.pow(Math.sin(dLng / 2), 2);
        return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(a));
    }
}
Test program (GeohashDemo.java)
java
package geo;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class GeohashDemo {

    record Venue(long id, double lat, double lng) {}

    public static void main(String[] args) {
        System.out.println("Cell size (width × height):");
        for (int length = 4; length <= 8; length++) {
            System.out.printf("  length %d: equator %s | 25°N %s%n", length, cellSize(0, length), cellSize(25, length));
        }

        double lat = 25.0340;
        double lng = 121.5645;                                      // Taipei 101
        System.out.printf("%nTaipei 101: %s%n", Geohash.encode(lat, lng, 9));

        // Within Taiwan, find two points about 100 m apart whose common prefix is the shortest
        String bestA = null;
        String bestB = null;
        int shortest = 99;
        for (double x = 120.0; x < 122.0; x += 0.0005) {
            String a = Geohash.encode(23.5, x, 9);
            String b = Geohash.encode(23.5, x + 0.00098, 9);
            int common = commonPrefix(a, b);
            if (common < shortest) {
                shortest = common;
                bestA = a;
                bestB = b;
            }
        }
        System.out.printf("Two points about 100 m apart: %s and %s, common prefix only %d characters%n", bestA, bestB, shortest);

        // 100,000 venues stored in geohash order, simulating a B+Tree index on a geohash column in the database
        Random random = new Random(42);
        TreeMap<String, Venue> index = new TreeMap<>();
        for (long id = 1; id <= 100_000; id++) {
            Venue v = new Venue(id, 21.9 + random.nextDouble() * 3.4, 120.0 + random.nextDouble() * 2.0);
            index.put(Geohash.encode(v.lat(), v.lng(), 9) + ":" + id, v);
        }

        double radiusKm = 3;
        int precision = Geohash.precisionFor(radiusKm, lat);
        System.out.printf("%nSearch radius %.0f km, using cells of length %d%n", radiusKm, precision);
        search("Taipei 101", index, lat, lng, radiusKm, precision);
        double[] b = Geohash.bounds(Geohash.encode(lat, lng, precision));
        search("Corner of the same cell", index, b[1] - 0.0005, b[3] - 0.0005, radiusKm, precision);
    }

    static void search(String label, TreeMap<String, Venue> index, double lat, double lng, double radiusKm, int precision) {
        Set<Long> truth = index.values().stream()
                .filter(v -> Geohash.distanceKm(lat, lng, v.lat(), v.lng()) <= radiusKm)
                .map(Venue::id).collect(Collectors.toSet());
        double band = radiusKm / 110.574;                           // B+Tree index on latitude only: narrows down to a latitude band at best
        long latitudeBand = index.values().stream().filter(v -> Math.abs(v.lat() - lat) <= band).count();
        String center = Geohash.encode(lat, lng, precision);
        int[] scanned = new int[1];
        Set<Long> centerOnly = scan(index, List.of(center), lat, lng, radiusKm, scanned);
        int centerScanned = scanned[0];
        scanned[0] = 0;
        Set<Long> nine = scan(index, Geohash.cellAndNeighbors(center), lat, lng, radiusKm, scanned);
        System.out.printf("%s: %d venues actually within the radius%n", label, truth.size());
        System.out.printf("  latitude index    scanned %,6d rows%n", latitudeBand);
        System.out.printf("  center cell only  scanned %,6d rows, found %d%n", centerScanned, centerOnly.size());
        System.out.printf("  9 cells           scanned %,6d rows, found %d%s%n", scanned[0], nine.size(),
                nine.equals(truth) ? " (same as a full table scan)" : " (mismatch)");
    }

    static Set<Long> scan(TreeMap<String, Venue> index, List<String> cells, double lat, double lng, double radiusKm, int[] scanned) {
        return cells.stream()
                .flatMap(cell -> index.subMap(cell, true, cell + "{", false).values().stream())  // '{' comes right after 'z': a prefix query
                .peek(v -> scanned[0]++)
                .filter(v -> Geohash.distanceKm(lat, lng, v.lat(), v.lng()) <= radiusKm)
                .map(Venue::id).collect(Collectors.toSet());
    }

    static String cellSize(double latitude, int length) {
        double[] b = Geohash.bounds(Geohash.encode(latitude, 0, length));
        double heightKm = Geohash.distanceKm(b[0], 0, b[1], 0);
        double widthKm = Geohash.distanceKm(latitude, b[2], latitude, b[3]);
        return widthKm >= 1 ? String.format("%7.2f km × %5.2f km", widthKm, heightKm)
                : String.format("%7.0f m  × %5.0f m ", widthKm * 1000, heightKm * 1000);
    }

    static int commonPrefix(String a, String b) {
        int i = 0;
        while (i < a.length() && a.charAt(i) == b.charAt(i)) {
            i++;
        }
        return i;
    }
}
text
Cell size (width × height):
  length 4: equator   39.09 km × 19.55 km | 25°N   35.43 km × 19.55 km
  length 5: equator    4.89 km ×  4.89 km | 25°N    4.43 km ×  4.89 km
  length 6: equator    1.22 km ×  0.61 km | 25°N    1.11 km ×  0.61 km
  length 7: equator     153 m  ×   153 m  | 25°N     138 m  ×   153 m 
  length 8: equator      38 m  ×    19 m  | 25°N      35 m  ×    19 m 

Taipei 101: wsqqqm29d
Two points about 100 m apart: wsjvxyp9k and wsnj8n037, common prefix only 2 characters

Search radius 3 km, using cells of length 5
Taipei 101: 43 venues actually within the radius
  latitude index    scanned  1,561 rows
  center cell only  scanned     28 rows, found 22
  9 cells           scanned    254 rows, found 43 (same as a full table scan)
Corner of the same cell: 33 venues actually within the radius
  latitude index    scanned  1,602 rows
  center cell only  scanned     28 rows, found 9
  9 cells           scanned    254 rows, found 33 (same as a full table scan)

Cell size: length 5 is roughly 5 km square, length 6 about 1 km × 600 m, and length 7 about 150 m square. A cell’s height is the same everywhere, but its width shrinks with latitude: meridians converge at the poles, so the same difference in longitude is only 90% as wide at 25°N as at the equator, and only half as wide at 60°N.

Neighbors do not always share a prefix: two points about 100 m apart have geohashes that differ from the 3rd character on. Geohash numbers its cells along a Z-shaped curve (the Z-order curve), which jumps a long way at the boundaries of large cells. So “a longer shared prefix means closer” holds in one direction only: a shared prefix means close, but close does not mean a shared prefix.

Querying only the center cell misses half: with the user standing at Taipei 101, it finds only 22 of the 43 venues within 3 km; standing at a corner of the cell, it finds only 9 of 33.

Querying 9 cells: as long as the cell’s width and height are both at least the search radius, a circle centered on the user always falls inside “its own cell plus the 8 around it”. The 9 cells scan 254 rows, and computing the exact distance for each one gives exactly the same result as a full table scan; the latitude index has to scan more than 1,500 rows.

Cell size is a trade-off: smaller cells mean fewer rows scanned, but once a cell is smaller than the radius, 9 cells no longer cover the whole circle and you have to query more cells. precisionFor in the implementation picks the longest precision whose cells are no smaller than the radius, and accounts for how latitude affects width.

Other spatial indexes

Geohash is the easiest approach to understand and the easiest to build on an ordinary database, but it is not the only one:

  • Quadtree: when a region holds too many points, split it into four; dense city areas get small cells, while the countryside keeps large ones. More efficient than fixed-size cells when the data is unevenly distributed; often used for in-memory indexes
  • R-Tree: groups nearby objects by their minimum bounding rectangle (MBR) and builds the groups into a tree. Besides points, it can store lines and polygons. MySQL’s SPATIAL index and PostGIS’s GiST index both belong to this family
  • S2 (Google): projects the Earth onto the six faces of a cube and numbers the cells along a Hilbert curve. A Hilbert curve does not make big jumps the way Z-order does, so covering an arbitrary shape takes fewer cells
  • H3 (Uber): hexagonal cells at 16 resolutions. A hexagon’s six neighbors are all the same distance from its center, which suits regional statistics, such as demand heat per area

Redis’s GEO commands are geohash too: longitude and latitude are interleaved into a 52-bit integer, stored as a sorted set score. A query likewise checks the score ranges of the center area plus the 8 areas around it, then filters out members outside the circle, the same idea as the measurements above.

Comparing options

Geohash column + B+Tree MySQL SPATIAL (R-Tree) Redis GEO PostGIS
How it works 9 prefix range queries, then compute distances R-Tree sorted set + 52-bit geohash R-Tree (GiST)
Shapes Points Points, lines, polygons Points Points, lines, polygons; the most complete set of functions
Consistency with business data Same transaction Same transaction Derived data, needs syncing Same transaction
Good for Works on any database Teams already on MySQL High-frequency queries, moving objects Geographic computation: districts, delivery zones, routes

In Java

1. Nearby venues: Redis GEO

Venue data rarely changes but is queried heavily, which makes it a good fit for Redis. The database remains the single source of truth; when a venue is added or moves, an outbox event updates Redis (the same index sync as in the Full-Text Search and Inverted Indexes post):

java
package geo;

import java.util.List;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands.GeoSearchCommandArgs;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;

public class NearbyVenueService {

    private static final String KEY = "geo:venues";
    private static final double MAX_RADIUS_KM = 10;
    private static final int MAX_RESULTS = 50;

    private final GeoOperations<String, String> geo;

    public NearbyVenueService(StringRedisTemplate redis) {
        this.geo = redis.opsForGeo();
    }

    public record NearbyVenue(long venueId, double distanceKm) {}

    /** Called when a venue is added or moves; the database is still the single source of truth, and this is only a derived index. */
    public void upsert(long venueId, double longitude, double latitude) {
        geo.add(KEY, new Point(longitude, latitude), Long.toString(venueId));   // Point is (x = longitude, y = latitude)
    }

    public void remove(long venueId) {
        geo.remove(KEY, Long.toString(venueId));
    }

    public List<NearbyVenue> nearby(double longitude, double latitude, double radiusKm) {
        GeoSearchCommandArgs args = GeoSearchCommandArgs.newGeoSearchArgs()
                .includeDistance()
                .sortAscending()
                .limit(MAX_RESULTS);
        return geo.search(KEY,
                        GeoReference.fromCoordinate(longitude, latitude),
                        new Distance(Math.min(radiusKm, MAX_RADIUS_KM), Metrics.KILOMETERS),
                        args)
                .getContent().stream()
                .map(r -> new NearbyVenue(Long.parseLong(r.getContent().getName()), r.getDistance().getValue()))
                .toList();
    }
}
  • geo.search maps to GEOSEARCH, available since Redis 6.2
  • Both the radius and the number of results are capped, so one request cannot scan a large area
  • Spring’s Point and the Redis arguments both put longitude first

Once you have the nearby venue IDs, query the database for this week’s talks at those venues. Watch out: “find the nearest 50, then keep the ones with talks this week” can leave nothing at all. If a business condition filters out most venues, build the condition into the key, for example by putting only the venues with talks this week into geo:venues:active.

2. No extra Redis to run: a geohash column

When the data volume and query load are not that large, one extra geohash column in the table is enough. The application computes Geohash.encode(lat, lng, 9) on write, and queries use the prefixes of the 9 cells:

sql
ALTER TABLE venue
    ADD COLUMN geohash CHAR(9) NOT NULL,
    ADD INDEX idx_venue_geohash (geohash);

SELECT id, latitude, longitude
  FROM venue
 WHERE geohash LIKE 'wsqqj%' OR geohash LIKE 'wsqqn%' OR geohash LIKE 'wsqqp%'
    OR geohash LIKE 'wsqqm%' OR geohash LIKE 'wsqqq%' OR geohash LIKE 'wsqqr%'
    OR geohash LIKE 'wsqqt%' OR geohash LIKE 'wsqqw%' OR geohash LIKE 'wsqqx%';

A LIKE that does not start with a wildcard can use the index, so the 9 conditions become 9 range scans, the same as subMap in the measurements. Then compute the exact distances of the returned rows with Geohash.distanceKm and sort them.

3. Coordinate order in MySQL SPATIAL

To use MySQL’s R-Tree index, the column must be NOT NULL and declare an SRID; otherwise the optimizer will not use the index:

sql
CREATE TABLE venue (
    id       BIGINT PRIMARY KEY,
    location POINT NOT NULL SRID 4326,
    SPATIAL INDEX idx_venue_location (location)
);

INSERT INTO venue
VALUES (1, ST_GeomFromText('POINT(121.5645 25.0340)', 4326, 'axis-order=long-lat'));

For SRID 4326 (WGS 84, the coordinate system GPS uses), MySQL’s default coordinate order is latitude first. Without 'axis-order=long-lat', 121.5645 is read as a latitude and rejected with an error, because it is outside ±90 degrees.

Pitfalls and gotchas

  • Longitude and latitude order: Redis, Spring’s Point, and GeoJSON put longitude first; coordinates copied from a map app and MySQL’s SRID 4326 put latitude first. Taiwan’s longitude is over 90, so swapping them fails right away with an error; in regions such as Europe and Africa, where both values are within 90, the point is silently stored in the wrong place
  • Querying only the center cell: in the measurements it missed more than half
  • Cells smaller than the radius: 9 cells cannot cover the whole circle. Choose the precision based on the radius and the latitude
  • Crossing the 180th meridian and the polar regions: a hand-written neighbor calculation has to handle longitude wraparound; in production, use a mature library
  • Straight-line distance is not travel distance: a venue within 3 km may be on the other side of a river. Redis also computes distance by treating the Earth as a sphere, with up to 0.5% error; compute billing or delivery fees some other way
  • GEO members do not expire: GEO is a sorted set, and members cannot have their own TTL. Moving objects such as couriers and drivers stay in the key after they go offline. You need a second sorted set scored by the last report time, and a periodic job that finds members that have not reported for too long and removes them from both
  • A single hot key: in Redis Cluster, a key lives on only one node. When moving objects update often (100,000 couriers reporting every 4 seconds is 25,000 writes per second), you can split them into several keys by geohash prefix, at the cost of queries near a boundary having to read several keys and merge the results

Security

  • Distance leaks location (trilateration): showing “1 km away” in “nearby peers” looks harmless, but an attacker can fake their own location, query again and again from different places, and draw circles from three distances to find where they intersect. In the simulation below, the attacker sees only the distances the server returns:

    Trilateration simulation (TrilaterationDemo.java)
    java
    package geo;
    
    import java.util.Random;
    
    /** The attacker can fake their own location at will; the server only returns "how far you are from them". How precisely can that answer alone locate the target? */
    public class TrilaterationDemo {
    
        static final double TARGET_LAT = 25.0418;
        static final double TARGET_LNG = 121.5503;                      // the target's real location, unknown to the attacker
        static final double START_LAT = 25.0340;
        static final double START_LNG = 121.5645;                       // the attacker only knows the target is somewhere near Taipei 101
    
        interface DistanceApi {
            double distanceKm(double lat, double lng);                  // the only thing the attacker can see
        }
    
        static int queries;
    
        public static void main(String[] args) {
            Random random = new Random(7);
            double[] cell = Geohash.bounds(Geohash.encode(TARGET_LAT, TARGET_LNG, 6));
            double snappedLat = (cell[0] + cell[1]) / 2;
            double snappedLng = (cell[2] + cell[3]) / 2;
    
            DistanceApi exact = (lat, lng) -> Math.round(distance(lat, lng, TARGET_LAT, TARGET_LNG) * 1000) / 1000.0;
            DistanceApi rounded = (lat, lng) -> Math.round(distance(lat, lng, TARGET_LAT, TARGET_LNG));
            DistanceApi noisy = (lat, lng) -> distance(lat, lng, TARGET_LAT, TARGET_LNG) + (random.nextDouble() - 0.5);
            DistanceApi snapped = (lat, lng) -> Math.round(distance(lat, lng, snappedLat, snappedLng));
    
            report("exact distance (to the meter)", averagingAttack(exact, 1));
            report("distance rounded to whole km", boundaryAttack(rounded));
            report("±500 m random noise on every query", averagingAttack(noisy, 500));
            report("location snapped to cell center, then rounded", boundaryAttack(snapped));
            System.out.printf("(distance from the real location to the center of its length-6 geohash cell: %.0f m)%n",
                    distance(TARGET_LAT, TARGET_LNG, snappedLat, snappedLng) * 1000);
        }
    
        static void report(String label, double[] guess) {
            System.out.printf("%,5d queries | error %,4.0f m | %s%n",
                    queries, distance(guess[0], guess[1], TARGET_LAT, TARGET_LNG) * 1000, label);
            queries = 0;
        }
    
        /** Query n times from each of three positions and average, then intersect the three circles. */
        static double[] averagingAttack(DistanceApi api, int n) {
            double[][] anchors = {{START_LAT, START_LNG}, {START_LAT + 0.02, START_LNG}, {START_LAT, START_LNG - 0.02}};
            double[] radii = new double[3];
            for (int i = 0; i < 3; i++) {
                double sum = 0;
                for (int k = 0; k < n; k++) {
                    sum += query(api, anchors[i]);
                }
                radii[i] = sum / n;
            }
            return trilaterate(anchors, radii);
        }
    
        /** Move your own position along three directions and binary-search for the point where the answer just changes: that point is exactly k + 0.5 km from the target. */
        static double[] boundaryAttack(DistanceApi api) {
            double[][] centers = new double[3][];
            double[] radii = new double[3];
            for (int i = 0; i < 3; i++) {
                double angle = Math.toRadians(90 + 120 * i);
                double dLat = Math.sin(angle) / 110.574;               // how much latitude and longitude change per km walked
                double dLng = Math.cos(angle) / (111.320 * Math.cos(Math.toRadians(START_LAT)));
                double first = query(api, new double[] {START_LAT, START_LNG});
                double low = 0;
                double high = 0.25;
                while (query(api, new double[] {START_LAT + high * dLat, START_LNG + high * dLng}) == first) {
                    low = high;
                    high += 0.25;
                }
                double changed = query(api, new double[] {START_LAT + high * dLat, START_LNG + high * dLng});
                for (int k = 0; k < 40; k++) {
                    double mid = (low + high) / 2;
                    if (query(api, new double[] {START_LAT + mid * dLat, START_LNG + mid * dLng}) == first) {
                        low = mid;
                    } else {
                        high = mid;
                    }
                }
                centers[i] = new double[] {START_LAT + low * dLat, START_LNG + low * dLng};
                radii[i] = Math.min(first, changed) + 0.5;
            }
            return trilaterate(centers, radii);
        }
    
        static double query(DistanceApi api, double[] position) {
            queries++;
            return api.distanceKm(position[0], position[1]);
        }
    
        /** Within a few km, treat latitude and longitude as plane coordinates (km); subtracting the circle equations pairwise gives a linear system. */
        static double[] trilaterate(double[][] centers, double[] r) {
            double kmPerLng = 111.320 * Math.cos(Math.toRadians(START_LAT));
            double[] x = new double[3];
            double[] y = new double[3];
            for (int i = 0; i < 3; i++) {
                x[i] = (centers[i][1] - START_LNG) * kmPerLng;
                y[i] = (centers[i][0] - START_LAT) * 110.574;
            }
            double a1 = 2 * (x[1] - x[0]);
            double b1 = 2 * (y[1] - y[0]);
            double c1 = r[0] * r[0] - r[1] * r[1] + x[1] * x[1] - x[0] * x[0] + y[1] * y[1] - y[0] * y[0];
            double a2 = 2 * (x[2] - x[0]);
            double b2 = 2 * (y[2] - y[0]);
            double c2 = r[0] * r[0] - r[2] * r[2] + x[2] * x[2] - x[0] * x[0] + y[2] * y[2] - y[0] * y[0];
            double det = a1 * b2 - a2 * b1;
            double px = (c1 * b2 - c2 * b1) / det;
            double py = (a1 * c2 - a2 * c1) / det;
            return new double[] {START_LAT + py / 110.574, START_LNG + px / kmPerLng};
        }
    
        static double distance(double lat1, double lng1, double lat2, double lng2) {
            return Geohash.distanceKm(lat1, lng1, lat2, lng2);
        }
    }
    text
        3 queries | error    3 m | exact distance (to the meter)
      134 queries | error    9 m | distance rounded to whole km
    1,500 queries | error    8 m | ±500 m random noise on every query
      153 queries | error  329 m | location snapped to cell center, then rounded
    (distance from the real location to the center of its length-6 geohash cell: 336 m)
    • Returning the exact distance: 3 queries locate the target to within 3 m
    • Rounding only the output does not help: the attacker moves their own position and finds the point where the answer changes from “1 km” to “2 km”; that point is exactly 1.5 km from the target. 134 queries locate the target to within 9 m
    • Adding random noise to every answer does not help either: query 500 times from the same position and take the average, and the noise cancels out
    • What works is reducing precision before computing: snap the target’s location to the center of a fixed cell, and keep it unchanged while they stay in that cell. The attacker can at best find the cell center, so the error is the 300-plus meters that snapping introduces. Add query rate limits and “impossible travel speed” checks to raise the cost of the boundary search
  • Only people who want to be found can be found: put only learners who have turned on sharing into a dedicated key, and remove them the moment they turn it off (GEO members do not expire on their own). The visibility condition has to hold in the query itself, for the same reason as in the Full-Text Search and Inverted Indexes post; this is another form of BOLA (Part 8)

  • Location is personal data: location history can reveal where someone lives and works. Store only the precision you need, set a retention period, and keep raw coordinates out of logs

  • Client-reported locations can be faked: location-spoofing apps are easy to get, so GPS cannot prove that someone is on site. For on-site check-in at in-person talks, use a QR code on the venue’s screen that changes at a fixed interval instead

When to use it, and when not to

  • geohash column: the data is already in a relational database, you only need nearby search on points, and you do not want to run another system
  • Redis GEO: high query frequency, moving objects, and you can accept sync delay for derived data
  • SPATIAL/PostGIS: you need polygons (districts, delivery zones), routes, or other geographic computation
  • H3: regional statistics and heat analysis
  • Do not use: when you have only a few hundred points (load them all into memory and compute the distances directly); when you need travel distance or arrival time (use a road network and a routing service)

References

Comments